Skip to content

Activity

Clap-o-meter

Intermediate | MakeCode, Python | LED display, Microphone | Arithmetic operators, Measurement, Selection, Sensors, Variables

Step 1: Make it

What is it?

Measure how long applause - or any loud sound - lasts with this timer that uses the microphone on the new micro:bit.

Introduction

Coding guide

What you'll learn

  • How to trigger events when loud and quiet sound measurements are made by the microphone
  • How to use the micro:bit's built-in timer
  • How to set the threshold for loud and quiet events

How it works

  • At the start of the program the threshold for triggering a loud sound event is set. Use bigger numbers so louder sounds are needed, smaller number for smaller sounds. You can use any number from 0 to 255.
  • A variable called start is set to 0. This is used for tracking when the loud sound began.
  • When the microphone detects a loud sound, the start variable is then set to the micro:bit's current running time and an icon is shown on the LED display so you know the timer has started.
  • Running time is a measure of how long your micro:bit has been running your program in milliseconds (thousandths of a second).
  • When the loud sound stops, a quiet sound event is triggered.
  • If there has already been a loud event, and the timer has started, the start variable will have a value greater (>) 0. In this case a variable called time is set to the new current running time minus the start time. This tells us how long the loud sound lasted.
  • Because the time is measured in milliseconds, the program divides it by 1000 to convert it to seconds and displays it on the LED display.

What you need

  • A micro:bit
  • MakeCode or Python editor
  • battery pack (optional)

Step 2: Code it

1from microbit import *
2microphone.set_threshold(SoundEvent.LOUD, 150)
3start = 0
4
5while True:
6    if microphone.was_event(SoundEvent.LOUD):
7        start = running_time()
8        display.show(Image.TARGET)
9
10    if microphone.was_event(SoundEvent.QUIET):
11        if start > 0:
12            time = running_time() - start
13            start = 0
14            display.clear()
15            sleep(100)
16            display.scroll(time / 1000)

Step 3: Improve it

  • Experiment with different thresholds for loud and quiet sound events to find the values that work best for you.
  • Add code from the Sound logger project so you can also measure how loud the applause was.