Final project: the micro:bit as a game controller

Lesson 17 of 20 · Python and Processing
Environment:
the examples in this lesson are written for Processing Python Mode. If you work in the recommended environment Thonny + py5, most of the code stays the same, and names with a capital letter in the middle are written in lower case with an underscore: mouseX → mouse_x, noStroke() → no_stroke(). See the table of differences.

In this lesson we will use the micro:bit as a game controller for a game made in the Processing Python Mode environment. The data from the tilt sensor is sent over serial communication, and Processing uses it to control objects in real time. This project connects MicroPython, sensors, graphics and game development into one whole.

In this project the micro:bit becomes an interactive game controller. Tilting the device controls the movement, while buttons A and B trigger special actions.


This is a complete real-time system that connects: sensors → serial communication → a graphical game.



Before you continue

This project uses the knowledge from the lesson A visual tilt controller.

If you have not yet done serial communication between the micro:bit and Processing, we recommend that you go through that lesson first.

⬅ See the lesson: A visual tilt controller (SR)

The goal of the project


  • The micro:bit sends the tilt (X, Y)
  • Button A activates a boost (faster movement)
  • Button B gives points
  • Processing shows the game and runs the logic

The key idea:

The micro:bit is the "controller", and Processing is the "game".


The architecture of the system


micro:bit (sensors + buttons)
        ↓
uart.write("x,y,A,B\n")
        ↓
USB Serial
        ↓
Processing (Python Mode)
        ↓
Game: movement + points + boost


MicroPython code (micro:bit)



from microbit import *
import utime

while True:
    x = accelerometer.get_x()
    y = accelerometer.get_y()

    a = button_a.is_pressed()
    b = button_b.is_pressed()

    # sending 4 values in one line
    uart.write(
        str(x) + "," +
        str(y) + "," +
        str(int(a)) + "," +
        str(int(b)) + "\n"
    )

    utime.sleep(0.05)

The message format:

x,y,A,B\n

  • A = boost (0 or 1)
  • B = points (0 or 1)


Processing code (Python Mode – the game logic)


# Processing Python Mode – the serial library is included like this
# (in Java it would be: import processing.serial.*;)
add_library('serial')

x_pos = 350
y_pos = 250
speed_multiplier = 1
score = 0
my_port = None


def setup():
    global my_port
    size(700, 500)
    print(Serial.list())   # list of ports – choose the right index
    my_port = Serial(this, Serial.list()[0], 115200)
    my_port.bufferUntil(10)  # 10 = the new line character


def draw():
    background(30)
    fill(0, 150, 255)
    ellipse(x_pos, y_pos, 50, 50)
    fill(255)
    textSize(20)
    text("Score: " + str(score), 20, 30)


def serialEvent(port):
    global x_pos, y_pos, speed_multiplier, score
    data = port.readStringUntil(10)
    if data is None:
        return
    values = data.strip().split(',')
    if len(values) != 4:
        return
    x = float(values[0])
    y = float(values[1])
    a = int(values[2])
    b = int(values[3])

    # button A = boost
    speed_multiplier = 2 if a == 1 else 1

    # movement and screen borders
    x_pos = constrain(x_pos + (x / 200.0) * speed_multiplier, 25, width - 25)
    y_pos = constrain(y_pos + (y / 200.0) * speed_multiplier, 25, height - 25)

    # button B = points
    if b == 1:
        score += 5


How does the game work?


  • Tilting moves the player
  • Button A speeds up the movement
  • Button B adds points
  • Processing handles everything in real time

Experiment:

Change the divisor in the movement:

x_pos += (x / 100) * speed_multiplier
What happens when you increase or decrease the value?


What do students learn?


  • How a communication protocol is designed
  • How several sensors are combined in one message
  • How data is parsed and validated
  • How a sensor is mapped to movement
  • The basics of 2D game design


Advanced challenges


  • Add more enemies
  • Add lives (a health system)
  • Add a game restart
  • Add a sound on a collision
  • Add difficulty levels


Conclusion


This project connects hardware and software into one whole:

  • micro:bit = sensor and controller
  • Serial = communication channel
  • Processing = graphical game

The final goal:

Students move from "writing code" to understanding a whole interactive system.

How does data travel from the micro:bit to the graphics?


