Raspberry Pi Pico Digital Compass with QMC5883L & OLED (MicroPython)

Build a Raspberry Pi Pico digital compass with a QMC5883L (GY-271) magnetometer and SSD1306 OLED, with a rotating compass rose, 16-point directions, one-button calibration and a north beep.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCURaspberry Pi Pico (RP2040)
  • Parts7 items
  • CodeMicroPython

Need it ready-made? Buy Ready Project

This Raspberry Pi Pico digital compass shows which way you are facing on a small OLED screen. It reads the Earth’s magnetic field with a GY-271 module (QMC5883L chip) and displays the heading in degrees, a 16-point direction such as NE or SSW, and a compass rose whose N mark always turns to point at magnetic north.

It is a medium-level MicroPython build. You will learn how to share one I2C bus between two devices, read a magnetometer without any extra library, calibrate it to remove errors from nearby metal, and draw graphics on an SSD1306 OLED. A push button switches a north-finding beep on and off, and holding it starts a 20-second calibration that is saved on the Pico.

Raspberry Pi Pico digital compass with QMC5883L GY-271 magnetometer, SSD1306 OLED, push button and buzzer on a breadboard

How It Works

  • Magnetic sensing: the QMC5883L measures the magnetic field on the X, Y and Z axes. The code puts it in continuous mode at 200 Hz with the 8 gauss range and reads six bytes from registers 0x00 to 0x05.
  • Heading: with the board held flat, the heading is atan2(Y, X) converted to degrees. A small declination value (about -1 to +1 degree across India) is added to get closer to true north.
  • Calibration: screws, magnets and the breadboard itself shift the readings. During calibration you turn the compass in slow full circles while the code records the lowest and highest X and Y values. Their middle point is the offset and their spread gives a scale factor. These values are saved in calib.json, so you only calibrate once.
  • Smoothing: raw headings jitter a little. The code averages the heading as a direction vector, so the reading stays steady and does not jump when it crosses from 359 to 0 degrees.
  • Display: the left side of the OLED shows the heading and direction name. The right side draws a dotted compass ring, a fixed marker at the top for the direction the board faces, and a needle with an N that turns to magnetic north.
  • North beep: when the heading is within 5 degrees of north, the buzzer gives a short beep once per second. A short button press turns this on or off.

Components Required

  • Raspberry Pi Pico or Pico W – 1
  • GY-271 magnetometer module with QMC5883L chip – 1
  • 0.96 inch SSD1306 I2C OLED display, 128×64 – 1
  • Tactile push button (6×6 mm) – 1
  • Active buzzer, 3.3V or 5V type – 1
  • Breadboard and male-to-male jumper wires
  • Micro-USB cable, plus a power bank to use it outdoors

Wiring Table

Part / pinPico pinPhysical pinNotes
OLED VCC and GY-271 VCC3V3(OUT)36Both modules run on 3.3V
OLED GND and GY-271 GNDGND38Common ground
OLED SDA and GY-271 SDAGP4 (I2C0 SDA)6Shared I2C data line
OLED SCL and GY-271 SCLGP5 (I2C0 SCL)7Shared I2C clock line
GY-271 DRDYNot connected–Code polls the status register instead
Push button leg 1GP1520Internal pull-up, reads LOW when pressed
Push button leg 2GND23
Buzzer (+)GP1621Active buzzer
Buzzer (-)GND23
PowerMicro-USB–PC or power bank

Connection Diagram

The illustration above shows the parts and how they sit on the breadboard. It is a placement guide only, and its printed pin labels are not exact. The pin-accurate drawing below matches the wiring table, so follow it while you build.

Raspberry Pi Pico Digital Compass – Pin-Accurate Wiring Power Pico 3V3(OUT) pin 36: OLED VCC and GY-271 VCC Pico GND pin 38: OLED GND, GY-271 GND, button, buzzer (-) Power the Pico from micro-USB (PC or power bank) I2C bus (shared) GP4 (pin 6) = SDA: OLED SDA and GY-271 SDA GP5 (pin 7) = SCL: OLED SCL and GY-271 SCL OLED address 0x3C, QMC5883L address 0x0D GY-271 module DRDY pin not used, leave it unconnected Mount it flat, at least 10 cm from magnets, motors and steel Push button One leg to GP15 (pin 20), the other leg to GND Internal pull-up in code; short press = beep on/off, hold 2 s = calibrate Active buzzer Buzzer (+) to GP16 (pin 21), buzzer (-) to GND Beeps once per second while facing north
Pin-accurate connection diagram for the Raspberry Pi Pico digital compass.

MicroPython Code

Flash the latest MicroPython firmware on the Pico and open Thonny. Install the ssd1306 driver (Tools, Manage packages, search “ssd1306”) so that ssd1306.py is on the Pico. Then save the code below on the Pico as main.py. The magnetometer driver is built into the code, so no other library is needed. The code was syntax-checked with Python 3.

