**Calculate Everything From Iphone’s**

**Accelerometer And Magnetometer Sensors**

**ABSTRACT**

The orientation of an iPhone as a rigid body can be completely characterized utilizing data extracted from the iPhones accelerometers and magnetometers.

New spreadsheet available (6 Mar 2013: Now combines gyrometer, to calculate accelerations, speeds, displacements, pitch, roll without being restricted to static conditions described below.

Click Here for free OpenOffice Calc (zipped) spreadsheet. Click Here for Excel (zipped) spreadsheet. See new article for above spreadsheets: Click Here.

# Introduction

The following will explain how to calculate various quantities from the iPhone’s accelerometer and magnetometer sensor data. Such as: Pitch, roll, a set of Euler angles, 3D rotation matrices, rotation axis and angle, quaternions, and the orientation of each of the Body Frame x, y, z axes from magnetic north. These calculations apply only for “static” conditions, that is, the mobile device, a rigid body, is at rest or in uniform rectilinear motion. No outside forces such as accelerations, and non-ambient Earth magnetic fields exerted on the mobile device during data collection. However, under none static conditions, useful actual accelerations that the iPhone experiences can be calculated. That is, we can subtract the effect of gravity from net accelerometer values (after applying calibration) under certain conditions. Namely, using a static initial reference state to subtract from net accelerations.

This publication should be considered a continuation of an earlier related publication titled Calibration Of iPhone Accelerometers. That publication describes how using a spreadsheet we may calibrate the mobile device’s accelerometers to correct inherent errors of accelerometer values that are often observed for a mobile device under “static” conditions. Hence, it will be assumed that the above calibration with the resulting linear equations for correcting accelerometer values from each axis has been performed. These calculations that are detailed here using the accelerometer and magnetometer readings are also performed with an Excel spreadsheet. One can use a single Excel workbook for calibration and the analysis for the quantities that will be calculated in the following. We will be describing calculations with extensive referencing the columns on this workbook. Familiarity with using Excel is assumed. It is recommended that you save the downloaded Excel workbook as a master and work with a copy.

To obtain accelerometer and magnetometer data from an iPhone, an app that collects data from the iPhone’s sensors is needed, and should provide access to the data via a file of some type. Data formatted as comma separated values (CVS) is perfect as they can easily be imported to a spreadsheet. Apps that collect and output data from all the sensors can be found in the Apple iTunes App Store.

# Procedure

Before proceeding we should understand what the orientation of the iPhone’s three axes are, see figure 1:

Figure 1

These axes should be considered as fixed to the mobile device’s Body. Hence will be referred to as the Body Frame coordinate axes. Note the +Z-axis is pointing away from the front and is always perpendicular to the face of the iPhone. The X-axis is along the short length and the Y-axis along the long length. The +Y-axis is toward the “on” button on the top right of the iPhone. The orientation of the axes follows the Right-Hand Rule. As these axes are to be fixed to the mobile devices Body, rotating the device will rotate the axes to maintain their configuration with respect to the devices shape as per figure 1.

A second coordinate axes are define as follows: An x-axis that always points to magnetic north and is contained in our horizontal plane. A y-axis that always points east and also on our horizontal plane, and a z-axis that always points down and of course is perpendicular to our horizontal plane. This coordinate system is defined as the fixed Earth Frame coordinate axes. Note that the orientation of the axes of the Earth Frame also follows the Right-Hand Rule.

An Excel workbook is provided that not only calculates the linear calibration equations that can be used to correct accelerometer data, but also contains the calculations that we can obtain from the accelerometer and magnetometer measurements. The Excel workbook has been automated as best as I could. So data can be entered and calculations are performed automatically. Take care not to delete or clear cells that have equations. Download and save a master, always work on a copy. Use as you wish. In the Sensor Data worksheet up to 6990 rows of data can be entered for automated results. The charts in the Analysis worksheet are also automated. However, a user should change the charts axis scale to better show the data.

1. Proceed by collecting or capturing the mobile device’s sensor data to a file with the app of your choice. Remember to collect data under “static” conditions, at rest or in uniform rectilinear motion. OK, due the best you can, relatively small accelerations will not be problematic. However, if you are primarily interested in obtaining actual accelerations (with the effect of gravity removed) proceed, the actual accelerations are calculated in the Analysis worksheet.

2. Transfer or import data to a spreadsheet. In the Excel workbook provided look at worksheet named: Sensor Data. Note the column headings, they describe the data collected from the sensors that are used for our calculations. You may paste your data starting on row 2, and in the corresponding column. For each column clear or delete the content in columns A and B below row 1 before pasting your data. If you use this workbook you must paste the data in exactly the corresponding column, otherwise the results in the Analysis worksheet will be incorrect.

3. The accelerometer and magnetometer values are measurements performed along the Body Frame axes. Therefore, represent vectors, which means they have a magnitude and a direction. As opposed to a scalar which only has magnitude. We proceed by normalizing our two vectors. We will call the accelerometer vector

**G**, and the magnetometer vector**B**. It is assumed that the accelerometer measurements have been corrected with the calibration equations. The vector**G**should be pointing straight down. We can check for that after we build our rotation matrices. In the**Analysis**sheet of the workbook columns E, F, G performs the calculations for correcting the raw accelerometer values. The linear calibration equations one for each axis are used. Columns J, K, L and N, O, P perform the calculation on the components for normalizing the accelerometer and magnetometer vectors. The unit vectors are designated as**uG**and**uB**. Since the unit vector**uG**always points downward (under static conditions) we can define it as the fixed Earth Frame z-axis.
Down =

**uG**= Earth Frame +z-axis
4. We proceed using unit vectors (normalizing), and calculate the vector cross product of our unit vectors

**uG X uB**. Note that the accelerometer and magnetometer vectors should not move under static conditions as we rotate our Body Frame. Though the components measured along the Body Frame axes change, their magnitudes and actual directions are constant. This author has noticed that the magnitude of the measured magnetic vector seems to change with Body Frame rotations for my iPhone; hence it is likely that the magnetometers also need to be calibrated. Possibly a more difficult task than calibrating the accelerometers. However, will proceed with what we have. We define our Earth Frame +z-axis as down and equal to**uG**. Since**uG**always points down and therefore is perpendicular to our horizontal plane (under static conditions), then**uG X uB**is perpendicular to**uG**and**uB**, and is always a vector on the horizontal plane. On a compass held horizontally you can observe that East is always 90 deg (perpendicular) clockwise from magnetic North. Which tells us that the vector cross product**uG X uB**always points to East on the horizontal plane. We then define our Earth Frame +y-axis pointing East as the vector cross product**uG X uB**. We will call the vector**E**(for East) =

**uG X uB**= Earth Frame +y-axis.

This

**E**vector also needs to be normalized and becomes unit vector**uE**with components uEx, uEy, and uEz. These calculations are performed in columns R thru Y on the Analysis sheet.
5. So far we have defined the Earth Frame z-axis as pointing down along

**uG**, and the Earth Frame y-axis pointing East along**uE**. We can now define the Earth Frame x-axis as follows, the vector cross product**uE X uG**. Since**uE X uG**is perpendicular to both**E**(Earth Frame +y-axis) and**G**(Earth Frame +z-axis) it also resides on the horizontal plane. Since North is always perpendicular (90 deg) counter clockwise from East, our Earth Frame +x-axis always points to earth’s magnetic North, we have the vector**N**(for North) =

**uE X uG = (**= Earth Frame +x-axis.

**uG X uB**) X uG
Note that we used the BAC –CAB rule to perform the triple vector cross products. The unit vector pointing to magnetic north,

**uN**, is calculated in columns AF thru FH. Then we now have our two coordinate frames. The Body Frame’s unit vector coordinate values are, for the X-axis, (+1, 0, 0); for the Y-axis, (0, +1, 0); and for the Z-axis, (0, 0, +1). In the Body Frame coordinates, the unit vectors of the Earth Frame axes are, for the x-axis, uNx =**(uE X uG)**x**= [(**x; for the y-axis, uNy =**uG X uB**) X uG]**(uE X uG)**y**= [(****y, and similarly for the z-axis, uNz, see columns AF thru FH. As a convention the two coordinate systems are differentiated by using Capital X, Y, and Z for the Body Frame, and small x, y, z for the Earth Frame, see figure 2. The figure contains other entities that will be discussed later. The purple oval represents the horizontal plane and contains the Earth Frame x and y axes, and the Earth Frame z-axis is shown pointing down. The blue oval represents the plane formed by the X and Y axes of the Body Frame.****uG X uB**) X uG]
Figure 2

6. At this time we can also calculate the pitch and roll angles. We define the pitch as the angle the Body Frame’s +X-axis makes with the horizontal plane. The roll we define as the angle the Body Frame’s +Y-axis makes with the horizontal plane. The roll results from a positive rotation about the Body Frame X-axis, and pitch results from a positive rotation about the Y-axis. Positive rotations are defined by the Right-Hand Rule. If the Body Frame X-axis or Y-axis are pointing above the horizontal plane they are positive value, pointing below the horizontal plane they are negative. Note that rotations about the Body Frame’s X and Y axes also rotates the Body Frame’s Z-axis. The Earth Frame +z-axis always points downward and was defined earlier as the unit vector

**uG**, which is measured by the accelerometers using the Body Frame coordinate system. Hence using the vector dot product of the Body Frame X-axis, (+1, 0, 0) with**uG**we get the pitch as the angle
This is obtained in column BC. Typically trigonometric functions are performed with angles defined in radians, hence we multiply radians by 180 / pi to convert to degree’s. We may also calculate the pitch with the following equation

and multiply by 180 / pi to convert to degree. This calculation is shown in column BD.

For roll, performing the dot product of (0, +1, 0) with

**uG**we get
or

and multiply by 180 / pi to convert to degree. A minus sign is used on the calculation to preserve the convention that pitch and roll are positive if the +X-axis, and +Y-axis are above the horizontal plane, and negative if they are below the horizontal. This are shown in columns BE and BF respectively. Recall from earlier that we have specified that measurements be performed under “static” conditions, at rest or uniform rectilinear motion. You can see that for non-uniform motion the measured accelerometer readings would not correspond to a vector pointing downward with magnitude 1g, our

**uG**vector. Therefore the above equations would not be valid. See figure 3.
Figure 3

Accelerations are vectors (they have magnitude and direction); therefore vector operations can be applied.

**G**is our static acceleration,**A**is an acceleration applied to our Body Frame, the iPhone, by an outside force. The accelerometers always measure the**Net Acceleration**as shown in figure 3. Since the net acceleration can be in any direction unless**A**is zero, and greater than 1g, all of the above calculations would be incorrect for our definitions. To perform the above meaningful calculations by our definitions, we must subtract the applied vector acceleration**A**from our measured Net Acceleration. See Section 11 below for how to extract applied accelerations from the net measured accelerations.
7. Next, we proceed with projecting vectors unto the horizontal plane defined by the Earth Frame unit vectors

**uN**and**uE**, which point North and East respectively. We can project the unit vectors of the Body Frame coordinate axes unto the horizontal plane. Projecting the Body Frame X-axis unit vector, (+1, 0, 0) unto the horizontal plane is performed by using the vector dot product of (+1, 0, 0) with**uN**and then with**uE**in Body Frame coordinates. These dot products gives uNx and uEx in columns AF and W respectively, as the components of the Body Frame X-axis unit vector in the horizontal plane, we then have (uNx, uEx). From this we can calculate the orientation of the Body Frame X-axis unit vector from magnetic North on the horizontal plane. We use the function MOD**[**360 + ATAN2(uNx, uEx), 360**]**; this result is performed in column BJ. Similarly, projecting the Body Frame’s Y-axis unit vector (0, +1, 0) unto the horizontal plane using the vector dot product of (0, +1, 0) with**uN**and then with**uE**in Body in Body Frame coordinates, we get the orientation of the Y-axis from magnetic North in the horizontal plane as MOD**[**360 + ATAN2(uNy, uEy), 360**]**. Again, performing the above projection calculations for the Body Frame Z-axis (0, 0, +1), we obtain the orientation of the Z-axis from magnetic North. All results are shown in columns BH thru BJ.**Note**: The orientation of the Y-axis (Body Frame) from magnetic North, actually provides the heading as would be shown on a compass and can be compared to the heading values provided as data from the iPhone, see figure 4.

Figure 4

Light blue is the magnetic heading data obtained from the iPhone, and the dark blue is the heading calculated as the orientation of the Body Frame’s +Y-axis from magnetic North, as

In calculating the heading from the Body Frame’s +Y-axis orientation from magnetic North on the horizontal plane, we encounter a special condition, namely, when the Roll approaches 90 degrees. That is, the +Y-axis approaches being perpendicular to the horizontal plane, up or down; therefore uNy and uEy become very small approaching zero. Noise in the measurements of the components x, y, z of

**G**and**B**and performing arithmetic operations with small noisy uNy and uEy becomes inaccurate. See figure 5.
Figure 5

Data was collected with the Roll angle very close to 90 degrees. Then we performed rotations about +Y-axis in small increments all the way around, 360 deg. The light blue is the heading provided in the iPhone data. The dark blue is our calculated heading. A trick to increase the accuracy of our calculation for this special condition, is to use the X-axis orientation from magnetic North. We subtract 90 deg from this X-axis orientation as follows

Cal_2_MagHeading = MOD[360+ATAN2(uNx, uEx) – 90, 360].

In figure 5 this calculation is shown in yellow and can be found in column BR. Observe, it is practically superimposed on the value obtained as data from the iPhone. When the absolute value of the Roll angle is between 80 and 100 degrees, it is recommended to use the above equation, otherwise using the former equation with the Body Frame Y-axis orientation works great.

8. From calculations performed so far, we can also form rotation matrices. Using our unit vectors for North, East, and G, we can form a matrix as follows

Note that the rows are the components of our unit Earth Frame x, y, z axes in the Body frame coordinates. The above matrix is a rotation matrix, it rotates the Body Frame unto the Earth Frame alignment. Meaning that the Body Frame X-axis aligns with the fixed Earth Frame x-axis. The Body Frame Y-axis aligns with the fixed Earth Frame y-axis, and similarly for the Z and z axes. The rotation of a vector in the Body Frame to a vector in the Earth Frame is perform with matrix multiplication. A vector in the Earth Frame is equal to the matrix multiplication with a vector in the Body Frame. This result can be found in cells CW47:CY49, notice the number in cell CV44 is used to obtain the rotation matrix for a given row of data. Furthermore the inverse of the above rotation matrix is given by

Notice that the M inverse matrix is the transpose of the M matrix, columns are the vector components of

**N**,**E**, and**G**. This is a property of rotation matrices. This M inverse matrix will rotate the Earth Frame unto the Body Frame aligning the corresponding axes as before. This M inverse matrix will rotate a vector from in the Earth Frame coordinates to the Body Frame coordinates. The testing of the above matrices to perform the implied rotations is left as an exercise.
9. From the

**G**and**B**vectors we can extract more quantities, we can calculate a rotation axis and angle from the rotation matrix elements.
The rotation angle is given by

and we can use this rotation angle to calculate the normalized rotation axis

where Wx =

in other words, the rows of this 1 column matrix are the x, y, z components of the rotation axis, W. These calculations are in columns BL thru BP.

10. Now we proceed to calculate a set of Euler angles. We make use of the Body Frame vector

**L**=**(0, 0, +1)**, the unit vector along the +Z-axis of our Body Frame. It can be found in columns AJ thru AK. Performing the vector cross product**H**=

**G X L**

we obtain a vector in the horizontal plane, designated as

**H**. Results are in columns AN thru AP. This vector lies on a line formed by the interception of the xy and XY planes of our defined coordinates usually designated as the line of nodes, see figure 2. We normalize, results are in columns AS thru AU. We have as defined, the angle between the Earth Frame x-axis and the line of nodes that can be calculated with a vector dot product**uH**dot**uN**as Euler Angle alpha. The angle between the Earth Frame +z-axis and the Body Frame +Z-axis as the Euler Angle beta calculated from unit vectors +z-axis dot +Z-axis. And the angle between Body Frame unit vector +X and the line of nodes calculated from**(+1, 0, 0)**dot**uH**, equations below, results are in columns AY thru BA.
These Euler Angles represent a rotation in the x-convention denoted as (ZXZ), and is performed as follows, we start with our two defined coordinates superimposed with corresponding axes, +X-axis on +x-axis, +Y-axis on +y-axis, and +Z-axis on +z-axis, then perform the following rotations:

a. The first rotation is by an angle alpha about the Earth Frame z-axis or Body Frame Z-axis, since they are superimposed.

b. The second rotation is by an angle beta about the former Earth Frame x-axis, now Body Frame X-axis along the line of nodes.

c. The third rotation is by an angle gamma about the former z-axis, now Body frame Z-axis

11. What can we do when there are net forces acting on the iphone? Net forces produce accelerations, see figure 3 above. We surmised that when there are net accelerations the above calculations become invalid. This can be seen in figure 6 for calculated pitch and roll. Data was collected as follows: Holding the iPhone horizontally, oscillated back and forth along the x-axis, stopped, then oscillated along the y-axis, and stopped, always holding the iPhone horizontally. Using the above equations to calculate pitch and roll we get the results in figure 6. However, we never tilted the iPhone; therefore the calculated oscillations of the pitch and the Roll are not the result of tilting the iPhone. Accelerations can result in apparent pitch and roll changes.

Figure 6.

So, if our body frame coordinate, on the iPhone, is experiencing accelerations, we ignore the above calculations. Note, the apparent changes in pitch and roll are interpreted as changes that an observer in the body frame would see as rotations of the Earth Frame.

What we can do then, is that under certain conditions we can calculate the true acceleration that the body frame coordinate is experiencing. Referencing figure 3, if the vertical vector G is measured in the body frame under static conditions, that is, no net accelerations, then a vector subtraction of Net G measured minus our reference static G, will give us the true acceleration experienced by our mobile device. In order for this simple vector subtraction to work, our body frame must not experience a net change in orientation with respect to our reference static G. Net changes in body frame orientation with respect to the static reference state will appear as an acceleration even though the device is in a static condition.

What we can do then, is that under certain conditions we can calculate the true acceleration that the body frame coordinate is experiencing. Referencing figure 3, if the vertical vector G is measured in the body frame under static conditions, that is, no net accelerations, then a vector subtraction of Net G measured minus our reference static G, will give us the true acceleration experienced by our mobile device. In order for this simple vector subtraction to work, our body frame must not experience a net change in orientation with respect to our reference static G. Net changes in body frame orientation with respect to the static reference state will appear as an acceleration even though the device is in a static condition.

From the data collected above, we have taken our reference static G at the 3 sec point, performed the subtraction G Net – G-ref, results are in figure 7.

Fiigure 7, Accel x, y, z are plotted with the left y-axis, and the magnitude of the Acceleration is plotted along the right y-axis. The acceleration A is measured in g-terms. Multiply A by 9.80665 meters per seconds squared.

This vector subtraction is performed in columns BW thru BZ in the spreadsheet, Analysis, of our Excel workbook.

G Net, and A are plotted below in figure 8.

Figure 8, G Net is plotted along the left y-axis, and A is plotted along the right y-axis.

By subtracting our static G reference at the 3 sec point from G Net, we produce the condition that A is equal to 0 under static conditions. In the Analysis worksheet the reference initial static state is selected with cell CW41. Cell CW41 is set at a data row under static conditions just prior to applying accelerations to the iPhone. In order to obtain useful acceleration try to keep the Body Frame from experiencing angular rotations. Sustained angular rotations will increase the complexity of result and understanding. See this link for rotating reference frame.

The Excel workbook has other quantities in columns that are calculated. Such as quaternions in columns CJ thru CR. Those are left to be explored by users.

The Excel workbook has other quantities in columns that are calculated. Such as quaternions in columns CJ thru CR. Those are left to be explored by users.

**Conclusion**

By utilizing the measured accelerometer and magnetometer values, under static conditions, obtained from an iPhone we can completely characterize the orientation of the iPhone. For the iPhone, with respect to two defined coordinate systems, the moveable Body Frame coordinates, and the fixed Earth Frame coordinates, see figure 2, quantities such as Body Frame axes headings, pitch, roll, rotation matrices, axis and angle of rotation, quaternions, and Euler Angles in the x-convention (ZXZ) are easily calculated with a spreadsheet. Furthermore, under certain conditions the true acceleration experienced by the iPhone can be determined.

Hi there,

ReplyDeleteI can't seem to download the Excel workbook. Is there another link for it? Thanks. My email address is simonli108@live.com

Simon Li

sure - but are the components returned in a CLHeader vector direction cosines?

ReplyDeleteResponse for Anonymous: Dont know what you mean by "CLHeader vector direction cosines"; and components of which vector ?

ReplyDeleteThis comment has been removed by the author.

ReplyDeleteThank you so much. It's very helpful to understand accelerometer ant its physics. I'm not sure I can understand all of it :). But anyway, thank you again. This article is the best one I've ever found.

