# IMU

Measure how the Kode Dot tilts and turns with its accelerometer and gyroscope, a QMI8658A.

## What it is

An IMU, an inertial measurement unit, puts an accelerometer and a gyroscope in
one chip, and the Kode Dot's is a **QMI8658A** from QST.

- The **accelerometer** measures acceleration, gravity included. Lying still it
  reads 1 g, and tilting the Kode Dot moves that 1 g from one axis to another.
  It is how an app knows which way you are holding it, and how a step counter
  counts.
- The **gyroscope** measures rotation rate, in degrees per second. It does not
  know where you are pointing, only how fast that is changing. Add its readings
  up over time and you get an angle, which slowly drifts.

With `kode_imu_read()` your app reads the acceleration and the rotation on the
three axes, and the chip's temperature. To count steps or
detect taps, you work them out from those readings. The chip can do it
too, but the SDK does not use those features.

![Animation. The Kode Dot seen from the front, standing on its bottom edge, tilts in the plane of the screen. On the right are the acceleration values that kode_imu_read() returns, in g, each with a bar from −1 to +1. Standing up, accel_x reads 0.00 g, accel_y −1.00 g and accel_z 0.00 g. Tilted 30° to the right, accel_x reads about +0.50 g and accel_y about −0.87 g. Lying on its right side, accel_x reads +1.00 g and accel_y 0.00 g. Then it stands up again. accel_z stays at 0.00 g the whole time, because the Kode Dot turns while still facing you. Label: tilt the Kode Dot and the 1 g moves from one axis to another.](/device/imu/tilt.webp)

With the [magnetometer](/device/magnetometer), which works as a compass, that
makes three sensors of three axes each, which is where "9-axis" comes from.
Together they correct each other. The accelerometer knows which way gravity
pulls, but not where north is. The compass finds north, although its reading changes when
the Kode Dot tilts, and the gyroscope responds fast and smoothly but drifts over
time. Combining the three is what "sensor fusion" means. For the heading,
`kode_mag_heading()` already combines the compass with the accelerometer, and
if you also want to add the gyroscope, you write that fusion in your app.

## How it is connected

The QMI8658A sits on the Kode Dot's [shared I2C bus](/device/overview#how-it-is-connected),
the same one as the touch screen, the buttons and the LED. The P4 asks it for
each sample over that bus with `kode_imu_read()`. The chip has an alert line
that reaches the expander, but KodeOS does not use it, so it never tells you a
new sample is ready.

![The ESP32-P4, which runs your code, reaches the accelerometer and gyroscope, a QMI8658A, over the I2C bus at address 0x6A, on pins GPIO4 and GPIO5.](/device/imu/connection.webp)

The full circuit is in the [main board schematic](/hardware/main-board).

## Specifications

- **±8 g**: What the accelerometer measures, gravity included, in steps of 0.001 g.
- **±512 degrees per second**: What the gyroscope measures, in steps of 1/64 of a degree per second.
- **896.8 Hz**: The rate the chip measures at. Each call returns the latest sample.
- **Steps of 0.1 °C**: The temperature is the chip's own and not the room's.
- **x to the left, y downwards**: The axes are the chip's own, and the chip is mounted rotated half a turn. With the screen facing you, `x` grows to the left, `y` downwards and `z` out of the screen. With the Kode Dot standing on its bottom edge, `accel_y` reads −1 g.
- **Asleep after 2 s**: If nobody reads it for 2 s, the chip goes to sleep. The read that wakes it takes about 200 ms, which the gyroscope needs to give reliable values.
- **7 values per sample**: `kode_imu_read()` returns them in a `kode_imu_t`, all from the same sample. Acceleration is in g (`accel_x`, `accel_y` and `accel_z`), rotation in degrees per second (`gyro_x`, `gyro_y` and `gyro_z`) and temperature in degrees Celsius (`temp`).
- **A single value**: `kode_imu_read_axis("accel_x")` returns just one, by the name of its field.

The calls are `kode_imu_read()` and `kode_imu_read_axis(axis)`, in `kode.h`.
Both wait for the sample and, if they fail, return NAN.

## Gotchas

- **With the Kode Dot lying still, the accelerometer reads 1 g and not zero**: It is gravity, which the accelerometer always measures. To keep only your own motion, store one reading taken with the Kode Dot still and subtract it from the next ones, as long as you do not tilt it, because then gravity moves to another axis.
- **A read returns NAN and not zero**: That is how a failed read comes back. Test it with `isnan` before you use it and, if it failed, `kode_error()` tells you why.

## Apps that use it

- https://apps.kode.diy/app/a3c72f04-0936-4c64-9401-e14588332521
- https://apps.kode.diy/app/685b318b-a654-42a4-8d75-efe807653cca

## Example code

The program prints the acceleration, the rotation and the temperature twice a second. Lay
the Kode Dot flat and one axis reads about 1000 mg with the other two near
zero. Tilt it and the 1000 mg moves from one axis to another.

```c
/* SPDX-License-Identifier: GPL-3.0-or-later */
/**
 * @file imu_log.c
 * @brief Prints the acceleration and rotation of the Kode Dot twice a second.
 *
 * Lay it flat and one acceleration axis reads about 1 g, the pull of gravity,
 * while the rotation stays near 0. Pick it up and turn it, and the rotation
 * values move. A failed read gives NAN, so the program skips those samples.
 *
 * from Kode with love
 */
#include <math.h>
#include "kode.h"

#define IMU_PERIOD_MS 500U     /**< Time between two samples. */
#define MG_PER_G      1000.0f  /**< Thousandths of a g in one g. */

/** @brief Start the system, then print one sample every 500 ms. */
void app_main(void)
{
    kode_init();
    kode_print("Running: tilt and turn the Kode Dot");

    while ( true )
    {
        kode_imu_t imu = kode_imu_read();

        if ( 0 == isnan(imu.accel_x) )
        {
            kode_print("accel %d %d %d mg  gyro %d %d %d dps  %d C",
                       (int)(imu.accel_x * MG_PER_G), (int)(imu.accel_y * MG_PER_G),
                       (int)(imu.accel_z * MG_PER_G), (int)imu.gyro_x,
                       (int)imu.gyro_y, (int)imu.gyro_z, (int)imu.temp);
        }
        kode_delay(IMU_PERIOD_MS);
    }
}
```

If you would rather build it yourself, follow [the steps shared by every example](/device/overview#run-the-example-of-a-page).

## In the SDK

- [`kdrv/motion`](https://github.com/kodediy/kode-sdk/tree/v0.1.5/components/kdrv/motion): the QMI8658A driver in `kode-sdk`, described in [the QMI8658A driver](/sdk/kdrv/qmi8658a).
- [`examples/imu`](https://github.com/kodediy/kode-sdk/tree/v0.1.5/examples/imu): an SDK example for the same calls.