# Raspberry Pi Pico Digital Compass with QMC5883L (GY-271) and SSD1306 OLED
# MicroPython - save as main.py on the Pico. Also copy ssd1306.py to the Pico
# (Thonny: Tools > Manage packages > search "ssd1306" > install).
#
# Wiring: OLED and QMC5883L share I2C0 -> SDA = GP4, SCL = GP5, VCC = 3V3, GND = GND
#         Push button GP15 -> GND (internal pull-up), active buzzer GP16 -> GND
#
# Button: short press = north beep on/off, hold 2 s = 20 s calibration.

from machine import Pin, I2C
import math, time, json
import ssd1306

# ---------------- user settings ----------------
DECLINATION = -0.5     # magnetic declination in degrees (India is about -1 to +1)
NORTH_WINDOW = 5       # beep when heading is within +/- this many degrees of north
CAL_FILE = "calib.json"
CAL_TIME_MS = 20000    # rotate the compass slowly for this long during calibration

# ---------------- hardware ----------------
i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
button = Pin(15, Pin.IN, Pin.PULL_UP)
buzzer = Pin(16, Pin.OUT, value=0)
led = Pin(25, Pin.OUT)   # on-board LED (on Pico W use Pin("LED", Pin.OUT))

QMC_ADDR = 0x0D

class QMC5883L:
    """Minimal driver for the QMC5883L 3-axis magnetometer."""
    def __init__(self, bus, addr=QMC_ADDR):
        self.i2c = bus
        self.addr = addr
        self.i2c.writeto_mem(addr, 0x0A, b"\x80")   # soft reset
        time.sleep_ms(10)
        self.i2c.writeto_mem(addr, 0x0B, b"\x01")   # SET/RESET period (datasheet value)
        # 0x1D = OSR 512, range 8 gauss, 200 Hz, continuous mode
        self.i2c.writeto_mem(addr, 0x09, b"\x1D")

    def ready(self):
        return self.i2c.readfrom_mem(self.addr, 0x06, 1)[0] & 0x01

    def read_raw(self):
        """Return raw (x, y, z) as signed 16-bit numbers."""
        t0 = time.ticks_ms()
        while not self.ready():
            if time.ticks_diff(time.ticks_ms(), t0) > 50:
                break
        d = self.i2c.readfrom_mem(self.addr, 0x00, 6)
        def s16(lo, hi):
            v = lo | (hi << 8)
            return v - 65536 if v > 32767 else v
        return s16(d[0], d[1]), s16(d[2], d[3]), s16(d[4], d[5])

# ---------------- calibration (hard-iron + simple soft-iron scale) ----------------
cal = {"xoff": 0, "yoff": 0, "xscale": 1.0, "yscale": 1.0}

def load_cal():
    global cal
    try:
        with open(CAL_FILE) as f:
            cal = json.load(f)
        print("Calibration loaded:", cal)
    except (OSError, ValueError):
        print("No calibration file - hold the button 2 s to calibrate")

def save_cal():
    with open(CAL_FILE, "w") as f:
        json.dump(cal, f)

def calibrate(mag):
    """Rotate the compass flat through several full circles to find min/max."""
    global cal
    xmin = ymin = 32767
    xmax = ymax = -32768
    t0 = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), t0) < CAL_TIME_MS:
        x, y, _ = mag.read_raw()
        xmin, xmax = min(xmin, x), max(xmax, x)
        ymin, ymax = min(ymin, y), max(ymax, y)
        left = (CAL_TIME_MS - time.ticks_diff(time.ticks_ms(), t0)) // 1000
        oled.fill(0)
        oled.text("CALIBRATING", 20, 0)
        oled.text("Rotate slowly", 12, 16)
        oled.text("in full circles", 4, 28)
        oled.text("%2d s left" % left, 28, 48)
        oled.show()
        led.toggle()
        time.sleep_ms(50)
    led.off()
    xr, yr = (xmax - xmin) / 2, (ymax - ymin) / 2
    if xr < 50 or yr < 50:          # did not turn enough, keep old values
        show_message("Cal failed", "Turn more")
        return
    avg = (xr + yr) / 2
    cal = {"xoff": (xmax + xmin) / 2, "yoff": (ymax + ymin) / 2,
           "xscale": avg / xr, "yscale": avg / yr}
    save_cal()
    print("New calibration:", cal)
    show_message("Cal saved", "")

def show_message(line1, line2):
    oled.fill(0)
    oled.text(line1, 0, 24)
    oled.text(line2, 0, 40)
    oled.show()
    time.sleep(2)

# ---------------- heading maths ----------------
POINTS = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
          "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]

def heading_deg(x, y):
    xc = (x - cal["xoff"]) * cal["xscale"]
    yc = (y - cal["yoff"]) * cal["yscale"]
    h = math.degrees(math.atan2(yc, xc)) + DECLINATION
    return h % 360

