# Calculating Lean Angle with Core Motion

I have a record session for my application. When user started a record session I start collecting data from device’s CMMotionManager object and store them on CoreData to process and present later. The data I’m collecting includes gps data, accelerometer data and gyro data. The frequency of data is 10Hz.

Currently I’m struggling to calculate the lean angle of device with motion data. It is possible to calculate which side of device is land by using gravity data but I want to calculate right or left angle between user and ground regardless of travel direction.

This problem requires some linear algebra knowledge to solve. For example for calculation on some point I must calculate the equation of a 3D line on a calculated plane. I am working on this one for a day and it’s getting more complex. I’m not good at math at all. Some math examples related to the problem is appreciated too.

### 2 Solutions Collect From Internet About “Calculating Lean Angle with Core Motion”

It depends on what you want to do with the collected data and what ways the user will go with that recording iPhone in her/his pocket. The reason is that Euler angles are no safe and especially no unique way to express a rotation. Consider a situation where the user puts the phone upright into his jeans’ back pocket and then turns left around 90°. Because CMAttitude is related to a device lying flat on the table, you have two subsequent rotations for (pitch=x, roll=y, yaw=z) according to this picture:

- pitch +90° for getting the phone upright => (90, 0, 0)
- roll +90° for turning left => (90, 90, 0)

But you can get the same position by:

- yaw +90° for turning the phone left (0, 0, 90)
- pitch -90° for making the phone upright (-90, 0, 90)

