In this lesson, you'll build a sound-sensitive 'light clapper' with your Micro:bit, using its microphone to detect claps and toggle the LED display. You'll use conditional logic in loops to monitor sound levels, functions to handle toggling the display, and lists to store clap patterns for advanced modes like double-clap detection. This reinforces control structures, variables, and functions, turning your Micro:bit into a home automation gadget.
By the end, your Micro:bit will toggle an LED image (like a light bulb) when it detects claps above a threshold. Open the Micro:bit Python editor at python.microbit.org and start a new project.
Start by importing the necessary modules. We'll need the microbit module to access the hardware, including the microphone and display.
Add the following complete code to your editor:
from microbit import *
Let's read the sound level from the microphone and display it. The microphone.sound_level() returns a value from 0 (quiet) to 255 (loud). We'll use a loop to continuously monitor it.
Update your code to this complete version:
from microbit import *
while True:
sound_level = microphone.sound_level()
display.scroll(str(sound_level))
sleep(500)
Now, set a sound threshold (e.g., 100) to detect a clap. Use conditional logic (if
statement) inside the loop to check if the sound level exceeds the threshold, and if so, show a simple image like a heart to indicate detection.
Update your code to this complete version:
from microbit import *
threshold = 100 # Adjust this value based on testing
while True:
sound_level = microphone.sound_level()
if sound_level > threshold:
display.show(Image.HEART)
else:
display.clear()
sleep(100)
if-else
structure is a control structure that checks the condition. We could use a shorter sleep for quicker response.Now, let's add interactivity by toggling the 'light' on and off with each clap. Create a function toggle_light()
to switch the state using a boolean variable light_on
(initially False
).
In the function, use global
to modify light_on
, flip it with not
, and display Image.YES (on)
or Image.NO (off)
accordingly.
In the loop, call the function on clap detection and add sleep(500)
for "debounce" (to prevent multiple toggles from one clap).
Update your code to this complete version:
from microbit import *
threshold = 100
light_on = False # Variable to track light state
def toggle_light():
global light_on
light_on = not light_on # change it to the opposite value (on or off)
if light_on:
display.show(Image.YES) # Represents light on
else:
display.show(Image.NO) # Represents light off
while True:
sound_level = microphone.sound_level()
if sound_level > threshold:
toggle_light()
sleep(500) # Debounce to avoid multiple toggles from one clap
sleep(100)
toggle_light()
, which flips the light_on
variable and updates the display accordingly. The debounce sleep(500)
ensures that after a toggle, the code waits half a second before checking again, giving the sound from one clap time to fade.