Chapter 7. Sound and Motion

Speakers generate sounds by vibrating.

You can generate those sound vibrations with the same PWM feature you used in Chapter 6 to adjust the intensity of LEDs. By changing the period and length of pulses, you can change the frequency of the sounds. And by using pulses that correspond to musical notes, you can play songs.

You can also use the length of pulses as a signal to a servo (motor), setting the servo to certain angular positions through specific pulse lengths.

Making Music

To play a song, you’ll need a speaker. For this example, use a common and inexpensive piezo speaker.

Wire up the piezo’s positive wire to pin D5 on your Netduino. Wire up the piezo’s negative (ground) wire to the GND pin on your Netduino. Figure 7-1 shows the connections.


Some piezos have legs rather than wires. In most cases, one leg is longer than the other, and the long leg is positive. There may also be faint markings on the piezo indicating which is positive and which is negative. If in doubt, check your piezo’s instructions or datasheet for proper wiring.

Connecting the piezo

Figure 7-1. Connecting the piezo

Create a new Netduino project. Add the following code to the top of your Main routine:

// store the notes on the music scale and their associated pulse lengths
System.Collections.Hashtable scale = new System.Collections.Hashtable();

// low octave
scale.Add("c", 1915u); scale.Add("d", 1700u); scale.Add("e", ...

Get Getting Started with Netduino now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.