9-Axis Sensor (imu)
imu is the built-in 9-axis motion sensor module of the Firefly T1 firmware. It drives the BMI270 (3-axis accelerometer + 3-axis gyroscope) and the BMM150 (3-axis magnetometer) over I2C. With just init() and read_9axis(), you get the device's full orientation data. The launcher's auto-sleep feature reads it to decide whether the device is lying still.
read_9axis() returns acceleration (m/s²), angular rate (°/s), and magnetic flux density (μT) at once.
SDA=GPIO2, SCL=GPIO1, 100 kHz. Do not create another bus yourself.
If any of the three sensors has not refreshed, the read fails. Skip that round and retry.
Hardware and Pins
| Item | Value |
|---|---|
| Accelerometer + gyroscope | BMI270 |
| Magnetometer | BMM150 (accessed through the BMI270 auxiliary interface) |
| Bus | I2C (shared with Power Management (pm)) |
SDA / SCL | GPIO2 / GPIO1, 100 kHz, internal pull-ups |
| Ranges | Accelerometer ±2 g, gyroscope ±2000 °/s |
| Sample rate | 100 Hz for accelerometer, gyroscope, and magnetometer |
| Data ready | Mapped to the BMI270 INT1 pin (handled inside the firmware, nothing for you to do) |
You do not need to create an I2C object yourself — the module uses the firmware's shared bus wrapper, and imu.init() takes care of everything.
Quick Start
import imu
if imu.init() != 0:
print("IMU init failed")
else:
rslt, accel, gyro, mag = imu.read_9axis()
print("Accel (m/s^2):", accel)
print("Gyro (dps):", gyro)
print("Mag (uT):", mag)
What you will see: with the device lying flat on a desk, one axis of accel is close to ±9.8 while the other two are near 0 (gravity); all three gyro values are near 0; mag sits in the tens-of-μT range and changes as you turn the device.
If initialization fails, imu.init() returns a negative number — see the error code table below.
9-Axis Data and Units
This is the part people get wrong most often: the firmware has already converted the raw LSB values into physical units, so what you receive is the final value.
| Data | Source | Unit | Range | Typical value when lying still |
|---|---|---|---|---|
accel = (ax, ay, az) | BMI270 accelerometer | m/s² | ±2 g | one axis ≈ ±9.8, the rest ≈ 0 |
gyro = (gx, gy, gz) | BMI270 gyroscope | °/s | ±2000 °/s | all three ≈ 0 |
mag = (mx, my, mz) | BMM150 magnetometer | μT | — | roughly ±tens of μT, varies with heading |
Two key points to remember:
- Acceleration is in m/s², not g. The firmware converts using
GRAVITY_EARTH = 9.80665, so a device at rest reads about 9.8 rather than 1.0. To get g, divide by9.80665. - Which axis gravity lands on depends on your hardware — measure it. It is determined by how the sensor is mounted. Read one still sample on the real device, see which axis has the largest magnitude, and write your "face up / face down / standing" logic from that. Do not copy someone else's axis numbers.
A useful, orientation-independent metric is the total acceleration:
total = math.sqrt(accel[0]**2 + accel[1]**2 + accel[2]**2)
It is about 9.8 at rest, grows noticeably when you swing the device quickly, and approaches 0 in free fall.
API Reference
Initialization imu.init()
rslt = imu.init() # 0 means success
No arguments. Returns an int: 0 for success, negative for failure.
- The first call does all of this in order: creates the shared I2C bus (
SDA=GPIO2,SCL=GPIO1,100kHz) → initializes the BMI270 → configures the accelerometer and gyroscope (±2 g / ±2000 °/s at 100 Hz) → configures the magnetometer auxiliary interface → enables all three sensors → maps the data-ready interrupt toINT1. - If it is already initialized it returns
0immediately without re-initializing. The launcher's auto-sleep thread has already called it, so calling it again from your app is safe and very fast. - A call after a failure retries the full initialization: the internal flag is not set when initialization fails.
Meaning of the returned value on failure:
rslt | Name | Typical cause |
|---|---|---|
0 | Success | — |
-1 | BMI2_E_NULL_PTR | The shared I2C bus handle is invalid; the bus was not created |
-2 | BMI2_E_COM_FAIL | I2C communication failed (bad wiring, or the pins are claimed by other code) |
-3 | BMI2_E_DEV_NOT_FOUND | Chip ID could not be read; the sensor is not responding |
-4 | BMI2_E_INVALID_CONFIG | Invalid configuration parameter |
| other negative values | Internal Bosch driver errors | Failures during initialization or configuration |
Read 9-axis data imu.read_9axis()
rslt, accel, gyro, mag = imu.read_9axis()
No arguments. Returns a 4-tuple:
| Position | Type | Description |
|---|---|---|
rslt | int | 0 on success; non-zero when this round produced no valid data |
accel | tuple[float, float, float] | Acceleration (ax, ay, az) in m/s² |
gyro | tuple[float, float, float] | Angular rate (gx, gy, gz) in °/s |
mag | tuple[float, float, float] | Magnetic flux density (mx, my, mz) in μT |
Behavior notes:
- All three datasets come back in one read: it is a single burst read internally, so it is cheaper than three separate reads.
- If any of the three sensors has not refreshed,
rsltis non-zero, and in that case all three tuples are0.0— which is exactly why you must checkrsltfirst, or you will flatten real data to zero. - Non-blocking: it reads the registers once and returns failure immediately when nothing is ready; it never waits for new data.
- Each call returns brand-new tuples, so
last_accel = accelsafely keeps the previous sample without being overwritten by later reads.
Data Readiness and Read Cadence
The sample rate is 100 Hz, meaning every 10 milliseconds each of the three sensors produces one new frame. Whether read_9axis() succeeds depends entirely on whether 10 ms have passed since the last frame:
| Situation | rslt | Explanation |
|---|---|---|
| >= 10 ms since the last successful read | 0 | All three datasets are the newest frame |
| Two reads too close together | commonly -1 | A sensor has not refreshed yet; just retry — this is not a fault |
Always -1 | -1 | No data for a long time → see the troubleshooting table |
The launcher's auto-sleep thread reads once per second and simply skips the round without any error message when rslt != 0 — that is the recommended way to handle it.
Also note that the launcher's own loop reads the same sensor; when two threads read it at once, one of them will occasionally get -1. That is normal.
Common Pitfalls
- Acceleration is in m/s², not g. Judge tilt against ±9.8; comparing against
1.0will never be true. rslt != 0does not mean the sensor is broken. Most often it means "data is not ready yet", especially when reads are too close together. Skip the round.- When
rslt != 0, all three values are0.0. Doing math without checkingrsltflattens real data to zero and breaks still-detection. init()returns negative numbers on failure — do not treat every!= 0as "broken". Print the value; knowing whether it is-1,-2,-3, or-4pinpoints the cause.- Reading faster will not get you data faster. The rate is fixed at 100 Hz; stuffing
time.sleep(0.001)into your loop just re-reads the same frame or gets-1while burning CPU. Use an interval of 20 ms or more for reliable success. - Do not create another I2C bus.
GPIO1/GPIO2are shared by imu and pm, and the module uses the firmware's shared bus; a second bus will conflict. - The magnetometer is easily disturbed. Nearby magnets, speakers, motors, and the high-current traces of a LED strip all make
magjump. Rule out the environment before blaming the sensor.
More Recipes
Detecting whether the device is still
This is the same algorithm the launcher's auto-sleep uses: sum the change between two consecutive samples.
import imu
import time
THRESHOLD_ACCEL = 0.05 # in m/s^2, same as the launcher
THRESHOLD_GYRO = 0.4 # in dps
imu.init()
last_accel = [0.0, 0.0, 0.0]
last_gyro = [0.0, 0.0, 0.0]
while True:
rslt, accel, gyro, mag = imu.read_9axis()
if rslt != 0: # not ready, skip this round
time.sleep(0.1)
continue
delta_accel = sum(abs(a - b) for a, b in zip(accel, last_accel))
delta_gyro = sum(abs(a - b) for a, b in zip(gyro, last_gyro))
if delta_accel < THRESHOLD_ACCEL and delta_gyro < THRESHOLD_GYRO:
print("still")
else:
print("moving")
last_accel = accel
last_gyro = gyro
time.sleep(0.1)
Beep when shaken
import imu
import beep
import time
SHAKE_THRESHOLD = 3.0 # m/s^2, lower is more sensitive
imu.init()
last_accel = [0.0, 0.0, 0.0]
while True:
rslt, accel, gyro, mag = imu.read_9axis()
if rslt == 0:
delta = sum(abs(a - b) for a, b in zip(accel, last_accel))
if delta > SHAKE_THRESHOLD:
beep.tone(2000, 100)
last_accel = accel
time.sleep(0.05)
Measuring motion intensity with total acceleration
When you do not care about direction and only want "how hard is it moving", combining the three axes into one number is the simplest approach:
import imu
import math
import time
imu.init()
while True:
rslt, accel, gyro, mag = imu.read_9axis()
if rslt == 0:
total = math.sqrt(accel[0]**2 + accel[1]**2 + accel[2]**2)
print("total accel: {:.2f} m/s^2".format(total)) # about 9.8 at rest
time.sleep(0.2)
Finding which axis gravity is on
Run this once on the real hardware; your "face up / face down" logic will be based on it:
import imu
imu.init()
rslt, accel, gyro, mag = imu.read_9axis()
print("accel while lying flat:", accel)
# The axis with the largest magnitude is the gravity axis.
# Note its sign and use it in your orientation checks.
Complete Example
Firefly T1 apps live on the SD card under /sd/apps/<app folder>/, with boot.py as the entry point. Save the code below as /sd/apps/my-imu-app/boot.py: a short press of the center key prints one 9-axis sample, shaking the device beeps once, and a long press of the center key exits.
import imu
import beep
import time
from button import Button
imu.init() # already initialized by the launcher, returns at once
buttons = Button()
running = True
last_accel = [0.0, 0.0, 0.0]
SHAKE_THRESHOLD = 3.0 # m/s^2, lower is more sensitive
def on_center_short():
rslt, accel, gyro, mag = imu.read_9axis()
if rslt != 0:
print("data not ready, press again")
return
print("accel (m/s^2): {:.2f} {:.2f} {:.2f}".format(*accel))
print("gyro (dps): {:.2f} {:.2f} {:.2f}".format(*gyro))
print("mag (uT): {:.1f} {:.1f} {:.1f}".format(*mag))
def on_center_long():
global running
running = False
buttons.register_callback('center', 'short', on_center_short)
buttons.register_callback('center', 'long', on_center_long)
while running:
rslt, accel, gyro, mag = imu.read_9axis()
if rslt == 0: # skip the round when not ready
delta = sum(abs(a - b) for a, b in zip(accel, last_accel))
if delta > SHAKE_THRESHOLD:
beep.tone(2000, 80) # one beep per shake
last_accel = accel
time.sleep(0.05)
buttons.deinit()
Related modules: 5-Way Button (button), Buzzer (beep), and Power Management (pm).
Troubleshooting
| Symptom | Cause / Fix |
|---|---|
init() returns a negative value | I2C communication failure or the sensor is not responding → use the error code table, and check whether GPIO1/GPIO2 are occupied |
Occasional rslt = -1 | Two reads closer than 10 ms apart, or another thread just consumed the data → skip the round and read again |
Always rslt = -1 | The sensor never produces new data → confirm init() returned 0, and check that pm is not fighting over the same bus |
All three accel values are 0.0 | You used the result without checking rslt → check rslt == 0 before reading the data |
accel shows 9.8 while lying flat | Normal — the unit is m/s² → divide by 9.80665 to get g |
| Tilt detection never triggers | Comparing m/s² against 1.0 → set thresholds on the ±9.8 scale instead |
Almost every read returns rslt = -1 | Reading faster than the 100 Hz sample rate → raise the interval to 20 ms or more |
mag values jump around | Magnets, speakers, motors, or high-current wiring nearby → move the device and retest |
AI Usage (Coming Soon)
Soon you will not have to figure out the three axes yourself or remember when read_9axis() fails: describe the motion behavior you want in plain language, and the Agent will follow the API in this document to generate a complete program that runs on the Firefly T1.
For example, just tell it:
Beep when I shake the device, show an "about to sleep" hint after one minute of lying still, and print the current orientation data on a short press of the center key.
It will combine imu, beep, Button, and pm into a working program and place it in /sd/apps/ for you.
The entry link will go here. Once it is live, one click lets you start describing the app you want.