# Magnetometer

The Kode Dot's heading in degrees from north, from a compass that has to be calibrated first.

## What it is

The magnetometer is the compass of the Kode Dot. It measures the magnetic field
on three axes. Away from magnets and iron, that field is the Earth's, about 25
to 65 µT, and it points roughly north. How it combines with the accelerometer
and the gyroscope is in [IMU](/device/imu#what-it-is).

The chip is a **QMC5883P** from QST. The Earth's field is not the only one it
picks up, since it also gets the field of the magnetic connector, the speaker
and the haptic motor, which sit millimetres from the chip and turn with the
Kode Dot.

That is why you calibrate the compass once before you use it.
`kode_mag_calibrate()` asks you on the screen to turn the Kode Dot in every
direction, measures the Kode Dot's own field that way and stores it so it can
subtract it. After that, `kode_mag_heading()` gives you the heading in degrees and
`kode_mag_read()` the corrected field.

![Animation. The Kode Dot lies flat on a table, seen from above, inside a compass with the letters N, E, S and W. A fixed blue mark at the top points to the top of the Kode Dot. As the Kode Dot turns, the compass turns the other way around it. On the right is what kode_mag_heading() returns, in degrees from north. With N at the top it reads 0°. With the top towards the east it reads 90°, towards the south-west 225° and then 300°, until it is back at 0°. Label: the heading is where the top of the Kode Dot points.](/device/magnetometer/heading.webp)

## How it is connected

The QMC5883P sits on the Kode Dot's [shared I2C bus](/device/overview#how-it-is-connected),
the same one as the IMU, the buttons and the LED. The P4 asks it for each
reading over that bus. The chip has no alert line, so it never tells you a new
reading is ready.

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

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

## Specifications

- **±30 gauss**: That is ±3000 µT, in steps of 0.1 µT. It is this wide because the Kode Dot's own field is several gauss.
- **50 Hz**: The rate the chip measures at. Each call returns the latest measurement.
- **Heading from 0 to 360**: `kode_mag_heading()` returns where the top of the Kode Dot points, in degrees clockwise from north. It corrects the tilt with the accelerometer and needs a stored calibration.
- **Field in µT**: `kode_mag_read()` returns in a `kode_mag_t` the field on `x`, `y` and `z`, while `kode_mag_read_axis("x")` returns a single axis. With a stored calibration, the field comes out corrected. If it fails, it returns NAN.
- **Calibration of 30 s at most**: `kode_mag_calibrate()` takes the screen and shows in % how far you have turned the Kode Dot. It reaches 100 % once all three axes have measured the field almost as large in both directions. It finishes 3 s after the value stops growing, and fails if it has not finished after 30 s. It is in the `kode_screen` component. `kode_mag_is_calibrated()` says whether one is stored and `kode_mag_clear_calibration()` forgets it.
- **Asleep after 2 s**: If nobody reads it for 2 s, the chip goes to sleep. The read that wakes it waits for its first measurement, about 20 ms.

The calls are `kode_mag_read()`, `kode_mag_read_axis(axis)`,
`kode_mag_heading()`, `kode_mag_calibrate()`, `kode_mag_is_calibrated()` and
`kode_mag_clear_calibration()`, in `kode.h`.

## Gotchas

- **With the Kode Dot tilted, kode_mag_heading() gives a wrong heading**: The SDK corrects the tilt with the IMU's axes the wrong way round. At 10° of tilt the heading can be about 30° off, and at 20° it can read south instead of north. Until it is fixed, read the heading with the Kode Dot flat.
- **kode_mag_heading() returns NAN and asks for a calibration**: `kode_error()` says "call kode_mag_calibrate() first". There is no stored calibration, and without one the Kode Dot's own field hides the Earth's, so call `kode_mag_calibrate()` once and KodeOS keeps the result.
- **The heading comes out NAN from motion or a weak field**: `kode_error()` says "the Dot is moving too much to tell which way is up" or "the field is too weak to give a heading". It happens when the total acceleration falls outside 0.5 to 1.5 g, because then the SDK cannot tell which way gravity pulls, or when the horizontal field is under 2 µT. In both cases, hold the Kode Dot still and roughly flat.
- **kode_mag_calibrate() fails even though you turned the Kode Dot**: `kode_error()` says "not enough directions were covered". At the end, the SDK checks that all the readings form an almost perfect sphere. In v0.1.5 that check asks for more than the 100 % on the screen, so it can reject a sweep that did go through every direction. Near the computer or anything metal it usually fails, because the field changes as the Kode Dot moves. Move away from both and try again, as the example does.
- **The build fails with undefined reference to 'kode_mag_calibrate'**: The calibration draws on the screen and lives in the `kode_screen` component, which your project is missing. Add it and build again.
- **After calibrating, your app's screen is gone**: The calibration puts up its own screen and clears your widgets, so build your screen again with `kode_screen_new()` once the call returns.

The tilted heading is tracked in [kode-sdk#282](https://github.com/kodediy/kode-sdk/issues/282).
How to add `kode_screen` to your project is in
[Your first build](/build/first-build#write-your-first-app).

## Apps that use it

- https://apps.kode.diy/app/15bb0ecd-9648-4b02-8273-d79989804ec5

## Example code

This program turns the screen of the Kode Dot into a compass. The first time,
or when you press the Action button, it asks you to calibrate it. Turn the Kode
Dot every way, away from the computer and from metal objects. When it reaches
100 %, hold it still for a few seconds until it says **Compass ready**. If it
fails, it starts again by itself.

Then lay it flat and turn it. The screen shows where its top points, in degrees
from north and as a letter (N, NE, E…). The console prints it each time it
changes.

```c
/* SPDX-License-Identifier: GPL-3.0-or-later */
/**
 * @file compass.c
 * @brief Turns the screen of the Kode Dot into a compass.
 *
 * The first time, or when you press the Action button, the screen asks you to
 * calibrate: turn the Kode Dot every way until it says Compass ready. Then it
 * shows where the top of the Kode Dot points, in degrees from north and as a
 * letter, and the console prints it each time it changes.
 *
 * from Kode with love
 */
#include <math.h>
#include <stdio.h>
#include "kode.h"

#define WHY_BYTES         128U   /**< Room for the reason a calibration failed. */
#define CAL_RETRY_MS      3000U  /**< Wait before the next calibration. */
#define HEADING_PERIOD_MS 250U   /**< Time between two headings. */

static kode_widget_t s_degrees;   /**< The heading, in big digits. */
static kode_widget_t s_pointing;  /**< The heading as a letter. */

/** @brief Calibrate until it works, unless a calibration is saved, then draw the compass. */
static void compass_start(void)
{
    while ( !kode_mag_is_calibrated() && !kode_mag_calibrate() )
    {
        char why[WHY_BYTES];

        (void)snprintf(why, sizeof(why), "%s", kode_error());  /* kode_print() clears it */
        kode_print("calibration failed: %s", why);
        kode_delay(CAL_RETRY_MS);
    }
    (void)kode_screen_new("Compass");
    s_degrees = kode_screen_add_value("--", "degrees");
    s_pointing = kode_screen_add_text("Lay it flat and turn it");
    (void)kode_screen_add_text("Action button: calibrate again");
}

/** @brief Show the heading four times a second; the Action button calibrates again. */
void app_main(void)
{
    static const char *const names[8] = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" };
    int last = -1;

    kode_init();
    kode_print("Running: follow the screen if it asks to calibrate");
    compass_start();

    while ( true )
    {
        if ( kode_button_was_pressed("top") )
        {
            (void)kode_mag_clear_calibration();
            compass_start();
            last = -1;
        }
        float heading = kode_mag_heading();
        int now = isnan(heading) ? last : (int)heading;

        if ( now != last )
        {
            const char *name = names[((now + 22) / 45) % 8];

            (void)kode_widget_set_text(s_degrees, "%d", now);
            (void)kode_widget_set_text(s_pointing, "Pointing %s", name);
            kode_print("heading %d degrees, %s", now, name);
            last = now;
        }
        kode_delay(HEADING_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 QMC5883P driver in `kode-sdk`, described in [the QMC5883P driver](/sdk/kdrv/qmc5883p).
- [`examples/imu`](https://github.com/kodediy/kode-sdk/tree/v0.1.5/examples/imu): an SDK example for the sensors.
