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:
- (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.
- (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