Project: "A visual tilt controller"


Lesson 14 of 17 · MicroPython and micro:bit

MicroPython + Processing: Back to the serial connection lesson (SR)


In this project the micro:bit becomes a motion controller, while Processing shows an object that moves in real time.

Tilt the micro:bit ➝ the object moves on the screen.

What is the goal of the project?

In this project we connect:
  • the physical movement of the device
  • serial communication
  • graphic visualisation
It is a real example of an interactive system.

The architecture of the system


micro:bit (accelerometer)
        ↓
uart.write("x,y\n")
        ↓
USB Serial
        ↓
Processing reads the data
        ↓
Moves the object on the screen

The system works as a real-time motion controller.

An important idea:

The micro:bit does not draw graphics. Its job is:
  • to measure the tilt
  • to send the data
Processing then uses that data to draw objects on the screen.

Step 1 — MicroPython code (micro:bit)


The micro:bit sends the tilt values along the X and Y axes.


from microbit import *
import utime

while True:

    # reading the tilt of the device
    x = accelerometer.get_x()
    y = accelerometer.get_y()

    # sending the data as text:
    # x,y\n
    uart.write(str(x) + "," + str(y) + "\n")

    # a short pause between messages
    utime.sleep(0.1)

The message format:

x,y\n
  • x ➝ the tilt along the X axis
  • y ➝ the tilt along the Y axis
  • \n ➝ the end of the message
The data is sent about 10 times a second.

Step 2 — Processing Python Mode (visualisation)


Since students work in Python Mode, we use Python syntax and the Python style of writing code.


add_library('serial')

from processing.serial import *

xPos = 300
yPos = 200

def setup():

    global myPort

    size(600, 400)

    # showing the available ports
    print(Serial.list())

    # connecting to the first serial port
    myPort = Serial(this, Serial.list()[0], 115200)

def draw():

    global xPos, yPos

    background(240)

    # drawing the object
    ellipse(xPos, yPos, 50, 50)

    # we check whether there is data
    while myPort.available() > 0:

        # reading one line
        data = myPort.readStringUntil('\n')

        if data != None:

            # removing blank characters
            data = data.strip()

            # splitting by the comma
            values = data.split(',')

            # checking that we have two values
            if len(values) == 2:

                x = float(values[0])
                y = float(values[1])

                # mapping the sensor to the screen
                xPos = width/2 + x/10
                yPos = height/2 + y/10

Important:

This is code for Processing Python Mode. It is not the same as the classic Java Processing mode.

How does the system work?


  • The micro:bit measures the tilt with the accelerometer
  • It sends the data as a text message
  • Processing reads the complete line
  • The data is split by the comma
  • The object moves in proportion to the tilt

This is an example of a direct connection between physical movement and graphics.

Experiment:

Try the following changes:
  • Change the size of the circle
  • Change the background colour
  • Change the speed of movement
For example:

background(0)
fill(0, 255, 0)

Why do we divide by 10?


The accelerometer values can be very large (often over ±1000).

If we used the original values, the object would move far too fast.

That is why we use:


x/10
y/10

This reduces the range of movement.

Data mapping:

This is an example of turning raw sensor data into a visually usable range. This is called data mapping.

An advanced version (a challenge)


Extend the project:

  • Add borders so that the object does not leave the screen
  • Add a change of colour depending on the tilt
  • Add "inertia" (smooth movement)
  • Add obstacles that have to be avoided

In this way the project turns from a demonstration into a real mini game.

Mini challenge:

Can you make:
  • a maze
  • controlling a car
  • balancing a ball
using only the tilt of the micro:bit?

The teaching goal of the project


Here students learn:

  • how sensor data is transferred
  • how a message format is designed
  • how data is parsed
  • how physical movement is turned into graphics
  • how an interactive system is made

This is a real example of connecting:

  • hardware
  • programming
  • graphics
  • interaction

A mini challenge to think about


How would you make the game "Avoid the walls" where the object moves only by tilting the micro:bit?

Think:

  • Where is the collision checked?
  • Does the micro:bit need to know about the obstacles?
  • Does the logic stay in Processing?
An important idea:

The micro:bit does not have to know anything about the game. Its job can be only:
  • read the sensors
  • send the data
All the game logic can stay in Processing.

In this way you move from a simple visualisation to designing a real interactive system.

An important note for users of Processing 4+


The examples shown in this lesson use Processing Python Mode.

However, in newer versions of Processing (especially Processing 4.x), there can be compatibility problems with some libraries and the Python Mode add-on.

What do we recommend?

There are two reliable paths:
  • Processing 3.5.4 or older — the best for following older tutorials and examples.
  • py5 — a modern solution based on Python 3, which is the recommended direction for new projects.

