Skip to content

Clap Switch

Level Beginner
Board V2 only
Parts micro:bit V2

What you'll build

A clap-controlled lamp: clap once and every LED turns on, clap again and it goes off. A dim dot in the middle shows it's listening.

Code

13 clap-switch.py
'''
Example: Clap switch with the built-in microphone in micro:bit V2
By: Meqdad Darwish
'''
from microbit import *

LAMP = Image("99999:"
             "99999:"
             "99999:"
             "99999:"
             "99999")

# 0-255: raise it if the lamp toggles by itself in a noisy room
microphone.set_threshold(SoundEvent.LOUD, 150)

lamp_on = False
display.set_pixel(2, 2, 2)  # dim dot = listening

while True:
    if microphone.was_event(SoundEvent.LOUD):
        lamp_on = not lamp_on
        if lamp_on:
            display.show(LAMP)
        else:
            display.clear()
            display.set_pixel(2, 2, 2)
        sleep(300)
        microphone.was_event(SoundEvent.LOUD)  # forget the tail of this clap
    sleep(10)

How it works

  • The microphone sits behind the small hole next to the touch logo. The LED beside it lights up while it's in use.
  • microphone.set_threshold(SoundEvent.LOUD, 150) sets how loud (0–255) a sound must be to count as LOUD.
  • microphone.was_event(SoundEvent.LOUD) is True if a loud sound happened since the last check.
  • After a clap, the program waits 300 ms and checks again to throw away the rest of the same clap, so a single clap never toggles the lamp twice.

Tuning

If the lamp toggles by itself, raise the threshold. If it misses your claps, lower it. Scroll microphone.sound_level() to see how loud your room is.

Try this next

  • Require two claps within a second to toggle, so talking doesn't trigger it.
  • Show a live sound meter: map microphone.sound_level() to a bar of LEDs.
  • Send the on/off state to another micro:bit over radio to control a real lamp.