Turn your micro:bit's lights on or off when you clap.
The new micro:bits have a microphone to help them detect sound.
Let's learn how to use a clap ð to switch your micro:bit's lights on and off!
1. From the Input category, find the on [loud] sound container and add it to your workspace.
Let's begin by creating a variable to keep track of whether the micro:bit's lights are on or off.
2. In the Variables category, click on Make a Variable... and make a variable named lightsOn.
In this step, we'll be using an if then / else statement.
3. From the ð Logic category, grab an ð if <true> then / else block and snap it into your on [loud] sound container.
4. Look in the Variables category. Find the new lightsOn variable and snap it in to replace the ð<true> value in your ð if <true> then / else statement.
5. From Basic, grab show leds and snap it into the top container of your ð if then / else statement.
6. Set the lights to a pattern you like!
In the hint, we chose to turn on all of the outside lights. Feel to make your own design.
7. From Basic, find clear screen and snap it into the bottom container of your ðif then / else section.
ðĄThis will turn the display off if lightsOn is not true.
Just like we'd toggle a light switch, each time we clap, we want to flip the variable lightsOn to the opposite of what it was before.
8. From Variables, locate set [lightsOn] to [0] and snap it in at the very top of your ðīon [loud] sound container.
9. From the ðLogic category, find the ð not <> operator and use it to replace the [0] in set [lightsOn] to [0].
10. From Variables, grab lightsOn and snap it into the empty part of the not <> operator.
11. Check out the simulator!. Click on the pink slider bar beneath the microphone icon and drage it up and down.
ðĄ Right now, your micro:bit thinks that anything above 128 is loud. Every time the sound goes > 128, your lights should switch on/off.
ðĄYour micro:bit might detect sounds when you don't want it to. Setting a sound threshold could help ð
12. Click on the ðīInput category. A new category should show up beneath it called ðī...more.
13. From ðī...more, grab ðīset [loud] sound threshold to [128] and snap it into your empty on start container.
ðĄTry to change the value of your sound threshold so that every time you clap, your lights will turn on if they are off and vice versa.