Built-in project · Raspberry Pi Pico W

Pico W tilt controller: MPU6050 points a servo

MicroPython on a Pico W: the tilt of an MPU6050 on I2C1, worked out from gravity and averaged, turns a servo on GP15 to follow it. The whole build, a Raspberry Pi Pico W and 2 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 25 minutes to build and run. Runs in your browser. Free, and no account needed.

The parts retail for about $11. On Mokxi they're free.

The circuit runs here once the page has loaded.

What you'll learn

  • Tilt from gravity using atan2
  • Averaging readings to steady a sensor
  • Reading an MPU6050 over I2C
  • Servo control with a 50 Hz PWM signal
  • Difficulty: Advanced
  • Time: About 25 minutes
  • Board: Raspberry Pi Pico W
  • Parts: 5

How it works

An MPU6050 sits on I2C bus 1, on pins GP6 and GP7. When it is tilted, gravity pulls differently on its axes. The sketch turns that into an angle and moves a servo on GP15 to match.

It reads the acceleration ten times, with 5 ms between reads, and computes the angle from the sideways and vertical acceleration with atan2. Then it averages the ten angles, which steadies the result.

The servo sits at 90 degrees when the sensor is level. A tilt of 20 degrees one way moves it to 110, the other way to 70. The servo gets 5 V power, and the sensor gets 3.3 V.

Parts list

5 parts, plus the jumper wires. They retail for about $11; on Mokxi they're free.

Kits that can build it

These 2 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 pinConnects to
Accelerometer and gyroscope, MPU6050 pin SDARaspberry Pi Pico W pin GP6
Accelerometer and gyroscope, MPU6050 pin SCLRaspberry Pi Pico W pin GP7
Hobby servo pin PWMRaspberry Pi Pico W pin GP15
Accelerometer and gyroscope, MPU6050 pin VCC3.3 V
Accelerometer and gyroscope, MPU6050 pin GNDGround
Hobby servo pin GNDGround
Hobby servo pin VCC5 V

The code

The MicroPython code exactly as the editor opens it. Change a line there and press Run: the board runs it on the official MicroPython firmware, with nothing to compile.

main.py · Raspberry Pi Pico W
# Somatosensory controller: tip the MPU6050 (I2C1, GP6 and GP7) and the
# servo on GP15 follows. The tilt comes from gravity: atan2 of the y and
# z accelerations, averaged over a few readings to steady it.
from machine import I2C, Pin, PWM
from mpu6050 import MPU6050
import math
import time

mpu = MPU6050(I2C(1, sda=Pin(6), scl=Pin(7), freq=400000))
servo = PWM(Pin(15))
servo.freq(50)

def angle(deg):
    deg = min(max(deg, 0), 180)
    servo.duty_u16((500 + int(deg) * 2000 // 180) * 65535 // 20000)

while True:
    total = 0
    for _ in range(10):
        ax, ay, az = mpu.accel()
        total += math.degrees(math.atan2(ax, az))
        time.sleep_ms(5)
    tilt = total / 10
    angle(90 + tilt)
    print("tilt %.0f, servo %.0f" % (tilt, 90 + tilt))
    time.sleep_ms(50)
mpu6050.py · Raspberry Pi Pico W
# mpu6050.py: read an MPU6050's accelerometer and gyroscope over I2C.
# At power-up the chip is asleep; writing 0 to register 0x6B wakes it.
# The default ranges are +-2 g (16384 counts a g) and +-250 degrees a
# second (131 counts a degree a second).
import struct

class MPU6050:
    def __init__(self, i2c, addr=0x68):
        self.i2c = i2c
        self.addr = addr
        i2c.writeto_mem(addr, 0x6B, bytes([0]))

    def raw(self):
        data = self.i2c.readfrom_mem(self.addr, 0x3B, 14)
        return struct.unpack(">hhhhhhh", data)   # ax ay az temp gx gy gz

    def accel(self):
        ax, ay, az = self.raw()[0:3]
        return ax / 16384, ay / 16384, az / 16384

    def gyro(self):
        gx, gy, gz = self.raw()[4:7]
        return gx / 131, gy / 131, gz / 131

Code walkthrough

The key functions of the sketch, and what each one does.

angle main.py

Moves the servo to a given angle. It first limits the angle to between 0 and 180. Then it turns the angle into a pulse between 500 and 2500 microseconds out of a 20000 microsecond period, scaled to the 16-bit number duty_u16 expects.

def angle(deg):
    deg = min(max(deg, 0), 180)
    servo.duty_u16((500 + int(deg) * 2000 // 180) * 65535 // 20000)

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • The servo swings the wrong way This project
    Flip the sign of the tilt, or turn the sensor the other way around, since the angle comes from which axes you use.
  • The servo jitters This project
    Raise the number of readings averaged in the loop, or lengthen the pause at the end.
  • 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.
  • 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.
  • Pins are powered from 5 V, or a 5 V signal goes into a GPIO. The RP2040 pins are 3.3 V only and are not 5 V tolerant. Raspberry Pi Pico W
    Power the board from VBUS or VSYS at 5 V, but keep GPIO signals at 3.3 V. Use a level shifter or a divider for 5 V parts.
  • WiFi code fails to connect, or the on-board LED code does nothing. The LED on the Pico W is not on GP25 like on the plain Pico. Raspberry Pi Pico W
    Use the board's LED_BUILTIN name so the library drives it through the WiFi chip. Join a 2.4 GHz network only, with the right SSID and password, and wait for the link before sending.

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.