17. Music

Another fantastic feature of the micro:bit is its ability to generate musical notes. This makes it very easy indeed for even quite young children to program simple songs.


Task:

Program the micro:bit to play the first few bars of 'Happy Birthday'.


Algorithm:

When button A is pressed.

Display the message Happy Birthday!

Play D

Play D

Play E

Play D

Play G

Play F

Rest

Model:

There is no model for this task. A small piezo sounder that will operate at 3V must be connected between pin0 and GND.

You can use a speaker with a standard 3.5mm jack plug. See the diagram on the right for the connections when using pin0.

Purpose built micro-bit speakers can be purchased for the micro;bit. Typically they have three connections as shown in the image on the right.

PXT Editor script:

Micro Python script:

One for Christmas...

(remember you can copy and paste script into the Micr Python editor)

from microbit import *

import music


tune = ["E4:4", "E4:4", "E4:8", "E4:4", "E4:4", "E4:8", "E4:4", "G4:4", "C4:4", "D4:4", "E4:8", "F4:4", "F4:4", "F4:4", "F4:4", "F4:4",

"E4:4", "E4:4", "E4:2", "E4:2", "E4:4", "D4:4", "D4:4", "E4:4", "D4:8", "G4:8", "E4:4", "E4:4", "E4:8", "E4:4", "E4:4", "E4:8",

"E4:4", "G4:4", "C4:4", "D4:4", "E4:8", "F4:4", "F4:4", "F4:4", "F4:4", "F4:4", "E4:4", "E4:4", "E4:2", "E4:2", "G4:4", "G4:4",

"F4:4", "D4:4", "C4:8"]


while True:

if button_a.is_pressed():

music.play(tune)