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.You're previewing this lesson. Get full access to this lesson and hundreds more — each one ready to teach, with interactive activities, printable resources and pupil progress tracking built in.