In this activity, you'll create a parking sensor simulation using the Maqueen robot's ultrasonic sensor.
The robot will change its underglow color and beep based on its distance from objects.
BBC micro:bit
Maqueen Robot
18650 Battery
New project at https://python.microbit.org/v/3
Create a program that:
Continuously measures distance using the ultrasonic sensor
Sets the Maqueen's underglow based on distance:
Green for safe distance
Orange for getting close
Red for very close
Beeps with increasing tempo as the robot gets closer to an object
Open the Python editor for micro:bit.
Click on "Project" and then "Open"
Select "Add file" and choose "maqueenplusv2.py"
Here's a basic structure for your program:
from microbit import *
from maqueenplusv2 import *
import music
init_maqueen()
# Define your distance thresholds here
while True:
# Measure distance
distance = rangefinder()
# Your code here:
# 1. Determine colour based on distance
# 2. Set underglow colour
# 3. Control beeping based on distance
# Add a short delay
sleep(100)
First, let's see what kind of values we get from the ultrasonic sensor:
from microbit import *
from maqueenplusv2 import *
import music
init_maqueen()
while True:
distance = rangefinder()
print(distance)
sleep(100)
Run this code and observe the values. Move objects closer to and farther from the sensor. What range of values do you see?
The set_underglow(color) function sets all 4 underglow lights. Colours are specified as hexadecimal values.
Here are some examples:
Green: 0x00FF00
Orange: 0xFFA500
Red: 0xFF0000
Try setting the underglow to different colors based on distance thresholds you define.
You can make the Maqueen beep using the micro:bit's music module.
Try this function:
def beep(wait, volume, frequency):
set_volume(volume)
music.pitch(frequency, 20)
set_volume(0)
music.pitch(frequency, wait)
Experiment with different frequencies, durations and volumes.
How can you make the beeping louder and more frequent as distance decreases?
Use if, elif, and else statements to check distance against your thresholds
You might want to use a mapping function to map distance to beep frequency, volume or interval