Science Oxford Logo

Connecting & Programming a Speaker

Follow the instructions below to connect your speaker to your robot, then program it to play tunes or beep!

If you have not yet soldered the pin connectors onto your robot, click here.

Wiring

Step 1: collect your supplies

  1. Your robot, with pin connectors
  2. A small speaker
  3. Two jump wires
Components: robot, speaker, wires

Step 2: push the two jump wires onto the two leads of the speaker

Speaker with jump leads attached

Step 3: connect the wires to your robot

Robot with jump leads attached

Notes: information about the components

Programming

Step 1: playing a tune

Open your robot program (if you were at Robocamp, click here to find yours)

You are going to add new code near the top of your program, underneath import radio and above radio.config.

Position of new code, between 'import radio' and 'radio.config'

In this spot, add the following code:

import music
music.play(music.ODE, pin=pin12)

What other tunes can you get the micro:bit to play?


Step 2: creating your own tune

Instead of playing one of the built-in tunes, you can play individual notes and make your own tunes.

Replace your music.play line with this code:

music.play("C4:2", pin=pin12)

You can use notes A-G, with a # after a note to make a sharp, and an R for a rest.

To make a tune, use this format:

my_tune = ["A2:2", "C3:4", "E4:2", "G5:4"]
music.play(my_tune, pin=pin12)


Step 3: using music in your robot code

So far, you have tested code so that it runs at the start of your program.

Think about when you want a your robot to play a tune...

To help your code behave as expected, you can tell the micro:bit not to wait until it has finished the tune before moving on to the next instruction:

music.play(my_tune, pin=pin12, wait=False)