In this lesson we have seen how the micro:bit sends data over serial communication.


Now it is important to understand what happens "behind the scenes" — the whole path of the data.


The key idea:

The micro:bit does not make graphics.
It only sends data, and the computer interprets it.


The data flow in the system


micro:bit → UART → USB → computer → Processing → graphics

  • the micro:bit reads the sensors (tilt, temperature, buttons)
  • uart.write() turns the data into text
  • the USB cable carries the data to the computer
  • Processing reads the incoming messages
  • the data becomes graphics, an animation or a game


What does the micro:bit actually send?


The micro:bit does not send "graphics" or "objects", only plain text.


An example of simple messages:

23
24
25

Processing can turn these values into:

  • the movement of an object
  • a temperature chart
  • a change of colour or an animation


An example of several values in one message


Often two or more values are sent together:

23,512

This can mean:

  • 23 → temperature
  • 512 → light or another sensor

Why a comma?

A comma is a simple "separator" that lets Processing easily split the data with split(',').


A mini experiment in understanding


Think:

If the micro:bit sends:
120,-40
what could
  • the first number mean?
  • the second number mean?
How would you turn it into movement on the screen?


Why is this important?


This is the basis of all systems that connect hardware and software:

  • IoT devices
  • robotics
  • games with sensors
  • interactive installations

In all these systems the same principle applies: the device sends data → the program interprets it.



Both sides of the system


In this lesson you have written both sides of the system: the micro:bit program that sends the data and the Processing program that receives and draws it:

  • reading the serial port (serialEvent, or pyserial in py5),
  • splitting the data with split(','),
  • real-time graphics in draw().

The final idea:

micro:bit = sensor
Processing = brain + graphics

Mini quiz — the game controller (micro:bit ↔ Processing)

Click to check whether you understand the key concepts of the game: serial communication, mapping the tilt to movement and the buttons.

Open the quiz

Mini quiz: the game controller

1. Which micro:bit object sends the X and Y tilt to the computer over the USB cable?




2. Which function in the Processing code is called when a whole line has arrived from the micro:bit (because of my_port.bufferUntil(10))?




3. How does the tilt x change the horizontal position of the player?




4. What does button A do?




5. When does the player get points?







What next?

In this lesson you have learned how the micro:bit sends tilt and button data and how Processing turns it into a real-time game.

In the next lesson you will see ideas for larger projects that you can enter in creative programming competitions – this game is a good starting point for one of them.

Continue: Projects for competitions → (SR)

The same game in py5 (Thonny)

If the serial library does not work in Processing Python Mode (a common problem in Processing 4), make the same project in Thonny with the py5 add-on. Instead of serialEvent() we use the pyserial library and read the data in draw(). In Thonny install it through Tools → Manage packages → pyserial.

# py5, imported mode (Thonny + the py5 add-on). The micro:bit code stays the same.
import serial
import serial.tools.list_ports

x_pos = 350
y_pos = 250
score = 0
ser = None


def find_microbit():
    for p in serial.tools.list_ports.comports():
        description = (p.description or "").lower()
        if "micro:bit" in description or "mbed" in description or p.vid == 0x0D28:
            return p.device
    return None


def setup():
    global ser
    size(700, 500)
    port = find_microbit()
    if port:
        ser = serial.Serial(port, 115200, timeout=0)
    else:
        print("micro:bit not found")


def draw():
    global x_pos, y_pos, score
    background(30)

    # read all the messages that have arrived since the last frame
    while ser and ser.in_waiting:
        line = ser.readline().decode("utf-8", errors="ignore").strip()
        values = line.split(",")
        if len(values) != 4:
            continue
        x, y = float(values[0]), float(values[1])
        boost = 2 if values[2] == "1" else 1
        x_pos = constrain(x_pos + x / 200 * boost, 25, width - 25)
        y_pos = constrain(y_pos + y / 200 * boost, 25, height - 25)
        if values[3] == "1":
            score += 5

    fill(0, 150, 255)
    circle(x_pos, y_pos, 50)
    fill(255)
    text_size(20)
    text("Score: " + str(score), 20, 30)
Before running: close Thonny's connection to the micro:bit (Stop, then the interpreter Local Python 3). Only one program can use the port.