Can't figure out the angle of calculating the tilt using the accelerometer on the iPhone

double = rollingZ  = acceleration.x;
double = rollingX = acceleration.y;

if (rollingZ > 0.0) {
    self.centerCoordinate.inclination = atan(rollingX / rollingZ) + M_PI / 2.0; //LINE 1
else if (rollingZ < 0.0) {
    self.centerCoordinate.inclination = atan(rollingX / rollingZ) - M_PI / 2.0; // LINE 2
else if (rollingX < 0) {
    self.centerCoordinate.inclination = M_PI/2.0; //atan returns a radian
else if (rollingX >= 0) {
    self.centerCoordinate.inclination = 3 * M_PI/2.0;


I'm just trying to fully understand this piece of code. I am looking for building AR apps on iphone and this code has the function of calculating the angle of the device using accelerometer readings.

My understanding is this:

Assuming portrait orientation, if I rotate the device forward, the x-axis of the accelerometer increases towards a negative number of -1.0 (that is, the device is laid flat with the screen facing up). If I tilt the device towards me, the x-axis increases to 1.0 (until the device is firmly facing the ground).

The y-axis changes up and down the axis from -1.0 to 0.0 (0 means the device is horizontal).

Taking some rough readings, say x = 0.5 (angle -45 degrees, tilt of the device relative to me) and y = 0.8. If I plot this on a Cartesian coordinate graph with y (rollX as vertical axis) and x (rollZ as horizontal axis) and draw a line between them, I realize that I can use the backtouch (atan) function to calculate the angle. My confusion comes at line 1. I don't understand why this line adds 90 degrees (in radians) to the calculated angle given by the athan function?

I just can't imagine what is happening on the graph. If anyone could shed some light on this it would be much appreciated.


source to share

1 answer

I suppose these +90 degrees or -90 degrees (in the case of negative pitch Z) are added to make extensive use of the tilt value of the Polar coordinate system with an angle between -180 and 180 degrees. Assuming you have a Z line projecting upward when you look at the device screen and a Z line looking at you from the screen, the computation above the tree gives you the angle between the screen plane and the horizontal plane.

Suppose the acceleration value is positive when it is "inside" the device:

1) The device is upright, we have rollZ = 1, rollX = 0. The code returns 90 degrees.

2) The device is tilted towards the user. Let rollZ be 0.7 and rollX -0.7. This will give us a 45 degree angle.

3) , rollZ = -1 rollX = 0, -90 .


All Articles