3

How can I calculate the pitch of a micro bit accelerometer as a full range, i.e. from -Pi to Pi radians (the same as -180 to 180 degrees)?

Here is my existing micro python code:

while True:
    x = accelerometer.get_x()/1024
    y = accelerometer.get_y()/1024
    z = accelerometer.get_z()/1024
    roll = math.pi-(math.atan2(x, z)%(math.pi*2))
    pitch = math.atan2(-y, math.sqrt(x*x + z*z))
    print('{roll:'+str(roll)+',pitch:'+str(pitch)+'}')

The behaviour I see is:

  1. (Correct for me) Rolling the micro bit goes from 0 up to Pi to the right (until upside down) and from 0 down to -Pi rolling to the left (until upside down). At upside down, the radians will flip between Pi and -Pi.
  2. (incorrect for me) Pitching the micro bit forwards goes from 0 to Pi/2 (at 90 degrees) and then back down to 0 (upside down), pitching the micro bit backwards similarly goes from 0 down to -Pi/2 (at 90 degrees) then back up to 0 (when upside down).

I am looking for the pitch to go forwards from 0 to Pi (when upside down) and backwards from 0 to -Pi (when upside down).

Thank you in advance

Andy

AndyS
  • 725
  • 7
  • 17
  • 1
    Roll, pitch, and yaw form an Euler rotation sequence. The two outer angles in an Euler rotation sequence (e.g., roll and yaw in the case of roll/pitch/yaw or yaw/pitch/roll sequences) have a range of 2*pi radians, or 360 degrees. The central angle (pitch in this case) only has a range of pi radians, or 180 degrees. – David Hammen Oct 23 '17 at 13:08
  • Yes - but I'm trying to report the two angles separately - I don't use them at the same time. (I realise this includes redundancy in the pitch and roll). I think I can put: `pitch = math.pi-(math.atan2(y, z)%(math.pi*2))` This will work for the micro bit - if it can only pitch and roll and not yaw - which will suit my purpose. – AndyS Oct 23 '17 at 13:18
  • Actually - for +ve forwards and negative backwards, I need `pitch =(math.atan2(y, z)%(math.pi*2))-math.pi` – AndyS Oct 23 '17 at 13:26

0 Answers0