Making Sounds

Sparki’s buzzer does more than the single tone beep you have probably heard before! In this tutorial, you’ll learn how to make Sparki play music.

What You’ll Need


How It Works

Sparki has a buzzer that can play various tones.

Top - BuzzerSparki and a close up of the buzzer

The voltage causes the buzzer to bend, and it outputs sound waves:

The voltage applied to the piezoelectric speaker causes it to bend and flex.

This bending and flexing moves the air around, and creates what we perceive as sound waves.


Sounds coming out of the speaker

The closer the waves are together, the higher humans perceive the sound to be. The farther away the waves, the lower the sound. By changing the frequency with which the buzzer oscillates, we can bunch up the waves or space them out, making the sound seem higher or lower.

Programming It With Sparki

Using the buzzer from your own program is easy. For example, the following code produces just a small beep:


Now let’s make something a bit more complex: playing different notes. For example, 440 Hz is the frequency of an A note. If you double that frequency, you get the next A note in the music scale.

So, let’s play A notes:

Did you hear the octaves?

Finally, there is another parameter that we can modify on a note, aside from its frequency: its duration. The sparki.beep() let’s you use a second number, after the frequency number. This second number tells how long to beep in milliseconds (one-thousandth of a second). We will use this in the next example.


Making Music

In reality, since all the music you have heard corresponds to a pretty well-established series of notes, we have programmed all those notes in for you to use as constants.

This code uses Sparki basic code, arrays, variables, integers, for loops, and the buzzer. The note pitches are stored in one array, and the note durations are stored in another. This code loops through all of them to play the melody!

This example shows how to make a short melody with Sparki’s buzzer:


Great job! You made Sparki play a song. Can you write a different song and make Sparki play that? How about finding the music online to a favorite song and making it play that?


Lesson available for the miniBloq Programming Environment


This lesson is also available for the miniBloq Programming Environment. miniBloq is a graphical programming environment that you can use to easily program your Sparki.