13.18 Angle and motion sensors on I²C
The code of this chapter builds, but it has not yet run on the sensors of the lab kit.
The potentiometer of Reading an analog signal reports an angle as a voltage, which the ESP32 has to convert and calibrate. The two sensors of this chapter send numbers instead. The AS5600 reads the angle of a small magnet on the end of a shaft, without touching it, to 4096 steps per turn. The MPU6050 measures acceleration and rotation rate along three axes. Both talk to the ESP32 over the same two wires, the I²C bus, and we read them by asking for the contents of their registers.
The Guide
Step 1: Wire the bus
Both modules get 3.3 V and ground from the ESP32, and both connect their SDA pin to GPIO 21 and their SCL pin to GPIO 22 (Figure 13.18.1). The two signal lines are shared: the four wires of the second module run to the same strips as those of the first. On the AS5600 module, also connect DIR to ground. It selects the direction in which the angle grows, and left open it lets the direction change by itself.
Most sensor modules carry the two pull-up resistors of Figure 13.18.1 on their own board. Check with the meter before going on: with the ESP32 powered and no program running, SDA and SCL both read 3.3 V against ground.
Glue a diametrically magnetised disc magnet, 6 mm across, to the end of a shaft, and hold the AS5600 chip centred over it at a distance of 0.5 to 3 mm. A printed holder that clamps the module to the bearing housing keeps both distances constant.
Step 2: Find the sensors
The project is code/sensors next to this chapter. i2c.h holds three short functions for the bus, as5600.h and mpu6050.h one file per sensor, and main.cpp reads both:
// i2c.h: read and write the registers of a device on the I2C bus
// (SDA on GPIO 21, SCL on GPIO 22, the ESP32's default pins).
#pragma once
#include <Arduino.h>
#include <Wire.h>
// Write one byte into register reg of the device at address
void i2cWrite(int address, int reg, int value) {
Wire.beginTransmission(address);
Wire.write(reg);
Wire.write(value);
Wire.endTransmission();
}
// Read n bytes from the device at address, starting at register reg
void i2cRead(int address, int reg, uint8_t* buf, int n) {
Wire.beginTransmission(address);
Wire.write(reg); // the register to start from
Wire.endTransmission(false); // keep the bus: the read follows at once
Wire.requestFrom((uint8_t)address, (uint8_t)n);
for (int i = 0; i < n; i++) buf[i] = Wire.read();
}
// Print the address of every device that answers
void i2cScan() {
for (int a = 1; a < 127; a++) {
Wire.beginTransmission(a);
if (Wire.endTransmission() == 0) Serial.printf("found a device at 0x%02X\n", a);
}
}Upload the project and open the Serial Monitor. At start-up i2cScan() asks every address in turn whether a device is there, and prints
found a device at 0x36
found a device at 0x68
0x36 is the AS5600 and 0x68 the MPU6050. A missing line means a missing device: check its four wires, and check that SDA and SCL are not swapped. If the AS5600 is found but the program prints AS5600: no magnet, the magnet is too far away or off centre.
Step 3: Angle and speed of a shaft
as5600.h reads the angle as a number from 0 to 4095:
// as5600.h: the AS5600 magnetic angle sensor, address 0x36.
#pragma once
#include "i2c.h"
const int as5600Address = 0x36;
// The angle of the magnet as a number from 0 to 4095 for one turn
int as5600Raw() {
uint8_t b[2];
i2cRead(as5600Address, 0x0C, b, 2); // RAW ANGLE: the upper 4 bits, then the lower 8
return (b[0] & 0x0F) * 256 + b[1];
}
// True when the sensor finds a magnet of the right strength
bool as5600Magnet() {
uint8_t status;
i2cRead(as5600Address, 0x0B, &status, 1); // STATUS
return status & 0x20; // bit 5, MD: magnet detected
}main.cpp reads both sensors every 10 ms and prints four values for Teleplot:
// main.cpp: an AS5600 and an MPU6050 on one I2C bus. Every 10 ms it prints the shaft
// angle and speed, the tilt from gravity and the tilt from the gyro, for Teleplot.
#include <Arduino.h>
#include "i2c.h"
#include "as5600.h"
#include "mpu6050.h"
const int stepMs = 10; // one reading of both sensors every 10 ms
unsigned long lastMs = 0;
int lastRaw = 0; // the AS5600 reading of the previous step
float gyroAngle = 0; // tilt about x from adding up the rotation rate
void setup() {
Serial.begin(115200);
Wire.begin(); // SDA 21, SCL 22, 100 kHz
i2cScan(); // expect 0x36 and 0x68
if (!as5600Magnet()) Serial.println("AS5600: no magnet");
mpuBegin();
lastRaw = as5600Raw();
}
void loop() {
if (millis() - lastMs < stepMs) return;
lastMs = millis();
// Shaft angle and speed from the AS5600
int raw = as5600Raw();
int diff = raw - lastRaw; // counts turned in this step
if (diff > 2048) diff -= 4096; // passed 0 going backwards
if (diff < -2048) diff += 4096; // passed 0 going forwards
lastRaw = raw;
float angle = raw * 360.0 / 4096;
float rpm = diff * 6000.0 / 4096; // counts per 10 ms to turns per minute
// Tilt about the x axis from the MPU6050, two ways
mpuRead();
float tilt = atan2(accY, accZ) * 180 / PI; // from the direction of gravity
gyroAngle = gyroAngle + gyroX * stepMs / 1000.0; // rate times time, added up
Serial.printf(">angle:%.1f\n>rpm:%.0f\n>tilt:%.1f\n>gyro:%.1f\n", angle, rpm, tilt,
gyroAngle);
}Stop the Serial Monitor and open Teleplot. Turn the shaft slowly by hand: angle climbs from 0 to 360 and jumps back to 0 once per turn, and rpm shows the speed, positive one way and negative the other. If angle falls when the shaft turns the way it should count up, move DIR from ground to 3.3 V.
Step 4: Tilt from gravity and from the gyro
mpu6050.h wakes the chip and reads all six values in one go:
// mpu6050.h: the MPU6050 accelerometer and gyroscope, address 0x68.
#pragma once
#include "i2c.h"
const int mpuAddress = 0x68;
float accX, accY, accZ; // acceleration in g, gravity included
float gyroX, gyroY, gyroZ; // rotation rate in degrees per second
// Two bytes, high byte first, as a signed number from -32768 to 32767
int toSigned(uint8_t high, uint8_t low) { return (int16_t)(high * 256 + low); }
void mpuBegin() {
i2cWrite(mpuAddress, 0x6B, 0); // PWR_MGMT_1 = 0: wake up, the chip starts asleep
}
void mpuRead() {
uint8_t b[14];
i2cRead(mpuAddress, 0x3B, b, 14); // acceleration, temperature, rotation: 7 numbers
accX = toSigned(b[0], b[1]) / 16384.0; // range +-2 g: 16384 per g
accY = toSigned(b[2], b[3]) / 16384.0;
accZ = toSigned(b[4], b[5]) / 16384.0;
gyroX = toSigned(b[8], b[9]) / 131.0; // range +-250 deg/s: 131 per deg/s
gyroY = toSigned(b[10], b[11]) / 131.0;
gyroZ = toSigned(b[12], b[13]) / 131.0;
}Lay the MPU6050 module flat on the table and press EN. tilt and gyro both read close to 0°. Tilt the module about its x axis, the arrow printed on the board, by about 45° and hold it: both follow. Now leave the module still on the table for a minute. tilt stays where it is, while gyro wanders away slowly, a few degrees or a few tens of degrees, and does not come back. Tap the module or shake it gently: now tilt jumps, while gyro stays calm.
How It Works
The I²C bus
I²C (inter-integrated circuit) connects many devices with two lines. SCL carries the clock, which the ESP32 drives as the controller, and SDA carries the data in both directions. No device ever drives a line high. Each can only pull it to ground or let it go, and the pull-up resistor brings a released line back to 3.3 V. Two devices that talk at the same time therefore cannot short each other out: a line is low when anyone pulls it low. The resistors must be there, on a module or on the breadboard, and a bus without them reads nothing at all.
Every device has a 7-bit address, fixed by the manufacturer: 0x36 for the AS5600, 0x68 for the MPU6050. A transfer starts with a start condition, SDA falling while SCL is high, followed by the address and one bit that says read or write. The device with that address answers by pulling SDA low for one clock, the acknowledge, and all others stay quiet. i2cScan() uses exactly that: it sends each address and reports those that acknowledge.
Inside, each sensor is a row of numbered registers, one byte each. Reading starts by writing the number of the first register we want, then a repeated start turns the bus round, and the device sends bytes from that register on, one register after the other. That is i2cRead(): Wire.write(reg) sends the register number, endTransmission(false) keeps the bus for the read that follows, and requestFrom() fetches n bytes. Every byte on the bus costs nine clocks, eight bits and an acknowledge. At the default 100 kHz, the 14 bytes of the MPU6050 and their overhead take about 1.7 ms, and the AS5600 another 0.6 ms, well inside the 10 ms step.
The AS5600 and the speed of a shaft
The AS5600 holds an array of Hall sensors that measure the direction of the magnetic field above the chip. A diametrically magnetised magnet, with its north and south poles on opposite sides of the disc, turns that direction with the shaft, so the chip measures the shaft angle without contact and without wear. It reports the angle in 12 bits: 4096 steps per turn, 0.088° each. The value lives in two registers, 0x0C with the upper four bits and 0x0D with the lower eight, and as5600Raw() joins them as \(256 \cdot \text{high} + \text{low}\). Bit 5 of the status register 0x0B says whether the chip sees a magnet of usable strength.
The speed follows from two successive angles. With \(\Delta n\) counts in a step of \(\Delta t = 10\) ms,
\[ n_\text{rpm} = \frac{\Delta n}{4096} \cdot \frac{60}{\Delta t} = \frac{6000}{4096}\,\Delta n \quad \text{for } \Delta t = 0.01~\text{s}. \]
One count per step is therefore 1.46 rpm, the resolution of the speed. When the shaft passes zero, the raw value jumps from 4095 to 0 or back, and the difference comes out near \(\pm 4096\). The two if lines correct that by taking the shorter way round. That works as long as the shaft turns less than half a turn per step, so this program measures up to \(2048 \cdot 1.46 = 3000\) rpm. A faster shaft looks slower, or even reversed, the same effect that makes wheels in films seem to turn backwards.
The MPU6050: acceleration and rotation rate
The MPU6050 holds three accelerometers and three gyroscopes, each a tiny vibrating structure etched in silicon. After power-on the chip sleeps, so mpuBegin() writes 0 to the power register 0x6B. Its fourteen bytes from register 0x3B hold seven signed 16-bit numbers, high byte first: three accelerations, the temperature and three rotation rates. With the default ranges, ±2 g and ±250 °/s, 16 384 counts are one g and 131 counts one degree per second.
An accelerometer at rest measures gravity, 1 g pointing up from the table. Tilted by an angle \(\theta\) about its x axis, the module sees gravity split between its y and z axes, \(a_y = \sin\theta\) and \(a_z = \cos\theta\) in g, so
\[ \theta = \operatorname{atan2}(a_y, a_z). \]
This holds only while gravity is the only acceleration. Any shake or vibration adds its own acceleration, and the computed angle jumps, as Step 4 showed.
The gyroscope measures the rotation rate \(\omega\) directly, and adding up \(\omega \Delta t\) in every step gives the angle. Vibration does not disturb it, but every gyroscope has a small offset: at rest it reports perhaps 0.5 °/s instead of zero. Added up, an offset of 0.5 °/s grows into 30° per minute, and the integrated angle drifts away for good. The two measurements fail in opposite ways: the accelerometer is right on average and noisy moment to moment, the gyroscope is smooth moment to moment and wrong on average. Exercise 3 combines them.
Mounting
Both sensors measure only as well as they are fixed. The AS5600 needs the magnet centred on the chip within a few tenths of a millimetre and at a constant distance; an eccentric magnet gives an angle error that repeats once per turn. The MPU6050 measures the motion of its own board, so it must be screwed or glued to the part we want to measure, not left hanging on its wires, and its axes are those printed on the board.
Exercises
Exercise 1: Speed resolution
Change stepMs to 100. What are the resolution and the highest measurable speed now? Check both on a shaft driven by the motor of the BTS7960 chapter at a few duty values.
Exercise 2: The gyro offset
At start-up, with the module still, average gyroX over 200 readings and subtract that average from every later reading. How far does gyro drift in a minute now?
Exercise 3: A complementary filter
Combine the two tilt angles in every step as
\[ \theta \leftarrow 0.98\,(\theta + \omega_x \Delta t) + 0.02\,\theta_\text{acc}, \]
and plot \(\theta\) next to tilt and gyro while you shake and tilt the module. Which property does \(\theta\) take from each sensor, and what does the factor 0.98 set?
Exercise 4: A faster bus
Measure with micros() how long mpuRead() takes. Then add Wire.setClock(400000); after Wire.begin() and measure again. Compare both with the estimate in The I²C bus.