MPU6050 servo stabilizer on an Arduino Uno
A self-leveling gimbal on an Uno: tilt the MPU6050 and two servos turn the other way to hold a platform level, through a complementary filter. The whole build, an Arduino Uno and 3 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Advanced About 30 minutes to build and run. Runs in your browser. Free, and no account needed.
The parts retail for about $35. On Mokxi they're free.
What you'll learn
- Tilt from gravity with
atan2 - Tilt from a gyroscope by adding up turning speed
- A complementary filter that blends both
- Measuring elapsed time with
micros() - Moving servos against a tilt to stay level
- Difficulty: Advanced
- Time: About 30 minutes
- Board: Arduino Uno R3
- Parts: 7
How it works
An MPU6050 on A4 and A5 measures tilt two ways. The accelerometer finds the direction of gravity, which is right when the board is still but noisy when it moves. The gyroscope measures turning speed, which is smooth but slowly drifts.
A complementary filter blends them. It trusts the gyro from moment to moment and pulls gently toward the accelerometer. The time constant TAU is a quarter of a second.
The roll servo on pin 9 and the pitch servo on pin 10 turn the opposite way from the tilt. 90 degrees is level, so a roll of +20 sends the roll servo to 70. The servos use their own 5 V supply.
Parts list
7 parts, plus the jumper wires. They retail for about $35; on Mokxi they're free.
Kits that can build it
These 3 starter kits have every part in the circuit. Each kit's page lists what else it can build.
Wiring table
Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.
| Part and pin | Connects to |
|---|---|
| Arduino Uno R3 pin GND | Ground |
| Hobby servo (2) pin PWM | Arduino Uno R3 pin 10 |
| Hobby servo (1) pin PWM | Arduino Uno R3 pin 9 |
| Accelerometer and gyroscope, MPU6050 pin SDA | Arduino Uno R3 pin A4 |
| Accelerometer and gyroscope, MPU6050 pin SCL | Arduino Uno R3 pin A5 |
| Hobby servo (1) pin GND | Ground |
| Hobby servo (1) pin VCC | 5 V |
| Hobby servo (2) pin GND | Ground |
| Hobby servo (2) pin VCC | 5 V |
| Accelerometer and gyroscope, MPU6050 pin VCC | 5 V |
| Accelerometer and gyroscope, MPU6050 pin GND | Ground |
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// MPU6050 servo stabilizer: a two-axis self-leveling gimbal. Tilt the
// MPU6050 and two servos turn the other way to keep a platform level, the
// way a camera gimbal or a model plane's wing leveler does.
//
// MPU6050 SDA to A4, SCL to A5, VCC to 5V, GND to GND
// servos roll on pin 9, pitch on pin 10, from a separate 5 V supply
// with the grounds joined
//
// TILT FROM GRAVITY. Held still, an accelerometer measures only gravity, so
// the way gravity splits between its three axes tells you the tilt:
//
// roll = atan2(ay, az)
// pitch = atan2(-ax, sqrt(ay*ay + az*az))
//
// That is right on a bench and wrong in a moving model, where every bump
// and turn adds acceleration that is not gravity.
//
// TILT FROM THE GYRO. The gyroscope measures how fast the board is turning,
// in degrees per second. Add that up over time and you also have the tilt,
// smooth and unbothered by bumps, but every tiny error adds up too and the
// angle slowly drifts away.
//
// THE COMPLEMENTARY FILTER uses each for what it is good at: trust the gyro
// from moment to moment, and pull gently toward the accelerometer so the
// drift cannot build up.
//
// alpha = TAU / (TAU + dt)
// angle = alpha * (angle + rate * dt) + (1 - alpha) * accelAngle
//
// TAU is the filter's time constant, a quarter of a second here: after a
// tilt the angle covers about two thirds of the way to the accelerometer's
// answer in TAU, and nearly all of it in four TAU. Working alpha out from
// dt on every pass keeps that true however long a pass takes. Reading the
// sensor and the floating-point math take time too, so a pass is longer
// than the 10 ms delay at the end of loop().
//
// THE SERVOS hold the platform level by turning the same amount the other
// way: 90 degrees is level, so a roll of +20 sends the roll servo to 70.
#include <Wire.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Servo.h>
Adafruit_MPU6050 mpu;
Servo rollServo, pitchServo;
const float TAU = 0.25; // the filter's time constant, in seconds
const float DEGREES = 180.0 / M_PI;
// If a servo turns the same way as the tilt on your build, set its entry
// to -1 so it turns the other way.
const int ROLL_DIRECTION = -1;
const int PITCH_DIRECTION = -1;
float roll = 0, pitch = 0; // the filtered tilt, in degrees
unsigned long lastMicros = 0;
unsigned long lastPrint = 0;
void setup() {
Serial.begin(115200);
if (!mpu.begin()) {
Serial.println("no MPU6050 at 0x68: check SDA, SCL and VCC");
while (true) delay(10);
}
rollServo.attach(9);
pitchServo.attach(10);
rollServo.write(90);
pitchServo.write(90);
// Start the filter from the accelerometer, so it does not have to swing
// up from zero at power on.
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
roll = atan2(a.acceleration.y, a.acceleration.z) * DEGREES;
pitch = atan2(-a.acceleration.x, sqrt(a.acceleration.y * a.acceleration.y + a.acceleration.z * a.acceleration.z)) * DEGREES;
lastMicros = micros();
Serial.println("stabilizer: drag the MPU6050 to tilt it");
}
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
// How long since the last pass, in seconds.
unsigned long now = micros();
float dt = (now - lastMicros) / 1000000.0;
lastMicros = now;
// Tilt from gravity alone.
float ax = a.acceleration.x, ay = a.acceleration.y, az = a.acceleration.z;
float accelRoll = atan2(ay, az) * DEGREES;
float accelPitch = atan2(-ax, sqrt(ay * ay + az * az)) * DEGREES;
// The complementary filter. The gyro reads radians per second.
float alpha = TAU / (TAU + dt);
roll = alpha * (roll + g.gyro.x * DEGREES * dt) + (1 - alpha) * accelRoll;
pitch = alpha * (pitch + g.gyro.y * DEGREES * dt) + (1 - alpha) * accelPitch;
// Turn each servo against its tilt, held to its travel.
int rollAngle = constrain(90 + ROLL_DIRECTION * (int)lround(roll), 0, 180);
int pitchAngle = constrain(90 + PITCH_DIRECTION * (int)lround(pitch), 0, 180);
rollServo.write(rollAngle);
pitchServo.write(pitchAngle);
// Report five times a second.
if (millis() - lastPrint >= 200) {
lastPrint = millis();
Serial.print("roll ");
Serial.print(roll, 1);
Serial.print(" pitch ");
Serial.print(pitch, 1);
Serial.print(" -> roll servo ");
Serial.print(rollAngle);
Serial.print(" pitch servo ");
Serial.println(pitchAngle);
}
delay(10);
}
Code walkthrough
The key functions of the sketch, and what each one does.
setup sketch.ino
Starts the sensor and stops with a message if it is not found. Then it attaches the servos and centers them at 90. It also starts the filter from the accelerometer's reading, so the angle does not have to climb up from zero at power on.
void setup() {
Serial.begin(115200);
if (!mpu.begin()) {
Serial.println("no MPU6050 at 0x68: check SDA, SCL and VCC");
while (true) delay(10);
}
rollServo.attach(9);
pitchServo.attach(10);
rollServo.write(90);
pitchServo.write(90);
// Start the filter from the accelerometer, so it does not have to swing
// up from zero at power on.
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
roll = atan2(a.acceleration.y, a.acceleration.z) * DEGREES;
pitch = atan2(-a.acceleration.x, sqrt(a.acceleration.y * a.acceleration.y + a.acceleration.z * a.acceleration.z)) * DEGREES;
lastMicros = micros();
Serial.println("stabilizer: drag the MPU6050 to tilt it");
}loop sketch.ino
Reads the sensor and measures dt, the time since the last pass. It works out the tilt from gravity, then blends it with the gyro using alpha, which is recomputed each pass from dt. The servo angles are 90 plus a direction sign times the tilt, held to 0 to 180. It prints five times a second.
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
// How long since the last pass, in seconds.
unsigned long now = micros();
float dt = (now - lastMicros) / 1000000.0;
lastMicros = now;
// Tilt from gravity alone.
float ax = a.acceleration.x, ay = a.acceleration.y, az = a.acceleration.z;
float accelRoll = atan2(ay, az) * DEGREES;
float accelPitch = atan2(-ax, sqrt(ay * ay + az * az)) * DEGREES;
// The complementary filter. The gyro reads radians per second.
float alpha = TAU / (TAU + dt);
roll = alpha * (roll + g.gyro.x * DEGREES * dt) + (1 - alpha) * accelRoll;
pitch = alpha * (pitch + g.gyro.y * DEGREES * dt) + (1 - alpha) * accelPitch;
// Turn each servo against its tilt, held to its travel.
int rollAngle = constrain(90 + ROLL_DIRECTION * (int)lround(roll), 0, 180);
int pitchAngle = constrain(90 + PITCH_DIRECTION * (int)lround(pitch), 0, 180);
rollServo.write(rollAngle);
pitchServo.write(pitchAngle);
// Report five times a second.
if (millis() - lastPrint >= 200) {
lastPrint = millis();
// ... 11 more lines in the editorTroubleshooting
The usual mistakes with this circuit, and the fix for each.
- A servo tilts the same way as the board instead of against it This project
ChangeROLL_DIRECTIONorPITCH_DIRECTIONto 1. - The sketch stops with no MPU6050 at 0x68 This project
Check that SDA goes to A4 and SCL goes to A5, with VCC and GND. - The servos twitch or the Uno resets This project
Power the servos from the separate 5 V supply, and join the grounds. - The servo jitters, twitches or resets the board when it moves. Hobby servo
Power it from its own 5 V supply, not the Arduino 5 V pin, and join the grounds. A hobby servo can pull several hundred milliamps. Add a 100 uF to 470 uF capacitor across its supply. - The servo hums at the end of its travel or will not reach full angle. Hobby servo
Stay inside the pulse range, about 1000 to 2000 us for most hobby servos. Pushing past the end stop makes it strain. Calibrate the min and max pulse for your servo. - The sensor is not found or reads all zeros. Accelerometer and gyroscope
Check SDA and SCL (A4 and A5 on an Uno), power, and ground. The I2C address is 0x68, or 0x69 if AD0 is high. The chip starts in sleep mode, so write 0 to the power register PWR_MGMT_1. - The values look wrong or the angles drift. Accelerometer and gyroscope
Raw readings are counts, not g or degrees per second. Divide by the scale for your range (16384 per g at 2 g). Gyro angles drift, so blend with the accelerometer using a filter. - Upload fails or nothing runs after wiring pins 0 and 1 to a module. Arduino Uno R3
Pins 0 and 1 are the USB serial port. Move the module to other pins, or unplug it while uploading. Also check the right board is selected.
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.