You see two different representations (90, 90, 0) and (-90, 0, 90) for getting to the same rotation and there are more of them. So you press Start button, do some fancy rotations to put the phone into the pocket and you are in trouble because you can’t rely on Euler Angles when doing more complex motions (s. gimbal lock for more headaches on this 😉

Now the good news: you are right linear algebra will do the job. What you can do is force your users to put the phone in always the same position e.g. fixed upright in the right back pocket and calculate the angle(s) relative to the ground by building the dot product of gravity vector from CMDeviceMotion **g = (x, y, z)** and the postion vector p which is the -Y axis (0, -1, 0) in upright position:

g • x = x*0 + y*(-1) + z*0 = -y = ||g||*1*cos (alpha)

=> **alpha = arccos (-y/9.81)** as total angle. Note that gravitational acceleration g is constantly about 9.81

To get the left-right lean angle and forward-back angle we use the tangens:

**alphaLR = arctan (x/y)**

**alphaFB = arctan (z/y)**

**[UPDATE:]**

If you can’t rely on having the phone at a predefined postion like (0, -1, 0) in the equations above, you can only calculate the total angle but not the specific ones alphaLR and alphaFB. The reason is that you only have one axis of the new coordinate system where you need two of them. The new Y axis **y’** will then be defined as average gravity vector but you don’t know your new X axis because every vector perpedicular to y’ will be valid.

So you have to provide further information like let the users walk a longer distance into one direction without deviating and use GPS and magnetometer data to get the 2nd axis z’. Sounds pretty error prone in practise.

The total angle is no problem as we can replace (0, -1, 0) with the average gravity vector (pX, pY, pZ):

g•p = x*pX + y*pY + z*pZ = ||g||*||p||*cos(alpha) = ||g||^2*cos(alpha)

alpha = arccos ((x*pX + y*pY + z*pZ) / 9.81^2)

Two more things to bear in mind:

- Different persons wear different trowsers with different pockets. So the gravity vector will be different even for the same person wearing other clothes and you might need some kind of normalisation
- CMMotionManager does not work in the background i.e. the users must not push the standby button

If I understand your question, I think you are interested in getting the *attitude* of your device. You can do this using the `attitude`

property of the `CMDeviceMotion`

object that you get from the `deviceMotion`

property of the `CMMotionManager`

object.

There are two different angles that you might be interested in the `CMAttitude`

class: *roll* and *pitch*. If you imagine your device as an airplane with the propeller at the top (where the headphone jack is), pitch is the angle the plane/device would make with the ground if the plane were in a climb or dive. Meanwhile, roll is the angle that the “wings” would make with the ground if the plane were to be banking or in mid barrel roll.

(BTW, there is a third angle called *yaw* that I think is not relevant for your question.)

The angles will be given in radians, but it’s easy enough to convert them to degrees if that’s what you want (by multiplying by 180 and then dividing by `pi`

).

Assuming I understand what you want, the good news is that you may not need to understand any linear algebra to capture and use these angles. (If I’m missing something, please clarify and I’d be happy to help further.)

**UPDATE** (based on comments):

The attitude values in the `CMAttitude`

object are relative to the ground (i.e., the default reference frame has the Z-axis as vertical, that is pointing in the opposite direction as gravity), so you don’t have to worry about cancelling out gravity. So, for example, if you lie your device on a flat table top, and then roll it up onto its side, the `roll`

property of the CMAttitude object will change from 0 to plus or minus 90 degrees (+- .5pi radians), depending on which side you roll it onto. Meanwhile, if you start it lying flat and then gradually stand it up on its end, the same will happen to the `pitch`

property.

While you can use the pitch, roll, and yaw angles directly if you want, you can also set a different reference frame (e.g., a different direction for “up”). To do this, just capture the attitude in that orientation during a “calibration” step and then use CMAttitude’s `multiplyByInverseOfAttitude:`

method to transform your attitude data to the new reference frame.

Even though your question only mentioned capturing the “lean *angle*” (with the ground), you will probably want to capture at least 2 of the 3 attitude angles (e.g., pitch and either roll or yaw, depending on what they are doing), potentially all three, if the device is going to be in a person’s pocket. (The device could rotate in the pocket in various ways if the pocket is baggy, for example.) For the most part, though, I think you will probably be able to rely on just two of the three (unless you see radical shifts in yaw throughout the course of a recording session). So for example, in my jeans pocket, the phone is usually nearly vertical. Thus, for me, pitch would vary a whole bunch as I, say, walk, sit or run. Roll would vary whenever I change the direction I’m facing. Meanwhile, yaw would not vary much at all (unless I do kart-wheels, which I can’t!). So yaw can probably be ignored for me.

To summarize the main point: to use these attitude angles, you don’t need to do any linear algebra, nor worry about gravity (although you may want to use this for other purposes, of course).

**UPDATE 2** (based on Kay’s new post):

Kay just replied and showed how to use gravity and linear algebra to make sure your angles are *unique*. (And, btw, I think you should give the bounty to that post, fwiw.)

Depending on what you want to do, you may want to use this math. You would want to use the linear algebra and gravity *if* you need a standardized way of “talking about” and/or *comparing* attitudes over the course of your recording session. If you just want to visualize them, you can probably still get away with not using the increased complexity. (For example, visualizing (pitch=90, roll=0, yaw=0) should be the same as visualizing (pitch=0, roll=90, yaw=90).) In my approach above, while you could have multiple ways of referring to the “same” attitude, none of them is actually *wrong*, per se. They will still give you the angles relative to the ground.

But the fact that the gyroscope can switch from one valid description of an attitude to another means that what I wrote above about getting away with only 2 of the 3 components needs to be corrected: because of this, you will need to capture all three components, no matter what. Sorry.

- Align label from left and right that have “\n”
- iOS 8.3 – Meta viewport with fixed width results in weird content scaling on orientation change
- Two weak variables referencing each other in Swift?
- Parsing JSON response .
- Integrate Facebook SDK inside my iOS Framework
- iPhone4 iOS5 battery level monitoring do I need to add setBatteryMonitoringEnabled:NO to periodic battery checks?
- NSRangeException when deleting last UICollectionViewCell
- Change App Localization Based on User Selection
- Adding Navigation Bar programmatically iOS
- looping through an NSMutableDictionary
- Finding time between dates in Swift
- TODOs in Xcode: How to make them stand out?
- fake va_list in ARC
- Initialising empty arrays of dictionaries in Swift
- Watchkit AppIcon – The app icon set named “AppIcon” did not have any applicable content