Advertisement
shaggys

pybricks_heading_tracker

Nov 14th, 2024 (edited)
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | Source Code | 0 0
  1. from pybricks.hubs import InventorHub
  2. from pybricks.parameters import Color, Axis, Port, Direction
  3. from pybricks.tools import wait, StopWatch, run_task, multitask
  4. from pybricks.pupdevices import Motor
  5. from pybricks.robotics import DriveBase
  6.  
  7.  
  8. hub = InventorHub()
  9. time = StopWatch()
  10. left = Motor(Port.A, Direction.COUNTERCLOCKWISE)
  11. right = Motor(Port.B, Direction.CLOCKWISE)
  12. drive = DriveBase(left, right, 55, 125)
  13. def time_s():
  14.     return time.time()/1000
  15.  
  16.  
  17.  
  18. def calc_head_with_bias(angular_velocity, time_delta, bias, current_heading = 0):
  19.     corrected_velocoty = angular_velocity - bias
  20.  
  21.     heading_change = corrected_velocoty * time_delta
  22.     new_heading = current_heading + heading_change
  23.     return new_heading
  24. class track_heading:
  25.     def __init__(self):
  26.         self.value = 0.0
  27.  
  28.     async def start(self, bias = 0.0, start_heading=0.0):
  29.         self.value = start_heading
  30.         last_time = time_s()
  31.         hub.light.on(Color.GREEN)
  32.         while True:
  33.             current_time = time_s()
  34.             time_delta = current_time - last_time
  35.             angular_velocity = hub.imu.angular_velocity(-Axis.Z)
  36.             self.value = calc_head_with_bias(angular_velocity, time_delta, bias, self.value)
  37.             last_time = current_time
  38.             hub.display.number(self.value)
  39.             await wait(10)
  40.            
  41.     def current(self):
  42.         return self.value
  43.  
  44.  
  45. head = track_heading()
  46. async def track(bias = 0.0, start_heading = 0.0):
  47.     hub.light.on(Color.GREEN)
  48.     await head.start(bias, start_heading)
  49.  
  50.  
  51.  
  52. async def main():
  53.     print("hi")
  54.     track()
  55.     wait(100)
  56.     drive.straight(1000)
  57. run_task(main())
  58.  
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement