Using Windows Phone 7 Technologies : Understanding Orientation and Movement
Figure 1. Accelerometer axis direction when you hold it in your hand facing toward you
To illustrate the accelerometer reading of the (x, y, z) = (0, −1, 0) means putting the phone on the table, standing up with the phone buttons facing downwards, with the front of the phone facing toward you, as shown in Figure 2.
If you were to rotate the phone in Figure 6-2 to the right 90 degrees, so that the Windows Phone control buttons are to the right, as shown in Figure 3, and the expected accelerometer readings will be (x, y, z) = (-1, 0, 0).
If you took the phone in Figure 2 and rotated it to the right 180 degrees, (x, y, z) would be (0, 1, 0), as shown in Figure 4.
If you were to rotate the phone in Figure 4 to the right 90 degrees, as shown in Figure 5, (x, y, z) would be (1, 0, 0).
If you were to put the phone flat on the table with the phone facing up, as shown in Figure 6, (x, y, z) would be (0, 0, 1).
If you put the phone facing down on the table, as shown in Figure 7, (x, y, z) would be (0, 0, 1).
Figure 2. (x, y, z) = (0, −1, 0)
Figure 3. (x, y, z) = (−1, 0, 0)
Figure 4. (x, y, z) = (0, 1, 0)
Figure 5. (x, y, z) = (1, 0, 0)
Figure 6. (x, y, z) = (0, 0, −1)
Figure 7. (x, y, z) = (0, 0, 1)
1. Calculating Distance
The so-called Euclidean distance algorithm is a useful way to calculate a distance between two points in three-dimensional space. This is a very useful equation that allows you to detect sudden movements such as the shaking of the phone.
If ( Ox, Oy, Oz ) is a previous accelerometer value and ( Nx, Ny, Nz ) is a new one, you can calculate Euclidean distance as follows.
2. Calculating Pitch and Roll
With obtained accelerometer readings you will have a pretty good understanding of the current orientation of the phone as seen in foregoing section, but using the accelerometer data, you can obtain much more information to understand how the phone is tilted on the x, y, and z axes. This information can be very useful if you are planning to create airplane simulation games or racing games that use the accelerometer to control the direction of moving objects. Think of it as using a phone like joystick by detecting the tilt motion.
When you hold the phone vertically, with the screen facing you, both the pitch and roll angles are 0 degrees, as shown in Figure 8.
Figure 8. Pitch and roll angles of 0 degrees
Now if you tilt the phone slightly to the right, you will be able to calculate the pitch (ρ) and roll (φ) angles shown in Figure 6-9. Also there is another angle of interest, which would be theta, the angle respect to the z axis, which is not shown in Figure 9.
Figure 9. Pitch and roll angles
In order to calculate pitch (ρ), roll (φ), and theta angles you will need the following equations, where Ax, Ay, and Az are the accelerometer values for x, y, and z.
You'll use both Euclidean distance and pitch and roll calculations in the examples that follow.