You can already work with inputs and simple programs on the micro:bit. Today you will build a light clapper: clap once and the LEDs light up; clap again and they go off.
Before you build, think: how might the micro:bit tell a clap apart from ordinary talking? You will predict, build step by step, run the program, and fix anything that does not behave as you expect.
Keep this short. Devices ready, MakeCode micro:bit available. Optional predict: before anyone builds, ask what might separate a clap from talking, and park one or two ideas on the board to revisit later. Do not list build steps here. Then move straight into the project.
Go to the makecode.microbit.org website and create a new project.
Model opening makecode.microbit.org and creating a new project on the board. Watch for students editing an old project by mistake. Pairs can share a device if hardware is short. Differentiation: stay with anyone stuck on login or naming the project.
In this project we are going to detect when you clap using the microphone in your Microbit. When we detect a clap we will turn on the LED lights of the Microbit or turn them off if they're already on.
To decide whether to turn them on or off we will need a variable to store if they are currently on or off.
Create a variable called lightOn. and then add the following code to set this variable to false at the start.
let lightOn = false
Key idea: the program must remember whether the lights are on or off between claps. Ask why a variable is needed rather than only showing LEDs. Common bug: variable created but not set to false at the start, so the first branch behaves oddly. Model creating lightOn and initialising it; students then match on their screens.
For detecting the clap, we need to set how loud a sound we need to listen for. To do this we use the set [loud] sound threshold to block.
Add this block into the on start block and set the value to 128 (the range in 0 to 255).
let lightOn = false lightOn = false input.setSoundThreshold(SoundThreshold.Loud, 128)
Explain the threshold as the loudness line the mic must cross. 128 is a starting point, not the final answer. Ask what might happen if the number is too low or too high. Watch for the block placed outside on start. Differentiation: support students to find the sound blocks; extension students can already guess a classroom value to try later.
Now to detect the clap we will use the on [loud] sound block.
Add the following code.
input.onSound(DetectedSound.Loud, function () {
})
This handler runs when the loud threshold is crossed. Ask when this code will run compared with on start. Common mistake: stacking clap logic in forever or on start instead. Model adding the empty on loud sound block, then pause so everyone has it before the if-then-else.
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.