Lessons and the learning game

Accelerometers, gyros and IMUs

What a motion sensor really measures, turned into tilt, heading, steps and taps, ending in a level and a compass that stays true when you tip it.

What the course teaches

Accelerometers, gyros and IMUs is seven lessons on the Uno, in four chapters:

  • Which way is down: gravity as a vector on an MPU6050 read straight from its registers, raw counts and ranges, and tilt from asin and atan2 on an ADXL345 spirit level.
  • Turning and drifting: a gyro added up into an angle, the drift its offset causes, calibrating it out at rest, and the complementary filter with its time constant.
  • North, steps and taps: a magnetometer compass, why tipping it throws it off by tens of degrees, declination, and a pedometer and tap detector built from thresholds, hysteresis and timing.
  • Boss build: a builder's level with a green and a red LED and a tilt-compensated compass on an MPU-9250.

Each chapter ends in a short quiz. Open it from /learn.

The circuits

Two lessons open gallery builds: Tilt level (an ADXL345 on the GY-291 board) and Nine axes (an LSM6DSOX and an LIS3MDL on one I2C bus). The rest run sketches written for the course, all on the Uno's A4 and A5:

sketch parts what it does
imugravity MPU6050 the three axes in g, the length of the vector, raw counts, a typed bump
imugyro MPU6050 the gyro added up beside the accelerometer, and cal to remove the offset
imucomp MPU6050 a complementary filter scored against the clean reading, and a typed bump
imustep ADXL345 a step counter with cadence, single and double taps
imuboss MPU-9250, two LEDs level, compass points and a tilt-compensated heading

Why some sketches add noise

The simulated sensors are perfect: no noise, no offset, no drift. A real MPU6050's gyro reads a fraction of a degree per second when it is still, and its accelerometer shakes. The drift and filter lessons add those flaws in the sketch, with the numbers at the top (BIAS_DPS, NOISE_DPS, ACCEL_NOISE_G), so what you see is what a real board does. The noise is seeded, so a run gives the same numbers every time.

The simulated accelerometers also feel only gravity through their tilt, not a push. The pedometer walks by rocking the pitch, and the bump commands add the push in code.

Troubleshooting

  • Every reading is 0. The MPU6050 powers up asleep. Its sketch writes 0 to register 0x6B first; keep that line.
  • The g numbers are four times too small. The range in register 0x1C changed and the counts-per-g constant did not.
  • The compass is way off. It is tipped: the flat formula only works flat. Use the boss build's tilt compensation.
  • No steps count. The swing has to pass STEP_HIGH and come back under STEP_LOW each time. Rock further, or lower the threshold.

The next course, Sensor fusion and the Kalman filter, picks the mix from the noise numbers and learns the gyro's offset while it runs.