Skip to content

micro:bit Serial Communication

Level Intermediate
Board V1 & V2
Runs on micro:bit + your computer (standard Python)
Parts micro:bit · USB data cable · Computer with Python 3

What you'll build

A two-way link over the USB cable. The micro:bit becomes a sensor station: it streams its temperature and light level every second and reports button presses and shakes. A Python script on your computer turns those messages into a readable live log, decides whether it is too hot, and replies. The micro:bit then shows a tick (✅) or a cross (❌).

Listening to the micro:bit on COM19 (Ctrl+C to stop)
Temperature: 24 C | Light: 132 (dim) -> OK
Button A pressed
Temperature: 29 C | Light: 210 (bright) -> ALERT
Gesture detected: shake

The message format

Both sides agree on a tiny text protocol: one message per line, fields separated by commas.

Direction Message Meaning
micro:bit → computer SENSORS,24,132 Temperature in °C, light level 0–255 (every second)
micro:bit → computer BUTTON,A / BUTTON,B A button was pressed
micro:bit → computer GESTURE,shake The micro:bit was shaken
computer → micro:bit OK Temperature is fine: show a tick
computer → micro:bit ALERT Temperature ≥ 28 °C: show a cross

Code

Flash this to the micro:bit.

10 microbit serial sender.py
'''
Example: micro:bit Serial Communication (micro:bit side)
Flash this to the micro:bit, then run "10 microbit serial.py" on your computer.

Every message is one line of comma-separated text:
    SENSORS,<temperature C>,<light 0-255>   every second
    BUTTON,A / BUTTON,B                     when a button is pressed
    GESTURE,shake                           when the micro:bit is shaken

The computer replies with one word per line, shown on the LED matrix:
    OK    -> tick       ALERT -> cross (too hot)

By: Meqdad Darwish
'''
from microbit import *

REPORT_EVERY_MS = 1000
last_report = running_time()

while True:
    if button_a.was_pressed():
        print("BUTTON,A")
    if button_b.was_pressed():
        print("BUTTON,B")
    if accelerometer.was_gesture("shake"):
        print("GESTURE,shake")

    if running_time() - last_report >= REPORT_EVERY_MS:
        print("SENSORS,{},{}".format(temperature(), display.read_light_level()))
        last_report = running_time()

    if uart.any():
        reply = uart.readline()
        if reply:
            command = str(reply, "utf-8").strip()
            if command == "OK":
                display.show(Image.YES)
            elif command == "ALERT":
                display.show(Image.NO)

    sleep(20)

Run this on your computer with standard Python.

10 microbit serial.py
'''
Example: micro:bit Serial Communication (computer side)
CAUTION: this runs on your computer with standard Python, NOT on the micro:bit.
Flash "10 microbit serial sender.py" to the micro:bit first, then run this script.

pip install pyserial
By: Meqdad Darwish
'''
import serial

PORT = "COM19"  # Windows: Device Manager > Ports | Linux: /dev/ttyACM0 | macOS: /dev/cu.usbmodem*
BAUD = 115200
HOT_TEMPERATURE = 28  # degrees C; at or above this the micro:bit shows a cross


def describe_light(level):
    if level < 50:
        return "dark"
    if level < 150:
        return "dim"
    return "bright"


def take_action(temperature):
    return "ALERT" if temperature >= HOT_TEMPERATURE else "OK"


def handle_message(line, port):
    kind, _, payload = line.partition(",")

    if kind == "SENSORS":
        try:
            temperature, light = (int(value) for value in payload.split(","))
        except ValueError:
            print("Malformed sensor reading:", line)
            return
        reply = take_action(temperature)
        print("Temperature: {} C | Light: {} ({}) -> {}".format(
            temperature, light, describe_light(light), reply))
        port.write((reply + "\n").encode("utf-8"))
    elif kind == "BUTTON":
        print("Button {} pressed".format(payload))
    elif kind == "GESTURE":
        print("Gesture detected: {}".format(payload))
    else:
        print("Unknown message:", line)


def main():
    with serial.Serial(PORT, BAUD, timeout=1) as port:
        print("Listening to the micro:bit on {} (Ctrl+C to stop)".format(PORT))
        while True:
            line = port.readline().decode("utf-8", errors="replace").strip()
            if line:
                handle_message(line, port)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nStopped.")

Run it in this order

  1. Flash 10 microbit serial sender.py to the micro:bit.
  2. On your computer: pip install pyserial, then set PORT to your micro:bit's port — COM3-style on Windows (Device Manager → Ports), /dev/ttyACM0 on Linux, /dev/cu.usbmodem… on macOS.
  3. Close the Python Editor's serial monitor (or any other program using the port), then run python "10 microbit serial.py". Only one program can open the serial port at a time.

How it works

On the micro:bit

  • print() sends text over the USB cable at 115200 baud and adds a line ending, so every print is one message.
  • running_time() tracks milliseconds, so sensors are reported once per second without sleep(1000) blocking the button and shake checks.
  • uart.any() checks for a reply without waiting; uart.readline() reads it as bytes, which str(reply, "utf-8").strip() turns into "OK" or "ALERT".

On the computer

  • port.readline() waits (up to the 1-second timeout) for a complete line, so messages are never split.
  • handle_message() splits the line at the first comma to find the message type, then handles each type. Malformed lines are reported instead of crashing the script.
  • take_action() holds the decision: change HOT_TEMPERATURE to set when the alert fires.
  • port.write(b"OK\n") sends the reply back down the same cable.

About the temperature

temperature() reads the micro:bit's processor, which runs a few degrees warmer than the room — adjust HOT_TEMPERATURE to suit your board.

Try this next

  • Save every SENSORS reading to a CSV file and plot it with a spreadsheet or matplotlib.
  • Add a SOUND message using the V2 microphone's microphone.sound_level().
  • Let button B ask the computer for the time and scroll the reply on the micro:bit.
  • Combine with Radio Messaging: one micro:bit plugged into the computer relays readings from wireless micro:bits around the room.