Using PWM pins with the Piezo element

Piezo elements can be really fun—you can use them to simply add music to your Johnny-Five projects. We're going to build a small project and play with some of the Johnny-Five utilities to make music with this fun little component.

Setting up the hardware

Wiring a Piezo is pretty straightforward—you need to determine the + and - sides first. Usually, the + side is marked on the top of the plastic casing of the Piezo, and one leg is longer—much like an LED, the longer leg denotes the + side. Finally, some Piezo buzzers come with lead wires that are red (the + side) and black (the - side).

Once you've determined the + side, wire it to pin 3, and wire the - side to GND, as shown in the following diagram:

Setting up the hardware

A Piezo wiring diagram

Writing the script

The script is a little more complicated than our last few scripts; we need to create a Piezo element, which just requires a pin. However, a piece of music is more complicated than turning an LED on and off. Luckily, the Johnny-Five Piezo API has the play() method, which takes an object. This object has attributes such as beats, tempo, and song—we'll use these to play our tune.

There are many ways to describe a song for the play() method. One way—the way that we'll use here—is as a string of notes, as follows:

C D F D A - A A A A G G G G - - C D F D G - G G G G F F F F - -

When you use this method, it will assume the middle octave, and the - symbol indicates null or off notes—nothing will play here.

For beats, we will use one-fourth time, and for tempo, we'll start with 100 bpm (beats per minute). Your code will look like this:

var five = require("johnny-five"),
  board = new five.Board();

board.on("ready", function() {
  var piezo = new five.Piezo(3);

  board.repl.inject({
    piezo: piezo
  });

  piezo.play({
    song: "C D F D A - A A A A G G G G - - C D F D G - G G G G F F F F - -",
    beats: 1 / 4,
    tempo: 20
  });

});

Save it to a file called piezo.js and run it in your terminal:

node piezo.js

You should hear a jaunty tune come from your Arduino board!

What's going on with the pin?

The reason a Piezo requires a PWM pin is that the Piezo object is sending different amounts of power through pin 3 to the Piezo, which causes it to emit different notes. The Johnny-Five library allows us to show these notes in a way that we can understand, instead of having to calculate how much power to send for each note.

Exploring the Piezo API

You can now explore the Piezo API further, including looking at the other ways of writing tunes that give you more control of the octave. Check the Johnny-Five website for more details and examples.

A challenge: using the REPL, find a way to make the Piezo stop playing mid song. A hint: there is a piezo.off() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset