Combining sensors

Now that you are able to read the accelerometer data, you should be able to read the gyroscope data as well. We will use both sensors to get an estimate of the various angles around X, Y, and Z axis.

Determine the partial board attitude

Using only the accelerometer, determine the board tilt angles (the angles compared from the "flat-on-the-table" position). You will have to use some maths there. Check that it looks consistent with the position of the board.

Note that the accelerometer-based method works best if the board is not moving fast. Shaking the board will give very bad results.

Read the gyroscope as well

Configure the gyroscope for continuous reading. The same interrupt line will be used to signal data from the accelerometer and data from the gyroscope. Use the STATUS_REG register to read only the relevant data and display it.

Use the gyroscope to determine the partial board attitude

Assuming that the board is flat on the table when the program starts, use the gyroscope data to compute the board tilt angles. You'll see that the angles derive slowly as each of the axes has a bias. This is inherent to gyroscopes, and many other sensors: they are not perfect.

One characteristic of gyroscopes is that their bias gradually drift over time. However, the bias is usually small enough that, when the board is rotating, it becomes negligible compared to the measured value.

Design a complementary filter between the accelerometer and the gyroscope

Store the accelerometer and gyroscope data in mutex-protected global variables. From a new thread, read those data regularly and compute the new angles using a complementary filter. Choose update frequencies high enough so that the variables are relatively up-to-date.

For example, you can compute the angles by taking 50% of the accelerometer-based computation, and 50% of the gyroscope-based computation (derived from the previous angles). Check if this approach yields results that are both stable and responsive enough. Endeavor to find the best coefficients, ensuring the total amount is is 100%. Don't hesitate to test exterme values (such as 98%/2%).

LED blinking

Make the green leds blink according to the absolute tilt angles. The leds will be steady when the board is flat, and will blink very fast when the board is tilted by 90°.