Ada for micro:bit Part 8: Music to my ears
by Fabien Chouteau –
Welcome to the Ada for micro:bit series where we look at simple examples to learn how to program the BBC micro:bit with Ada.
If you haven't already, please follow the instructions in Part 1 to setup your development environment.
In this eighth part we will see how to play some simple music with the micro:bit and a piezo buzzer.
In the analog output example we said that the analog output was actually a Pulse Width Modulation (PWM) signal. When a piezo buzzer is connected to a PWM a note is produced, changing the frequency of the PWM signal means changing the note that the buzzer will play.
For this example we will need a couple of extra parts:
- A breadboard
- A piezo buzzer
- A couple of wires to connect them
MicroBit.Music provides different ways to play music. We are going
to use the procedure that plays a melody. A
Melody is an array of
Note is made of a pitch and a duration in milliseconds. This package
also provides declaration of pitches for the chromatic scale (e.g
So we declare our little melody like so:
My_Little_Melody : constant MicroBit.Music.Melody := ((C4, 400), (G3, 800), (B3, 400), (Rest, 400), (A3, 400), (G3, 400));
Then we simply have to call the procedure
Play of the package
procedure Play (Pin : Pin_Id; M : Melody) with Pre => Supports (Pin, Analog);
- Pin : The id of the pin that the melody will play on
- M : The melody that we want to play
- The procedure
Playhas a precondition that the pin must support analog IO.
Here is the full code of the example:
with MicroBit.Music; use MicroBit.Music; procedure Main is My_Little_Melody : constant MicroBit.Music.Melody := ((C4, 400), (G3, 800), (B3, 400), (Rest, 400), (A3, 400), (G3, 400)); begin -- Loop forever loop -- Play the little melody on pin 0 MicroBit.Music.Play (0, My_Little_Melody); end loop; end Main;
Following the instructions of Part 1 you can open this example (Ada_Drivers_Library-master\examples\MicroBit\music\music.gpr), compile and program it on your micro:bit.
Don't miss out on the opportunity to use Ada in action by taking part in the fifth annual Make with Ada competition! We're calling on developers across the globe to build cool embedded applications using the Ada and SPARK programming languages and are offering over $9,000 in total prizes. Find out more and register today!