Skip to content

[Feature] Basic IMU heading support. Feedback wanted! #989

Closed

Description

@laurensvalk

Update: all functionality is now available for use via https://beta.pybricks.com/

The links and functionality described below is outdated and should not be used anymore.


Is your feature request related to a problem? Please describe.

We get a lot of requests for gyro support. While full 3D attitude estimation or heading in arbitrary reference frames is still a long way off, there is perhaps something we can do to start with that works for certain use cases.

In this case, I am talking about the use case of drive bases (FLL/WRO), where the hub is flat (parallel to a horizontal table) most of the time.

We want your help to test it! (Preparation step)

Download this experimental firmware:

Installing it works just like installing Pybricks normally. But on the hub selection page, you now click Advanced to select the zip file you just downloaded:

image

We want your help to test it! (Question 1)

For the exciting stuff, skip to part 2. But we'd still like to get your feedback on part 1 :)

We'd love to get your help to pick certain sensible defaults so the gyro works for everyone. Please run the program below and read through the explanations in the comments. Increase the two noise values until you think it works well enough under all expected conditions.

Once we've settled on good values, others should not need to worry about it (and we'll remove this debug method).

from pybricks.hubs import PrimeHub
from pybricks.parameters import Color
from pybricks.tools import wait

hub = PrimeHub()

#
# FEEDBACK WANTED, Question 1:
#
# In the program below, we make the light turn green when
# the hub sits stationary for a while. It should
# turn red immediately on movement. When the light is green,
# the hub is automatically re-calibrating the gyro.
#
# We define stationary as the "raw values not changing much".
# "Not much" is defined as the sensor values not changing above
# a selected threshold value that we have to pick.
#
# Lower values are "better" because this makes the hub
# recalibrate only when it's really-really-really still.
#
# But it shouldn't be too low, or the robot will never get
# "still enough" for the light to turn green!
# 
# We still want this to work when students are jumping up and
# down next to the competition table...
#
#
#
# So in short: What is the lowest we can go for both values below, while 
# ensuring the light still turns green after one second of not touching it?
#
# Can you test this in the school cafeteria, etc? :-)
#
hub.imu.debug(gyro_noise=20, accelerometer_noise=100)

while True:
    if hub.imu.stationary():
        hub.light.on(Color.GREEN)
    else:
        hub.light.on(Color.RED)

We want your help to test it! (Question 2)
Now for the exciting part!

from pybricks.hubs import PrimeHub
from pybricks.parameters import Color
from pybricks.tools import wait

hub = PrimeHub()

hub.imu.debug(gyro_noise=20, accelerometer_noise=100)

while True:

    if hub.imu.stationary():
        hub.light.on(Color.GREEN)
    else:
        hub.light.on(Color.RED)

    # Get heading.
    #
    # FEEDBACK WANTED, Question 2: Is this good enough? :-)
    #
    heading = hub.imu.heading()

    # Display heading on the LED matrix.
    hub.display.number(round(heading))

    # Print heading and wait a moment to we don't print so much.
    print("{:.1f}".format(heading))
    wait(25)

    # You can easily reset the heading to arbitrary values.
    # No special wait operations are required here. Just reset and go.
    if hub.buttons.pressed():
        hub.imu.reset_heading(0)

NB: Positive is counterclockwise

A positive angle is a counterclockwise turn. This is consistent with most engineering definitions.

The DriveBase defaults to positive for clockwise to be similar to the LEGO apps. We will add an option to flip this. See the drive base examples further down in this thread.

That way, your drive base direction and gyro values will match, saving you some headaches.

NB: For now it only works in horizontal orientation

We have not yet implemented 3D attitude estimation. So if you lift the robot from the table and put it back, it won't give the same value.

It is only implemented for the default orientation, where the hub is parallel to the table.

This might not be so bad; after all, the EV3 also had just one gyro axis. But we'd love to get your thoughts.