If you use Processing 4.x or want to move to a more modern Python approach, see the following lessons:

A recommendation for new students:

If you are just starting new projects, we recommend getting to know py5, because it uses standard Python 3 and a more modern development ecosystem.

What does reading from the serial port look like in Python mode?


If you use Processing Python Mode, the code looks different than in Java mode.

The syntax is much closer to standard Python, which often makes it easier for students to understand.

Important:

Processing has different modes of work:
  • Java Mode — the default mode
  • Python Mode — uses Python syntax
Although both use the same Processing engine, the way of writing code is different.

Example — reading data from the micro:bit


This program:

  • reads data from the serial port
  • receives the values x and y
  • moves an object on the screen

# Loading the library for serial communication
add_library('serial')

from processing.serial import *

# Global variables for the position of the object
xPos = 300
yPos = 200

# A variable for the serial port
myPort = None


def setup():

    global myPort

    # The size of the window
    size(600, 400)

    # Showing all available COM ports
    print(Serial.list())

    # Opening the first port found
    myPort = Serial(this, Serial.list()[0], 115200)

    # Processing waits for the end of the line (\n)
    myPort.bufferUntil('\n')


def draw():

    global xPos, yPos

    # The background colour
    background(240)

    # Drawing the object
    ellipse(xPos, yPos, 50, 50)


# This function runs automatically
# when a new line of data arrives
def serialEvent(port):

    global xPos, yPos

    # Reading one line of text
    data = port.readStringUntil('\n')

    # Checking whether something has arrived
    if data != None:

        # Removing blank characters
        data = data.strip()

        # Splitting the text by the comma
        values = data.split(',')

        # We expect 2 values: x and y
        if len(values) == 2:

            # Turning the text into numbers
            x = float(values[0])
            y = float(values[1])

            # Moving the object
            xPos = width/2 + x/10
            yPos = height/2 + y/10

How does the program work?


Let us look step by step at what happens.

1. Loading the serial library



add_library('serial')

from processing.serial import *

With this we include support for:

  • COM ports
  • USB serial communication
  • reading data from the micro:bit
Remember:

Without the serial library Processing cannot communicate with the micro:bit.

2. Opening the serial port



print(Serial.list())

This line shows all available serial ports.

For example:


['COM3', 'COM5']

Then we open the first port found:


myPort = Serial(this, Serial.list()[0], 115200)
  • this ➝ the current Processing sketch
  • 115200 ➝ the communication speed (baud rate)
Important:

The baud rate must be the same in the MicroPython and the Processing program. If the speeds are not the same, the data will not be read correctly.

3. Waiting for the end of the message



myPort.bufferUntil('\n')

This line tells Processing:

"Wait until the new line character arrives."

That lets us read the whole message at once.

For example:


120,-45
Experiment:

Try removing:

bufferUntil('\n')
and watch what happens to the data.

4. The serialEvent() function


The function


def serialEvent(port):

runs automatically when a new message arrives.

That means we do not have to check the port by hand all the time.

An important idea:

This is an example of event-driven programming. The program reacts to an event (the arrival of data).

5. Splitting the data


The micro:bit sends a text message:


120,-45

Processing then uses:


values = data.split(',')

The result is a list:


['120', '-45']

After that,


x = float(values[0])
y = float(values[1])

turns the text into numbers.

6. Moving the object



xPos = width/2 + x/10
yPos = height/2 + y/10

In this way:

  • the tilt of the device affects the position of the object
  • sensor data becomes graphics

Dividing by 10 reduces the sensor values that are too large.

Data mapping:

Turning sensor values into positions on the screen is called data mapping.

Why do we use global?


In Python mode the variables inside a function are local unless we write:


global xPos

In this way Processing knows that we want to change the global variable and not make a new local copy.

A practical rule:

If you change a variable inside a function, and it is defined outside the function, you will often need global.

Java Mode vs Python Mode


Java Mode Python Mode
void setup() def setup()
String[] list
float x x = float()
Semicolon ; No ;
Java syntax Python syntax

Both modes use the same Processing engine, but the syntax is different.

If students already know Python, Python Mode is often the more natural choice.

Mini challenge


Try to extend the program:

  • change the colour of the object when the micro:bit is tilted
  • add more objects
  • add screen borders
  • add "smooth" movement
An idea for a project:

Can you make a mini game in which a ball is controlled only by tilting the micro:bit?

Check your knowledge

Open the quiz

Mini quiz: the tilt controller

1. The accelerometer gives values roughly from -1024 to 1024. Why do we divide by 10?




2. What does "120,-45".split(",") return?