micro:bit → py5 communication over the serial port
Goal: Controlling graphics on the computer with a micro:bit
So far we have used:
- the micro:bit for reading sensors
- serial communication for sending data
- Processing Python Mode for showing graphics
Now we will do the same using py5.
That way we get:
- modern Python 3
- support for pyserial
- easier use of additional libraries
- a more modern development environment
The micro:bit becomes a controller. It sends data about movement, and py5 turns it into graphics on the screen.
What does the data flow look like?
In this project the data travels in this order:
micro:bit
↓
UART
↓
USB cable
↓
COM port
↓
pyserial
↓
py5
↓
graphics on the screen
So:
- the micro:bit sends the data
- pyserial receives it
- py5 shows it
py5 does not read the serial port directly. For communication it uses the
pyserial library.
The program for the micro:bit
The micro:bit will:
- read the tilt of the device
- send the X and Y values
- send a new message ten times a second
from microbit import *
import utime
uart.init(baudrate=115200)
while True:
x = accelerometer.get_x()
y = accelerometer.get_y()
uart.write(
str(x) + "," +
str(y) + "\n"
)
utime.sleep(0.1)
The messages that reach the computer look like this:
120,-45
135,-60
100,-80
Every line contains:
- the X component of acceleration
- the Y component of acceleration
Installing the pyserial library
If it is not installed yet:
pip install pyserial
or:
python -m pip install pyserial
Without this library Python cannot access COM ports.
Run:
pip show pyserial
If you see information about the package,
the installation was successful.
How do you find the COM port?
Before we write the program, we have to find out which COM port the micro:bit uses.
You can use:
- Device Manager (Windows)
- ls /dev/tty* (Linux)
For example:
COM5
or:
/dev/ttyACM0
Unplug the micro:bit, then list the ports again. Which port has disappeared? That is most likely the micro:bit.
The first py5 program that receives data
This program:
- opens the COM port
- receives the X and Y values
- draws a ball
- moves the ball when you tilt the micro:bit
import py5
import serial
x_pos = 300
y_pos = 200
ser = serial.Serial(
"COM5",
115200,
timeout=0.1
)
def setup():
py5.size(600, 400)
def draw():
global x_pos
global y_pos
py5.background(240)
while ser.in_waiting:
line = (
ser.readline()
.decode("utf-8")
.strip()
)
values = line.split(",")
if len(values) == 2:
x = float(values[0])
y = float(values[1])
x_pos = py5.width/2 + x/10
y_pos = py5.height/2 + y/10
py5.circle(
x_pos,
y_pos,
50
)
py5.run_sketch()
Be sure to replace
"COM5"
with the real port on your computer.
How does the program work?
1. Opening the serial port
ser = serial.Serial(
"COM5",
115200
)
Here we set up the connection with the micro:bit.
The speed must be the same as in the MicroPython program.
2. Reading a message
line = ser.readline()
It reads one complete line of text.
For example:
120,-45
3. Splitting the values
values = line.split(",")
We get:
["120", "-45"]
4. Converting to numbers
x = float(values[0])
y = float(values[1])
We convert the text into numeric values.
5. Drawing the object
py5.circle(
x_pos,
y_pos,
50
)
Based on the data from the sensor, the position of the object on the screen changes.
Why do we divide by 10?
The accelerometer can return values roughly between:
-1024 ... +1024
That is much more than the dimensions of the screen.
That is why we use:
x/10
y/10
to get slower and clearer movement.
Try:
x/5x/20x/50
How do you make the movement smooth?
Sensors always contain a small amount of noise.
Because of that the object can tremble slightly.
A simple solution is averaging:
x_pos = 0.9*x_pos + 0.1*new_x
y_pos = 0.9*y_pos + 0.1*new_y
This technique is called:
- smoothing
- a low-pass filter
- exponential averaging
When controlling a ball or a paddle, smoothing almost always gives a more pleasant playing experience.
Mini challenge
Extend the program so that it:
- changes the colour of the ball
- adds more objects
- shows the numeric values of the sensor
- adds screen borders
- uses smoothing
Can you make a Pong game in which the paddle is controlled only by tilting the micro:bit? It is one of the most popular first projects that connects sensors, serial communication and graphics.
Without typing the port by hand (COM5)
Instead of typing "COM5", the program can find the micro:bit among the connected devices by itself:
import serial
import serial.tools.list_ports
def find_microbit():
"""Returns the name of the port the micro:bit is on (or None)."""
for port in serial.tools.list_ports.comports():
description = (port.description or "").lower()
# the micro:bit reports itself as "mbed" or "micro:bit"; VID 0x0D28
if "micro:bit" in description or "mbed" in description or port.vid == 0x0D28:
return port.device
return None
port_name = find_microbit()
if port_name is None:
print("micro:bit not found – check the USB cable.")
else:
ser = serial.Serial(port_name, 115200, timeout=0.1)
The same example in Thonny with the py5 add-on (imported mode) is written without py5. in front of the functions – see the table of differences and the final project the micro:bit as a game controller (SR).
Check your knowledge
Open the quiz
Mini quiz: micro:bit and py5
1. What does ser.in_waiting mean?
2. Why do we read all messages in a while loop in draw()?
