Learning Functions with Microbit

Ed update: This blog was published in MicroMag Issue 6 Nov 2016.
The Microbit can be used to create music. I recently watched the MicroMonsters YouTube video. The video is easy to follow and the purpose of the video is to learn to use a Piezo speaker. So of course I composed the code but I found the code very long and complex.
Then I wondered how can you simplify the code to make it shorter and easier to manage.
Definition
Functions are a way to store information that can called at anytime during the program. Functions remove the need to type the same code over and over and allow you to reuse repetitive pieces of code. This reduces the number of lines of code and errors.Example
For example, the tune of Star Wars has several parts that are repeated throughout the song. By creating a Function for each repeating part it is possible to use the function multiple times. This creates simpler code.The first phrase of Star Wars can be rewritten as SWIntro. It contains the opening phrase of Star Wars Da Da Da Dum Da "G, G, G, C, G". Instead of writing these 5 notes every time they can be replaced with the Function SWIntro.



The 3rd series of notes in the Star Wars these is "F, E, F, D" This series of notes is replaced with SW3rdPhrase.

Because the music goes for a long time it is important to be able to stop the music. To do this you can add another event called On Button B pressed. When you press Button B we want to reset the code to start. This will turn off the music and replace it with a cleared screen.
In the original video they used a control block to trigger the Star Wars introduction text to play in the background while the music is playing.
A long long time ago, in a galaxy far far away...
The way the code was written in the video the text starts playing immediately. I wanted the text to scroll when Button A was pressed and not before.

Here is a picture of the completed code, it will play the Star Wars theme. Button A will trigger the theme to play 3 times. When Button A lifts up after being depressed it will also trigger the Star Wars text to scroll. Button B will reset the program or stop the music.
Comments
Post a Comment