Controlling Anastasia from a second micro:bit

This is the third in a series of four articles about Anatasia, a home-brew micro:bit based robot.

Here's the full list of articles:

1. The original article introducing the robot.
2. A short update when I released the code on GitHub.
3. This detailed walk-though of the controller code.
4. A detailed walk-through of the code that runs on the robot

The code for Anatasia and her controller is finished. It's simple and it's all working well.

You control Anastasia via a separate hand-held micro:bit, which communicates using the micro:bit's built-in radio.

You tilt the controller and Anastasia responds by advancing, retreating or spinning to the left or right. Anastasia stops when you hold the controller level.

Here's the controller code:

Controller Code


The controller code starts with a bit of set-up

from microbit import *
import radio

# The critical value for tilt detection.
# A lower value makes the controller more sensitive.
RANGE = 250

Next, the say function checks to see if there is a command to send and sends it if necessary.

It returns a boolean value which tells you whether anything was sent.

def say(command):
    if command is not None:
        return True
    return False

The micro:bit has a built-in accelerometer which can be used to detect if the micro:bit is tilted or level.

react_to_tilt checks a value to see how much the micro:bit is tilted.

If the size of the tilt is less than the RANGE value the tilt is ignored. If the tilt is big enough, the appropriate command is returned.

def react_to_tilt(tilt, low, high):
    if tilt > RANGE:
        return high
    if tilt < - RANGE:
        return low
    return None

The check_tilt function measures the tilts in the x and y directions and sends the appropriate command over the radio.

def check_tilt():
    if say(react_to_tilt(accelerometer.get_x(), 'right', 'left')):
    if say(react_to_tilt(accelerometer.get_y(), 'forward', 'backward')):
    # micro:bit is more or less level, so stop the robot.

The final while loop runs forever. It looks for commands to send ten times a second.

while True:
    sleep(100) # on the micro:bit, times are in ms

I'll explain Anastasia's code tomorrow. If you can't wait, the code is already on GitHub.


Popular posts from this blog

Controlling a Raspberry Pi Pico remotely using PySerial

Five steps to connect Jetson Nano and Arduino

Raspberry Pi Pico project 2 - MCP3008