ReplyDeleteHello! I've got a your excel file. I never expected it. Thank you, so much!

Deletehi this article the best!! just exactly im looking for

ReplyDeletewhere exactly the sensor located inside the iphone?

does the position of the center of sensor effect the 'precisely' calculation for angle? for determine the zero value/still object?

just curious im not really good for math and physic...

many thanks

would this cover the following:

ReplyDeleteCalibration Algorithm Requirements:

- An algorithm is required to normalize readings from a mobile device accelerometer to the direction of motion of the vehicle the device is contained within. Using instantaneous accelerometer readings and gravity, the algorithm must normalize the X,Y, and Z acceleration vectors of the device to the interpreted direction of travel. The normalized values of the algorithm output will result in the Y axis interpreted as forward and backward, X axis is interpreted as left and right, with Z representing the vertical vector.

Pardon me for taking so long to respond. Let me see if I understand what you are asking, a vehicle (could be an automobile, a radio control car, a rocket) has a coordinate system with the +Y axis always pointing forward, the +X axis is always to the right, and the +Z axis is always upward (this follows the right-hand rule). In this vehicle is an electronic device such as an iPhone, which has an accelerometer, magnetometer, and gyrometer. You want to transform the device’s x, y, x accelerometer, magnetometer, and gyrometer values to what would be observed in the X, Y, and X axis of the vehicle.

DeleteIf yes, then an answer is very simple, fix the device such that the device’s +y axis is pointing forward in the vehicle (for iPhone the +y axis is pointing toward the power button). The device’s +x axis is pointing to the right. See Fig 1 in the paper. Then you will not need to do any transformation. If the axises of the vehicle and the device are aligned (+x and +X, +y and +Y), the device’s readings are what would be observed in the vehicle’s coordinate system. Otherwise, you will have to determine the transformation matrix to convert between the two coordinates. It is doable but not as easy as doing previous approach.

This comment has been removed by the author.

ReplyDeleteHi Rouel

ReplyDeleteThanks for sharing and the great work you have put into this.

br. Dan