Activity

  1. added
    topic: imu
    on Mar 16, 2023
  2. laurensvalk commented on Mar 16, 2023

    @laurensvalk
    MemberAuthor
  3. TheWendyPower commented on Mar 16, 2023

    @TheWendyPower

    This is exactly what the team needs to use their turn-by-gyro function. Here is what it looks like in their LEGO code:

    def right_turn(angle):
        p0w.motion_sensor.reset_yaw_angle()
        motor_pair.start(speed=10,steering=100)
        wait_until(p0w.motion_sensor.get_yaw_angle,greater_than_or_equal_to,int(angle))
        motor_pair.stop()
        wait_for_seconds(.5)
    
    def left_turn(angle):
        p0w.motion_sensor.reset_yaw_angle()
        motor_pair.start(speed= 10, steering= -100)
        wait_until(p0w.motion_sensor.get_yaw_angle, less_than_or_equal_to, int(angle))
        motor_pair.stop()
        wait_for_seconds(.5)
    

    We are more than happy to test imu.heading() and give you some feedback on it.

  4. laurensvalk commented on Mar 16, 2023

    @laurensvalk
    MemberAuthor

    Taking things a step further, we can optionally let users use the gyro with the existing drivebase methods. (This is not included in the build above yet, but it works quite well).

    For example, when driving straight or turning, you'd get automatic corrections like this:

    VID_20230316_141516.mp4

    We could add a keyword argument use_gyro to the DriveBase class for this.

    It would probably default to False, but setting it to True would enable the behavior above.

    We could also accept a callable like use_gyro=my_gyro_angle_function so all of this can also work with an external gyro or compass, as was the case for EV3 and NXT.

  5. TheWendyPower commented on Mar 16, 2023

    @TheWendyPower

    YES!!!!! We were using a drive straight function as well. Between the two it would give the kids the functionality they had before, plus all the additional stuff Pybricks lets them work with.

  6. added
    software: pybricks-micropython
    on Mar 16, 2023
  7. laurensvalk commented on Mar 16, 2023

    @laurensvalk
    MemberAuthor

    The download links above have now been updated to include the drivebase-with-gyro feature. You can use it as shown below.

    from pybricks.pupdevices import Motor
    from pybricks.parameters import Port, Direction
    from pybricks.robotics import DriveBase
    
    # Initialize both motors. In this example, the motor on the
    # left must turn counterclockwise to make the robot go forward.
    left_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE)
    right_motor = Motor(Port.B)
    
    # Initialize the drive base. In this example, the wheel diameter is 56 mm.
    # The distance between the two wheel-ground contact points is 112 mm.
    drive_base = DriveBase(
        left_motor,
        right_motor,
        wheel_diameter=56,
        axle_track=112,
        positive_direction=Direction.COUNTERCLOCKWISE, 
        use_gyro=True)
    
    # Drive in a straight line and back again a few times.
    for i in range(4):
    
        # Drive forward for 500 mm.
        drive_base.straight(500)
    
        # Turn around counterclockwise.
        drive_base.turn(180)
    
        # Drive forward for 500 mm.
        drive_base.straight(500)
    
        # Turn around clockwise.
        drive_base.turn(-180)
  8. laurensvalk commented on Mar 16, 2023

    @laurensvalk
    MemberAuthor

    OK, this is fun. 😄 This is the almost the same program as above but with higher speed/acceleration:

    drive_base.settings(
        straight_speed=500,
        straight_acceleration=1000,
        turn_rate=500,
        turn_acceleration=2000
    )
    VID_20230316_205400.mp4
  9. TheWendyPower commented on Mar 16, 2023

    @TheWendyPower

    @laurensvalk I LOVE how accurate and fast that is moving!!!!

    I updated the firmware to the latest one (the gyro worked grate in the previous one BTW), and added the arguments to DriveBase:

    positive_direction=Direction.CLOCKWISE, 
    use_gyro=True)
    

    However, I get ValueError: Invalid argument do I need a different version of the Pybricks App too?

    Here is the full block:

    left_motor = Motor(Port.B,Direction.COUNTERCLOCKWISE)
    right_motor = Motor(Port.C,Direction.CLOCKWISE)
    motor_pair = DriveBase(
        left_motor=left_motor,
        right_motor=right_motor,
        wheel_diameter=87.56,
        axle_track=111.46,
        positive_direction=Direction.CLOCKWISE,
        use_gyro=True)
    
  10. laurensvalk commented on Mar 16, 2023

    @laurensvalk
    MemberAuthor

    You have to use the DriveBase with positive_direction=Direction.COUNTERCLOCKWISE to match the gyro for now. See an example above.

    We'll enable both directions both ways at a later stage. For now this restriction made it easier to implement while we work out what to do with the gyro (not just multiple directions, but also multiple axes, etc.)

  11. TheWendyPower commented on Mar 16, 2023

    @TheWendyPower

    Makes sense. When I made the functions earlier that used imu.heading() I cheated with

    gyro_angle = P0W.imu.heading()*-1

    to reverse it for me in the functions.

  12. BertLindeman commented on Mar 17, 2023

    @BertLindeman

    We want your help to test it! (Question 1)

    I am no longer at school (retired a decade) but tried anyway.
    Used both a Robot Inventor hub and a Prime hub.
    They are the same, but small internal differences might be there.

    To test I placed the hubs on the armrest of my chair.
    Your defaults work well. I could go down to gyro_noise=18, accelerometer_noise=75 on the Prime Hub.
    Much lower caused the led to hardly show green. Even if I did not sit in my chair.
    Feels like the RobotInventor hub is a bit more sensitive than the prime hub.
    But no scientific proof for that.
    The RobotInventor hub would react similar to the prime hub at gyro_noise=19, accelerometer_noise=80

    This is fun-stuff.

    Bert

  13. laurensvalk commented on Mar 17, 2023

    @laurensvalk
    MemberAuthor

    I am no longer at school (retired a decade) but tried anyway.

    Jumping in excitement also counts as simulating the ambient acceleration/vibration of an FLL final 😄

    Thanks for testing Bert!

    As the converse challenge, how high you can make them such that it still always shows red when you try to move it?

  14. 26 remaining items

  15. johnscary-ev3 commented on Apr 1, 2023

    @johnscary-ev3

    @laurensvalk
    I have been working to integrate the new heading() method into my Blast Robot.
    It is working fine but I also use the tilt() method so I can get pitch and roll to check if robot has fallen over.
    This used to work ok giving me pitch and roll ~(0, 0) unless I tilt the robot.
    Now I am getting ~ (0, -179). If I turn the robot to stand on its head I get (0, 0) again.
    Seems like something has changed with respect to roll or something.
    Below is the heading() test program with pitch, roll added for Blast.
    Any comments?

    from pybricks.hubs import PrimeHub
    from pybricks.parameters import Color
    from pybricks.tools import wait
    from pybricks.geometry import Axis
    
    #hub
    #This is how the hub is mounted in BLAST in the 51515 set.
    hub = PrimeHub(top_side=Axis.X, front_side=-Axis.Y)
    
    hub.imu.debug(gyro_noise=20, accelerometer_noise=100)
    
    while True:
    
       if hub.imu.stationary():
           hub.light.on(Color.GREEN)
       else:
           hub.light.on(Color.RED)
    
       # Get heading.
       heading = hub.imu.heading()
    
       # Get Pitch and Roll.
       pitch, roll = hub.imu.tilt()
    
       # Display heading on the LED matrix.
       hub.display.number(round(heading))
    
       # Print heading and wait a moment to we don't print so much.
       print("h= ","{:.1f}".format(heading),"p= ", "{:.1f}".format(pitch),"r= ", "{:.1f}".format(roll))
       wait(100)
    
       # You can easily reset the heading to arbitrary values.
       # No special wait operations are required here. Just reset and go.
       if hub.buttons.pressed():
           hub.imu.reset_heading(0)
    
    Initial Data after starting robot with no movment
    h=  0.0 p=  4.0 r=  -179.0
    h=  0.0 p=  4.0 r=  -179.0
    h=  -0.0 p=  4.0 r=  -179.0
    h=  0.0 p=  4.0 r=  -179.0
    h=  -0.0 p=  4.0 r=  -179.0
    h=  0.0 p=  4.0 r=  -179.0
    h=  -0.0 p=  4.0 r=  -179.0
    h=  -0.0 p=  4.0 r=  -179.0
    
  16. BertLindeman commented on Apr 1, 2023

    @BertLindeman

    Below is the heading() test program with pitch, roll added for Blast.

    I can confirm.
    Running this on my Spike Prime hub I see:

    ('primehub', '3.3.0b2', 'v3.3.0b2-78-g86f27b429 on 2023-03-21')
    h=    0.0 p=    0.0 r=  179.0
    h=    0.0 p=    0.0 r=  179.0
    h=    0.0 p=    0.0 r=  179.0
    h=    0.0 p=    0.0 r=  179.0
    h=    0.0 p=    0.0 r=  179.0
    

    So +179 not -179.

    Running (older firmware) on the inventor hub:

    ('primehub', '3.3.0b2', 'v3.3.0b2-49-g0f343064 on 2023-03-16')
    h=   -0.0 p=    1.0 r=    0.0
    h=    0.0 p=    1.0 r=    0.0
    h=   -0.0 p=    1.0 r=    0.0
    h=   -0.0 p=    1.0 r=    0.0
    h=   -0.0 p=    1.0 r=    0.0
    

    [EDIT] updated inventor hub output

  17. laurensvalk commented on Apr 1, 2023

    @laurensvalk
    MemberAuthor

    Thanks @johnscary-ev3 and @BertLindeman! Proper gyro+accelerometer support is currently in progress.

    This issue was opened mainly to get some feedback on the heading concept. Since the response was so positive, we're now in the process of getting this merged in properly (without breaking the accelerometer 😉)

    If you can't wait, you can follow our progress in pybricks/pybricks-micropython#156.

    We'll keep this issue open for now, and ask everyone to move over to the public beta once we've released it :)

  18. johnscary-ev3 commented on Apr 3, 2023

    @johnscary-ev3

    @laurensvalk
    I downloaded a more recent build #2646 and the roll is working ok again. Thanks.

    By the way, I have a comment about the new calls being called "heading".
    From what I can tell heading should be a number from 0 - 360 dg like on a compass.
    Seems to me what we are calling heading is more like "yaw angle".
    So, I wrote a function to get compass style heading angle from yaw angle.
    See code below. Any comment on this naming? Could be confusing for users.

    from pybricks.hubs import PrimeHub
    from pybricks.parameters import Color
    from pybricks.tools import wait
    from pybricks.geometry import Axis
    
    # Get Heading Angle from Yaw Angle 
    def get_heading_angle(yaw_angle):
        if yaw_angle <= 0:
            heading_angle = (-yaw_angle % 360) 
        else:
            heading_angle = 360-(yaw_angle % 360)
        return(heading_angle)
    
    #hub = PrimeHub()
    # For example, this is how the hub is mounted in BLAST in the 51515 set.
    hub = PrimeHub(top_side=Axis.X, front_side=-Axis.Y)
    
    
    #hub.imu.debug(gyro_noise=20, accelerometer_noise=100)
    
    while True:
    
        if hub.imu.stationary():
            hub.light.on(Color.GREEN)
        else:
            hub.light.on(Color.RED)
    
        # Get heading.
        #
        # FEEDBACK WANTED, Question 2: Is this good enough? :-)
        #
        yaw_angle = hub.imu.heading()
        heading_angle = get_heading_angle(yaw_angle)
    
        # Display heading on the LED matrix.
        hub.display.number(round(yaw_angle))
    
        # Print heading and wait a moment to we don't print so much.
        print('yaw_angle= ',"{:.1f}".format(yaw_angle), 'heading_angle= ',"{:.1f}".format(heading_angle))
        wait(25)
    
        # You can easily reset the heading to arbitrary values.
        # No special wait operations are required here. Just reset and go.
        if hub.buttons.pressed():
            hub.imu.reset_heading(0)
  19. Xylar52 commented on Apr 5, 2023

    @Xylar52

    Can you share a code sample and a video that reproduces that behavior? You can just attach the video here.

    from pybricks.hubs import PrimeHub
    from pybricks.pupdevices import Motor, ColorSensor, UltrasonicSensor, ForceSensor,
    from pybricks.parameters import Button, Color, Direction, Port, Side, Stop, Icon
    from pybricks.robotics import DriveBase
    from pybricks.tools import wait, StopWatch
    
    hub = PrimeHub()
    motorl = Motor(Port.A, Direction.COUNTERCLOCKWISE)
    motorr = Motor(Port.B)
    motorl.control.limits(acceleration=[2000, 400])
    motorr.control.limits(acceleration=[2000, 400])
    drive_base = DriveBase(
        left_motor=motorl, 
        right_motor=motorr, 
        wheel_diameter=55, 
        axle_track=143,
        positive_direction=Direction.COUNTERCLOCKWISE,
        use_gyro=True)
    
    drive_base.settings(
        straight_speed=500,
        straight_acceleration=1000,
        turn_acceleration=2000,
        turn_rate=500
        )
    
    while True:
        drive_base.straight(1000, then=Stop.NONE)

    This code concludes in this :

    20230405_133825.mp4

    However, if you delete the straight speed in settings :

    from pybricks.hubs import PrimeHub
    from pybricks.pupdevices import Motor, ColorSensor, UltrasonicSensor, ForceSensor,
    from pybricks.parameters import Button, Color, Direction, Port, Side, Stop, Icon
    from pybricks.robotics import DriveBase
    from pybricks.tools import wait, StopWatch
    
    hub = PrimeHub()
    motorl = Motor(Port.A, Direction.COUNTERCLOCKWISE)
    motorr = Motor(Port.B)
    motorl.control.limits(acceleration=[2000, 400])
    motorr.control.limits(acceleration=[2000, 400])
    drive_base = DriveBase(
        left_motor=motorl, 
        right_motor=motorr, 
        wheel_diameter=55, 
        axle_track=143,
        positive_direction=Direction.COUNTERCLOCKWISE,
        use_gyro=True)
    
    drive_base.settings(
        straight_acceleration=1000,
        turn_acceleration=2000,
        turn_rate=500
        )
    
    while True:
        drive_base.straight(1000, then=Stop.NONE)`

    It concludes in the normal behaviour :

    20230405_133902.mp4
  20. Xylar52 commented on Apr 15, 2023

    @Xylar52

    Any news about my issue ?

  21. laurensvalk commented on Apr 15, 2023

    @laurensvalk
    MemberAuthor

    Thank you, I was able to reproduce it. I will open a separate ticket for this.

  22. BrBarry commented on Apr 21, 2023

    @BrBarry

    OK, I have tried most of the code samples about, and for the life of could not get the robot to turn square (90, 180, 270, 360)
    I assumed it was our RoboCup Junior competition robot configuration (the hub is at the back and sideways) but still 'Top Up'.

    Removed the Spike Prime hub and run the Yaw/heading output code against a square edge, rotating through all angles. Still out, and the same on 2 other hubs.

    I'm getting an accumulated error in my heading values of by an average -0.975 per degree out, on all our Spike Prime Hubs (3).

    One sample below

    Screenshot 2023-04-22 010542

  23. laurensvalk commented on Apr 21, 2023

    @laurensvalk
    MemberAuthor

    Thanks @BrBarry! We have since made considerable improvements that should get it a lot closer to 360 degrees.

    We will be publishing a proper beta release next week (i.e. not hidden here in a GitHub discussion). We didn't publish anything this week because the FLL finals are happening right now, and we didn't want any teams to run into accidental changes during their finals.

    Even after these improvements, there will still be some variations between hubs. If needed, we might address that with a calibration routine that people can run on their hubs.

  24. laurensvalk commented on Apr 25, 2023

    @laurensvalk
    MemberAuthor

    All functionality discussed here is now available via https://beta.pybricks.com/.

    Just install the firmware with the usual steps; no custom files required.

    Some implementation details have changed based on your feedback. Please consult the documentation in app via the link above for using the gyro and drive bases. If you've been using the experimental versions in this thread, here are the most important updates:

    • There is now a GyroDriveBase class that acts as a drop-in replacement for the regular DriveBase. No need to set special settings as in this thread.
    • The direction convention for heading is now positive-clockwise based on user feedback. This also makes the GyroDriveBase easier to use since everything works the same way.
    • The threshold setters have been updated. Based on comments from e.g. @JuliaFiMSFT we have decided to keep them accessible for users. See the documentation of the settings() method.

    Thanks everyone for your feedback! We will now archive this issue. Please feel free to open new discussions and issues if anything comes up.

    Also feel free to open a discussion if it "just works". That helps us too 😄

  25. added theissue type on Aug 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    software: pybricks-micropythontopic: imu

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions