micro:bit Pocket Doorbell: Ding Dong
Press button A and the onboard speaker plays a two-note doorbell. Button B plays a built-in tune; a note shows while it plays and a house while it waits. music.play plays the notes. No extra parts are needed.

Video
Circuit Diagram

Source Code
1# ─────────────────────────────────────────
2# BlueGrays · bluegrays.com
3# micro:bit Pocket Doorbell: Ding Dong
4# ─────────────────────────────────────────
5# Press button A and the onboard speaker plays a two-note doorbell. Button
6# B plays one of the built-in tunes. A note shows while it plays and a
7# house while it waits. No extra parts are needed.
8#
9# Pins:
10# LED -> Onboard 5x5 LED display
11# P5 -> Onboard button A
12# P11 -> Onboard button B
13# SPEAKER -> Onboard speaker
14
15from microbit import *
16import music
17
18# ============ SETTINGS ============
19VOLUME = 150 # Volume, 0-255
20LOOP_MS = 50 # Loop pause (ms)
21
22# How a note is written: the letter is the note, the number the octave, and the number after the
23# colon the length.
24DING_DONG = ["e5:4", "c5:8"]
25
26set_volume(VOLUME)
27display.show(Image.HOUSE)
28
29while True:
30 if button_a.was_pressed():
31 display.show(Image.MUSIC_QUAVERS)
32 music.play(DING_DONG)
33 display.show(Image.HOUSE)
34 elif button_b.was_pressed():
35 display.show(Image.MUSIC_CROTCHET)
36 music.play(music.POWER_UP) # Built-in tune
37 display.show(Image.HOUSE)
38 sleep(LOOP_MS)
39FAQ
How do I write my own tune?
Each note is written in quotes: the letter is the note (c, d, e, f, g, a, b), then comes the octave and, after a colon, the length. "c4:4" means middle C for one beat, and r is a rest. Split the notes with commas and put them inside square brackets.
Which built-in tunes are there?
The music module has more than twenty built-in tunes, such as music.POWER_UP, POWER_DOWN, BA_DING, JUMP_UP, BIRTHDAY, WEDDING, ODE, ENTERTAINER, NYAN. Just write one of them in place of music.POWER_UP in the code.
How do I put this code on the micro:bit?
The code is MicroPython. Open the micro:bit Python Editor (python.microbit.org) on a computer, delete the code that is there and paste this one. Connect the board with a USB cable and press Send to micro:bit. If that button does not work, use Save to download the .hex file and copy it to the drive called MICROBIT. You can rebuild the same project with blocks in MakeCode, but this code cannot be pasted there.
Does it work on the older micro:bit (V1) too?
The code is written for the micro:bit V2. Projects that only use the LED display, buttons A and B and the accelerometer also run on a V1. The speaker, the microphone and the touch logo exist only on the V2, so code that uses them gives an error on a V1. If your board has a speaker on the back and a gold logo on the front, it is a V2.