def cardinal(h):
    return POINTS[int((h + 11.25) // 22.5) % 16]

# Smooth the heading with a vector average so 359 -> 0 does not jump
sx = sy = 0.0
def smooth(h, k=0.25):
    global sx, sy
    sx = sx * (1 - k) + math.cos(math.radians(h)) * k
    sy = sy * (1 - k) + math.sin(math.radians(h)) * k
    return math.degrees(math.atan2(sy, sx)) % 360

# ---------------- drawing ----------------
CX, CY, R = 96, 32, 28   # compass rose centre and radius (right side of screen)

def draw(h, beep_on):
    oled.fill(0)
    oled.text("%3d deg" % (round(h) % 360), 0, 4)
    oled.text(cardinal(h), 0, 22)
    oled.text("Beep:" + ("ON" if beep_on else "OFF"), 0, 54)
    # outer circle (drawn with points)
    for a in range(0, 360, 10):
        r = math.radians(a)
        oled.pixel(int(CX + R * math.sin(r)), int(CY - R * math.cos(r)), 1)
    # the "N" mark rotates so it always points to magnetic north
    n = math.radians(-h)
    nx, ny = CX + (R - 8) * math.sin(n), CY - (R - 8) * math.cos(n)
    oled.line(CX, CY, int(nx), int(ny), 1)
    oled.fill_rect(int(nx) - 4, int(ny) - 4, 9, 9, 0)
    oled.text("N", int(nx) - 3, int(ny) - 3)
    # fixed pointer at the top = direction the board is facing
    oled.fill_rect(CX - 1, CY - R - 3, 3, 5, 1)
    oled.show()

def beep(ms):
    buzzer.on(); time.sleep_ms(ms); buzzer.off()

# ---------------- main loop ----------------
def main():
    try:
        mag = QMC5883L(i2c)
    except OSError:
        show_message("QMC5883L", "not found!")
        print("I2C devices:", [hex(a) for a in i2c.scan()])
        return
    load_cal()
    beep_on = True
    last_beep = 0
    while True:
        # button: short press toggles beep, 2 s hold starts calibration
        if button.value() == 0:
            t0 = time.ticks_ms()
            while button.value() == 0 and time.ticks_diff(time.ticks_ms(), t0) < 2000:
                time.sleep_ms(10)
            if time.ticks_diff(time.ticks_ms(), t0) >= 2000:
                beep(100)
                calibrate(mag)
                while button.value() == 0:
                    time.sleep_ms(10)
            elif time.ticks_diff(time.ticks_ms(), t0) > 40:   # debounce
                beep_on = not beep_on
        x, y, _ = mag.read_raw()
        h = smooth(heading_deg(x, y))
        draw(h, beep_on)
        # short beep once per second while facing north
        off_north = min(h, 360 - h)
        if beep_on and off_north <= NORTH_WINDOW and time.ticks_diff(time.ticks_ms(), last_beep) > 1000:
            beep(40)
            last_beep = time.ticks_ms()
        time.sleep_ms(100)

main()

Calibrating and Testing

  • Run the code. The OLED shows the heading, the direction name and the compass rose.
  • Move away from laptops, speakers and steel tables. Hold the button for 2 seconds until the buzzer beeps and the screen says CALIBRATING.
  • Keep the compass flat and turn it slowly through two or three full circles during the 20 seconds. “Cal saved” means the values are stored in calib.json.
  • Check it against a phone compass app. Point the top of the board north and the reading should be close to 0 degrees, and the buzzer should beep.
  • Look up the magnetic declination for your city and set DECLINATION at the top of the code for the best accuracy.

Troubleshooting

ProblemFix
OLED shows “QMC5883L not found!”Check SDA on GP4 and SCL on GP5. The Shell prints the I2C addresses found. If you see 0x1E instead of 0x0D, your GY-271 has the older HMC5883L chip, which needs a different driver.
OLED stays blankMake sure ssd1306.py is saved on the Pico and the OLED address is 0x3C. Some 1.3 inch displays use the SH1106 chip and need the sh1106 driver.
Heading turns the wrong wayThe X and Y axes on some boards are mirrored. Change atan2(yc, xc) to atan2(-yc, xc) in heading_deg().
Reading is off by 20 degrees or moreCalibrate again, away from metal, and turn it through full circles. Keep the module at least 10 cm from the buzzer and any magnets.
Heading changes when you tilt itThis simple compass has no tilt compensation. Hold it flat, or add an MPU6050 accelerometer to correct for tilt.
“Cal failed” messageThe compass was not turned enough. Hold the button again and make slow, complete circles.

Ideas to Extend

  • Add an MPU6050 for a tilt-compensated compass that works at any angle.
  • Use a Pico W to send the heading to a web page, for a wind vane or an antenna pointer.
  • Add a NEO-6M GPS module and show the direction and distance back to a saved home point.

Leave a Comment