Chapter 5

Adding Sound and Motion to Your Arduino Projects

IN THIS CHAPTER

Bullet Making sound with a speaker

Bullet Using the TONE command to create frequencies

Bullet Using an MP3 shield to play sound effects and music

Bullet Creating motion with a servo

In this chapter, you learn how to work with devices that add sound and motion to your Arduino projects. To create sound, you can add a speaker to create audible output tones. This is useful in situations where your Arduino program might need to get someone’s attention or when you want to create a sound effect. For more realistic sound effects and music, you can add a shield to your Arduino to play MP3 files that are stored on a micro-SD card. To create motion, you can add a very useful device called a servo, which lets you control mechanical motion with an Arduino program.

Using a Speaker with an Arduino

An inexpensive way to add sound to an Arduino project is to simply add a small 8 Ω speaker to a digital output pin. You can then rapidly alternate the pin between HIGH and LOW to create a square-wave signal on the pin, which the speaker will render as sound. The frequency of this square wave will determine the pitch of the sound.

As an alternative to a speaker, you can use a piezoelectric buzzer, sometimes referred to as a piezo buzzer. A piezo buzzer is similar to a speaker but isn’t capable of playing complex waveforms such as voice or music. Piezo buzzers and small speakers are essentially interchangeable when connected directly to a digital output pin. Figure 5-1 shows a small speaker (on the right) and a piezo buzzer (on the left). Either one of these devices will work for the project that’s coming up (Project 48).

image

FIGURE 5-1: The piezoelectric speaker that comes with the Arduino Activity Kit.

Note that the speaker is polarized, so when you connect it to an I/O pin, be sure to connect the + terminal to the I/O pin and the other terminal to Vss (ground), as shown in the schematic in Figure 5-2.

image

FIGURE 5-2: Connecting a speaker or buzzer to an Arduino digital output pin.

Using the tone function

Programming a speaker is remarkably simple. Arduino C includes a command called tone that sends a frequency of your choice to an output pin. Thus, you can create an audible tone on a speaker by using the tone command, using the following syntax:

tone(pin, frequency, duration)

Here's how that syntax works:

  • pin is simply the pin number that you want to send the frequency to.
  • frequency is the frequency in hertz (Hz) that you want to generate.
  • duration is simply the length of time in milliseconds you want the frequency to play. Note that if you omit duration, the tone plays indefinitely until you tell it to stop by calling the noTone function (more on that later).

For example, the following command generates a 2,000 Hz frequency for five seconds on pin 8:

tone(8, 2000, 5000);

Note that the tone function returns immediately; it does not wait for the tone to be completed. Thus, your program can do other work while the tone is playing.

You can easily create a beeping sound by alternately sending short bursts of a frequency to the speaker followed by a brief pause. For example, here's a function you can call to beep a speaker on a specified digital output pin a certain number of times:

void beep(int pin, int count)
{
for(int i=0; i < count; i++)
{
tone(8, 1000, 250);
delay(500);
}
}

To send three beeps to digital pin 8, call the function like this:

beep(8, 3);

In the beep function, a for loop handles the counting of the beeps. For each pass through the for loop, the tone sounds for 250 milliseconds. The delay of 500 milliseconds accounts for the 250 milliseconds during which the tone plays plus another 250 milliseconds of silence. The result is a nice beep beep beep sound.

Earlier, I mention that you can omit the duration argument when you call the tone function. If you do, the tone continues indefinitely until you call the noTone function, which silences the tone. Here's a version of the beep function that omits the duration argument:

void beep(int pin, int count)
{
for(int i=0; i < count; i++)
{
tone(8, 1000);
delay(250);
noTone(8);
delay(250);
}
}

In the for loop, a 1,000 Hz tone is started on pin 8. Then, the program is delayed for 250 milliseconds and the tone is stopped. Then the program is delayed again for 250 milliseconds. The result is a beep tone that’s on for a quarter of a second and then off for a quarter of a second.

Connecting a speaker to an Arduino

As I’ve already mentioned and as the schematic diagram that was presented in Figure 5-2 shows, a speaker or piezo buzzer connects to an Arduino via a GND pin and a digital output pin. Conceptually, this is easy. But in practice, it’s a little more complicated because speakers and piezo buzzers usually have leads constructed of stranded wire rather than solid wire. That makes the leads more difficult to insert into header pins on an Arduino or into the holes in a solderless breadboard.

Here are a few ways you can work around this challenge:

  • Strip off ⅜ inch or so of insulation and cleanly twist the individual wires. Then carefully insert the twisted ends into the appropriate Arduino header or a breadboard hole. This method will work only if the strands are twisted cleanly and tightly together.
  • Before twisting the wires, separate out about one-third of the strands and cut them off. Then carefully and cleanly twist the remaining wires. When you have a clean twist, apply a small amount of solder to hold the wires together. This takes a bit of soldering skill, as the resulting soldered end of the wire must be smooth to fit nicely into a header or breadboard hole. (This is the method I use for the projects in this chapter.)
  • Attach a header pin to the ends of the speaker or buzzer leads. You can purchase kits with header pin parts and a crimping tool to create header pins.
  • Use a two-terminal screw connector block. You can snap the connector block into a breadboard and then use the screw connector to attach the stranded speaker wires.
  • Use an Arduino screw-terminal breakout block such as the ones pictured in Figure 5-3. These shields provide a screw terminal for each of the header pins on the UNO. Just attach the shield to your Arduino UNO, and then connect your stranded speaker leads to the appropriate screw terminal.
image

FIGURE 5-3: Screw-terminal breakout shields that make it easy to connect stranded wires to Arduino headers.

In the next section, you connect a speaker directly to an Arduino UNO so that you can test various ways to generate tones. Figure 5-4 shows the assembled project.

image

FIGURE 5-4: A speaker connected to an Arduino (Project 48).

Project 48: Creating Sound with a Speaker

In this project, you connect a speaker to an Arduino UNO to run programs that generate sound. The project is very simple, because the only component other than the UNO is a speaker.

image
image

Parts

  • One computer with Arduino IDE software installed
  • One Arduino UNO
  • One USB type-B cable to connect the UNO to your computer.
  • One 8 Ω speaker (alternatively, you can use a piezo buzzer)

Steps

  1. Prepare the speaker leads.

    Strip off about ⅜ inch of insulation. Separate out about one-third of the individual wires in each lead and snip them off. Then carefully twist the remaining wire strands together. Apply a very small amount of solder to hold the individual strands together.

  2. Insert the speaker.

    The speaker is not polarized, so connect one of the leads to pin 8 and the other lead to any of the three GND pins on the UNO.

  3. Open the Arduino editor.
  4. Connect the Arduino UNO to your computer.
  5. Type the following sketch into the Arduino editor:

    void setup() {
    // put your setup code here, to run once:
    pinMode(8, OUTPUT);
    }

    void loop() {
    // put your main code here, to run repeatedly:
    tone(8, 1000);
    delay(250);
    noTone(8);
    delay(250);
    }

  6. Click the Upload button.

    The program compiles and is uploaded to the UNO. If everything works, you’ll hear a steady beep-beep-beep from the speaker.

  7. Now try the programs in Listings 5-1, 5-2, and 5-3.

    These programs vary the tone in different ways to demonstrate the versatility of the tone function.

Sounding the alarm with Morse code

Listing 5-1 is an Arduino program that sounds the familiar SOS emergency call in Morse code. The Morse code for SOS is three dots, three dashes, and three dots. This program simply sounds a 1,000 Hz tone in the familiar pattern: dot-dot-dot-dash-dash-dash-dot-dot-dot.

Technical stuff The proper way to pronounce Morse code is dit for dots and dah for dashes, so the correct way to say “SOS” in Morse code dit dit dit dah dah dah dit dit dit.

According to the rules of Morse code, a dash is three times longer than a dot, the gap between letters is three times the length of a dot, and the gap between words is seven times as long as a dot. However, for the special case of the code SOS, the gaps between letters are skipped.

The program uses a variable named pace to establish the pace of the Morse code sounded. This variable is set to 60, which is a pretty good pace for reading Morse code. (A pace of 60 milliseconds per dot translates to 20 words per minute. The world record is 75.2 words per minute, which is a pace of 16 milliseconds per dot. Just for fun, try the program with the pace variable set to 16. The result is gibberish to me. If you can make out individual dots and dashes, your hearing is much better than mine!)

The program uses four functions to sound each of the four elements of Morse code:

  • soundDot: Sounds a dot using a single pace unit and then pauses for a single pace unit.
  • soundDash: Sounds a dot by using three pace units and then pauses for a single pace unit.
  • soundLetterGap: Delays for three pace units. (Note that this function isn't called in the program, because SOS doesn’t require inter-letter gaps.)
  • soundWordGap: Delays for seven pace units.

LISTING 5-1: SOS!

// SOS Program
// Doug Lowe
// December 3, 2021

// This program sounds the alert by playing SOS in Morse Code
// on a speaker or piezo buzzer connected to pin 8.

int pin = 8; // The speaker pin.

int pace = 60; // Sets the speed at which SOS is sounded.
// Morse code standards spell out the duration
// of each element of the coded signal:
// A dot is one unit.
// A dash is three units.
// The gap between dots and dashes is one unit.
// The gap between letters is three units.
// However the gap is skipped for the
// specific sequence "SOS."
// The gap between words is seven units.
void setup() {
pinMode(8, OUTPUT);
}

void loop() {

// Sound SOS
soundDots(3);
soundDashes(3);
soundDots(3);
soundWordGap();
}

void soundDots(int count) {
for(int i=0; i < count; i++)
{
tone(pin, 1000);
delay(pace);
noTone(pin);
delay(pace);
}
}

void soundDashes(int count) {
for(int i=0; i < count; i++)
{
tone(pin, 1000);
delay(pace * 3);
noTone(pin);
delay(pace);
}
}

void soundLetterGap() {
delay(pace * 3);
}

void soundWordGap() {
delay(pace * 7);
}

Playing a siren

Listing 5-2 shows how you can use tone within a pair of for loops to create a continuously rising and falling tone, much like a police siren. The first for loop varies the pitch from a low value to a high value, and the second for loop varies the pitch from the high value back down to the low value.

The sound characteristics of the siren are set by four variables:

  • low: Sets the low end of the frequency range. This variable is set to 300, but you can change it to start from a lower or higher frequency.
  • high: Sets the high end of the frequency range. This variable is set to 1,000, but you can change it if you want.
  • increment: Sets the amount that is added or subtracted to or from the frequency at each pass through the for loops. Increasing this value speeds up the siren.
  • pace: Sets the length at which each pitch is played. Increase this value to make the siren slower. If you increase the value enough (say, to 100 or 150), you'll hear the individual pitches separately.

LISTING 5-2: Generating a Siren Effect

// Siren Program
// Doug Lowe
// December 3, 2021

// This program generates a siren sound on a speaker or piezo buzzer
// connected to Pin 8.

int pin = 8; // The speaker pin.
int low = 300; // Frequency of the lowest pitch of the siren.
int high = 1000; // Frequency of the highest pitch of the siren.
int increment = 5; // The amount added or subtracted from the pitch
// each time through the for loop.
int pace = 10; // The speed at which the pitch changes.
void setup() {
pinMode(8, OUTPUT);
}

void loop() {
for (int f = low; f < high; f = f+increment)
{
tone(pin, f);
delay(pace);
}
for (int f = high; f > low; f = f-increment)
{
tone(pin, f);
delay(pace);
}
}

Playing a song

Listing 5-3 shows a program that plays “Mary Had a Little Lamb.”

To simplify the code that generates the musical notes, the program defines several constants that represent the frequency for each of the notes required by the songs. For example, the constant NoteC4 is 262, the frequency in hertz of middle C on a piano keyboard. The constants span one full octave, which is plenty of range for “Mary Had a Little Lamb.”

The program also sets up constants for the duration of a quarter note, half note, and whole note. The constants make it easy to specify a particular pitch for a particular duration in a tone command.

Two functions are used to actually play the music:

  • playNote: Accepts the note's pitch and a duration as arguments. A little trick is used to ensure that the notes are distinguishable from one another to ensure that 10 percent of each note’s duration is used as a gap between notes.
  • playRest: Accepts a duration value and simply delays for the indicated duration.

Thus, playing a melody is simply a matter of writing a sequence of calls to these two functions to play the correct notes for the correct durations in the correct order. As you can see, I’ve added a comment to each of the calls to playNote so you can see what part of the song is being played.

LISTING 5-3: Making Music with an Arduino

// Mary Had a Little Lamb
// Doug Lowe
// December 3, 2021

// This program plays Mary Had a Little Lamb on a speaker or piezo buzzer
// connected to Pin 8.

int pin = 8; // The speaker pin.
int tempo = 100; // The speed at which the pitch changes.
// Note pitch constants for the Key of C (Starting at Middle C)
const int Note_C4 = 262;
const int Note_D4 = 294;
const int Note_E4 = 330;
const int Note_F4 = 349;
const int Note_G4 = 392;
const int Note_A4 = 440;
const int Note_B4 = 494;
const int Note_C5 = 523;

// Note duration constants
const int quarter = 300;
const int half = quarter * 2;
const int whole = quarter * 4;

void setup() {
pinMode(8, OUTPUT);
}

void loop() {
playNote(Note_E4, quarter); // Mar-
playNote(Note_D4, quarter); // y-
playNote(Note_C4, quarter); // Had
playNote(Note_D4, quarter); // a
playNote(Note_E4, quarter); // Lit-
playNote(Note_E4, quarter); // le
playNote(Note_E4, quarter); // Lamb
playRest(quarter);
playNote(Note_D4, quarter); // Lit-
playNote(Note_D4, quarter); // le
playNote(Note_D4, quarter); // Lamb
playRest(quarter);
playNote(Note_E4, quarter); // Lit-
playNote(Note_G4, quarter); // le
playNote(Note_G4, quarter); // Lamb
playRest(quarter);
playNote(Note_E4, quarter); // Mar-
playNote(Note_D4, quarter); // y-
playNote(Note_C4, quarter); // Had
playNote(Note_D4, quarter); // a
playNote(Note_E4, quarter); // Lit-
playNote(Note_E4, quarter); // le
playNote(Note_E4, quarter); // Lamb
playNote(Note_E4, quarter); // Its-
playNote(Note_D4, quarter); // Fleece
playNote(Note_D4, quarter); // Was
playNote(Note_E4, quarter); // White
playNote(Note_D4, quarter); // As
playNote(Note_C4, half); // Snot
playRest(half);
playRest(whole);
}

void playNote(int pitch, int duration){
int phrasing = quarter * 0.1;
tone(pin, pitch);
delay(duration - phrasing);
noTone(pin);
delay(phrasing);
}

void playRest(int duration) {
delay(duration);
}

Using an MP3 Shield

The tone function used in combination with a speaker or piezo buzzer is adequate for simple sounds, but what if your project needs more sophisticated sound effects? The Arduino doesn't have the ability to play audio files in the common MP3 audio format, but you can easily add that capability to an Arduino by adding an MP3 shield to your project.

There are many MP3 shields available — just search the web for “Arduino MP3 shield,” and you’ll find plenty of options. The one I use in this chapter is a popular MP3 shield from Adafruit (www.adafruit.com) called the Music Maker shield (see Figure 5-5).

The Music Maker shield comes in two versions — one that has just a line-out signal level, which you can use with headphones or as input to an external amplifier, and another that has a built-in 3-watt stereo amplifier that lets you connect small speakers. I’m using the one that has the built-in amplifier. You can purchase it directly from Adafruit or from other sources for about $35.

The Music Maker shield includes the following features:

  • A micro-SD card reader into which you can insert a card loaded with audio files.
  • An on-board audio decoder chip that can play MP3 files as well as several other file formats, including WAV and MIDI.
  • A standard ⅛-inch stereo audio jack to connect headphones or an external amplifier.
    image

    FIGURE 5-5: The Adafruit Music Maker shield.

  • Screw terminals to connect external speakers. The shield will work with either 4 Ω or 8 Ω speakers. Don’t expect the output to be very loud — 3 W is not a powerful amplifier, but it is suitable when a lot of volume isn’t required.
  • A programming library that makes it easy to play audio files stored on the micro-SD card.
  • Seven additional digital I/O pins that you can access via the Music Maker library. (To access these pins, you’ll need to solder additional header pins to the Music Maker shield.)

Assembling the Music Maker shield

When you purchase the Music Maker shield, you’ll find that a bit of assembly is required: The shield’s main board is fully assembled, but you’ll have to solder the header pins (included) onto the board. The soldering is pretty simple and should only take about 15 minutes.

Preparing the micro-SD card

The Music Maker shield reads audio files from its on-board micro-SD card reader. Before you can use the Music Make shield, you’ll need to copy at least one audio file to a micro-SD card.

If you’ve never worked with micro-SD cards, you’ll be surprised at how small they are. Most computers that have multi-format card readers don’t have a slot that’s small enough for micro-SD cards. However, micro-SD cards usually come with an adapter that lets you use a micro-SD card in a standard SD card reader. Simply insert the micro-SD card into the adapter, and then slide the adapter into your computer’s SD card reader. In a few moments, Windows will recognize the micro SD card so that you can copy files to it.

There’s one important caveat to know about saving your audio files to the micro-SD card: The Music Maker shield does not recognize file names longer than eight characters, and file extensions can be only three characters long. So, a filename like Puff the Magic Dragon.mp3 won't work. You’ll need to shorten the name to something like Puff.mp3.

You can put as many audio files on the micro-SD card as will fit. And you can, if you want, create folders to organize them — provided that the folder names are no longer than eight characters in length.

For the purposes of this chapter, copy just one MP3 file to the card and name it TRACK01.mp3. This can be any audio file you want — your favorite song, or perhaps a sound effect file with an owl screeching or a werewolf howling. As long as the file is named TRACK01.mp3, the program in the project that's coming up will be able to play the file.

Programming the Music Maker shield

Adafruit supplies a programming library with the Music Maker shield, making it simple to play individual audio files from your Arduino sketches. Before you can use this library, you have to download and install it into the Arduino IDE. Here are the steps:

  1. Open the Arduino IDE.
  2. Choose Tools⇒  Manage Libraries.

    The dialog box, shown in Figure 5-6, appears.

  3. Enter Adafruit_VS1053 in the search box at the top of the Library Manager.

    The Library Manager locates this library in the cloud.

  4. Select the most recent version in the Select Version drop-down list.
  5. Click Install.

    The library is installed.

    You’re done!

image

FIGURE 5-6: The Library Manager dialog box.

After you’ve installed the library, you can use it to play sound files on the micro-SD card that’s loaded into the shield.

The Music Maker shield uses four pins to play audio files:

Name

What it Does

Default Digital Pin

MCS

Chip select pin

D7

DCS

Data select pin

D6

CCS

Card select pin

D4

DREQ

Request interrupt pin

D3

There’s usually no reason to change these pins from their defaults, and you don’t need to worry about the details of what the pins actually do. But you do need to remember that these pins are used by the Music Maker shield, so you can’t use them for other purposes in your program.

It’s common to define these pin settings as constants at the beginning of an Arduino sketch that uses the Music Maker shield. For example:

#define CS 7 // Select pin (output)
#define DCS 6 // Data/command select pin (output)
#define CARDCS 4 // Card chip select pin
#define DREQ 3 // Data request

To play a file stored on the micro-SD card, first you have to create a media player object within your sketch. This is usually done prior to the setup function, so it’s available to all functions within the program. Here’s an example:

Adafruit_VS1053_FilePlayer mediaPlayer = Adafruit_VS1053_FilePlayer(
RESET, CS, DCS, DREQ, CARDCS);

Don’t worry too much about the details of this statement. Instead, just remember that it’s needed to create a variable named mediaPlayer, which you can then use to play audio tracks in your program.

In the setup function, you must call the begin function for the media player and for the SD card. Both of these functions return false if an error has occurred, so you can also use these statements to confirm that a Music Maker shield is installed onto the UNO and that a card is inserted into the micro-SD card reader:

if (mediaPlayer.begin() == false)
{
while (true); // Don't do anything -- Shield is missing
}
if (SD.begin(CARDCS) == false)
{
while (true); // Don't do anything -- SD card is missing
}

Notice that both if statements execute the command while (true) if an error is detected. The while (true) statement simply loops forever, preventing the program from actually doing anything if the shield or the card is missing.

After you've established that the shield and micro-SD card are present, you can play an audio file on the card like this:

mediaPlayer.playFullFile("TRACK01.mp3");

This statement supplies the name of the audio file. As long as there’s a file on the card named TRACK01.mp3, the Music Player shield will play the file.

One other statement you may want to use is setVolume, which adjusts the left and right channel volume of the playback. Use zeros to set the maximum volume:

mediaPlayer.setVolume(0, 0);

Building an Arduino Music Player

In this section, you build a simple Arduino project that uses a Music Maker shield to play MP3 files. Figure 5-7 shows the completed project.

image

FIGURE 5-7: An Arduino Music Player (Project 49).

Project 49: Using a Music Maker Shield to Play Sounds

This project uses an Adafruit Music Maker shield so you can add sound effects or music to your Arduino projects.

image

Parts

  • One computer with Arduino IDE software installed
  • One Arduino UNO
  • One USB type-B cable to connect the UNO to your computer
  • One Adafruit Music Maker shield
  • One micro-SD card
  • Two 8 Ω speakers (alternatively, you can use a headset with a ⅛-inch audio connector)

Steps

  1. Assemble the Adafruit Music Maker shield.

    Carefully follow the instructions that come with the shield. (You'll need a soldering iron and some solder to perform this step. A lighted magnifying viewer or goggles will help as well.)

  2. Prepare the micro-SD card.

    Copy any MP3 file to the root folder of the SD card. Change the name of the MP3 file to TRACK01.mp3.

  3. Open the Arduino editor.
  4. Attach the Music Maker shield to the Arduino UNO.
  5. Connect the leads from the two speakers to the speaker terminal blocks on the Music Maker shield.
  6. Connect the Arduino UNO to your computer.
  7. Enter the sketch shown in Listing 5-4 into the Arduino editor.
  8. Click the Upload button.

    The program compiles and is uploaded to the UNO. You’ll soon hear your MP3 file play on the speakers. When the MP3 file finishes, it will play again after a pause of 5 seconds.

LISTING 5-4: Playing an MP3 Track

// MP3 Program
// Doug Lowe
// December 3, 2021

// This program uses an Adafruit Music Player shield
// to play an MP3 file named TRACK01.mp3.

#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

#define CS 7 // Select pin (output)
#define DCS 6 // Data/command select pin (output)
#define CARDCS 4 // Card chip select pin
#define DREQ 3 // Data request

Adafruit_VS1053_FilePlayer mediaPlayer =
Adafruit_VS1053_FilePlayer(RESET, CS, DCS, DREQ, CARDCS);

void setup() {
if (mediaPlayer.begin() == false)
{
while (true); // Don't do anything -- Music Maker shield is missing
}

if (SD.begin(CARDCS) == false)
{
while (true); // Don't do anything -- SD card is missing
}

mediaPlayer.setVolume(0,0);
}

void loop() {
mediaPlayer.playFullFile("TRACK01.mp3");
delay(5000);
}

Using a Servo with an Arduino

The previous sections in this chapter look at two ways to create Arduino projects that make noise. In this section, you add an element of movement by utilizing a device called a servo.

A servo is a special type of motor that is designed to rotate to a particular position and hold that position until it’s told to rotate to a different position. Hobby servos are frequently used in radio-controlled vehicles such as airplanes, boats, and cars, but there are many other uses for servos. For example, I often use them in Halloween props to add movement such as eyes or a mouth.

Servos are readily available from many sources. Electronics suppliers, such as Adafruit (www.adafruit.com) and Jameco (www.jameco.com), sell these, as does the giant retailer Amazon. You may also be able to purchase servos from a local hobby store. Figure 5-8 shows a typical hobby servo.

image

FIGURE 5-8: A typical hobby servo.

Connecting a servo to an Arduino

Servos use a special three-conductor cable to provide power and a control signal that tells the servo what position it should move to and hold. The cable’s three wires are colored red, black, and white and have the following functions:

  • Red: Supplies the voltage required to operate the servo. For most servos, this voltage can be anywhere between +4 V and +9 V. On an Arduino, you should connect this to one of the +5 V pins.
  • Black: The ground connection. On the Arduino, you should connect it to one of the GND pins.
  • White: The control wire; it connects to one of the Arduino’s digital I/O pins.

Figure 5-9 shows how these wires should be connected in an Arduino circuit.

image

FIGURE 5-9: Connecting a servo to an Arduino.

The control wire controls the position of the servo by sending the servo a series of pulses approximately 20 ms apart. The length of each one of these pulses determines the position that the servo rotates to and holds.

Most hobby servos have a range of motion of 180 degrees — that is, one-half of a complete revolution. The complete range of pulse durations is 0.5 ms to 2.5 ms, where 0.5 ms pulses move the servo to its minimum position (0 degrees), and 2.5 ms pulses move the servo to its maximum position (180 degrees). To hold the servo at the center point of this range (90 degrees), the pulses should be 1.5 ms in duration.

Fortunately, Arduino provides a library of functions for programming servos that removes all the details of pulse duration. With the servo library, you just tell the servo what position you want to move it to, and the library moves the servo to that position and holds it there until you tell it otherwise. Because of this library, programming an Arduino to control a servo is easy.

To connect a servo to an Arduino, you must use a three-pin header adapter such as the one shown in Figure 5-10. A header like this is required because the leads from the servo have female pin connections, just like the female connections in the Arduino headers or on a breadboard. The header simply adapts the female header on the servo leads so it can properly connect. You simply plug the three-pin adapter into the breadboard and then plug the servo leads into the adapter.

image

FIGURE 5-10: A three-pin header adapter for connecting the servo to an Arduino.

Programming a servo

Arduino provides a servo library that makes it easy to work with servos. Because servos are so commonly used, the servo library is automatically installed in the Arduino integrated development environment (IDE), so you don’t have to do anything special to use the library.

For most programs, there are four steps you must take to program a servo:

  1. Include the servo library so your program can use its functions.

    To do this, add the following line near the top of your program:

    #include <Servo.h>

    Remember Case is important in Arduino C, so you must capitalize the word Servo here.

  2. Create a servo variable.

    Servo is a special variable type defined by the servo library. You’ll need a variable of this type to refer to your servo. The easiest way to do this is to create the variable outside of the setup() or loop() functions, like this:

    Servo Servo1;

    Here, I've created a servo variable named Servo1.

  3. Attach a pin to the servo variable.

    You’ll usually do that in the setup() function with a line like this:

    Servo1.attach(2);

    If you've create a constant for the servo pin number, you’ll use something like this instead:

    Servo1.attach(ServoPin);

    where ServoPin is the constant you’ve created.

  4. Move the servo.

    To move the servo to a specific position, use a line such as this:

    Servo1.write(90);

    This example moves the servo to the 90-degree position. After it’s there, the servo will remain there until you use the write function to move the servo to a new position.

Listing 5-5 shows a complete program that moves the servo based on the status of two push-button switches that are available to the program. The switches are identified as SW1, on pin 10, and SW2 on pin 11. The servo itself is on pin 2.

When you press SW1, the servo moves to 0 degrees. When you press SW2, the servo moves to 180 degrees. If you press both buttons simultaneously, the program moves the servo to the middle position (90 degrees).

LISTING 5-5: A Servo Control Program

// Servo Program
// Doug Lowe
// December 5, 2021

#include <Servo.h>

#define ServoPin 2
#define SW1 10
#define SW2 11
#define LowPos 0
#define MidPos 90
#define HighPos 180

Servo Servo1;

int ServoPos = MidPos;

void setup() {
pinMode(SW1, INPUT);
pinMode(SW2, INPUT);

Servo1.attach(ServoPin);
Servo1.write(ServoPos);

}

void loop() {

bool sw1HIGH = digitalRead(SW1);
bool sw2HIGH = digitalRead(SW2);

if (sw1HIGH & sw2HIGH)
ServoPos = MidPos;
else if (sw1HIGH)
ServoPos = LowPos;
else if (sw2HIGH)
ServoPos = HighPos;

Servo1.write(ServoPos);
delay(100);
}

Building a servo project

Project 50 shows you how to build a complete circuit that uses a servo as well as two push buttons. This circuit is capable of running the program that was shown in Listing 5-4. Figure 5-11 shows the assembled project.

image

FIGURE 5-11: An Arduino project that controls a servo (Project 50).

Project 50: Using a Servo with an Arduino

In this project, you connect a servo to an Arduino. The circuit also includes two push buttons (on pins 10 and 11) that you can use to control the action of the servo.

image
image

Parts

  • One computer with Arduino Editor software installed
  • One Arduino UNO
  • One prototyping shield
  • One USB cable
  • One hobby servo
  • One three-pin male-to-male header
  • Two normally open push buttons
  • Two 1 k4 Ω resistors
  • Ten jumper wires

Steps

  1. Insert the jumper wires.

    From

    To

    B11

    B7

    C7

    C1

    GND on bottom left header

    D1

    E1

    F1

    H12

    H8

    I8

    I2

    Digital pin 11 on right header

    J14

    Digital pin 10 on right header

    J10

    Digital pin 2 on right header

    J3

    +5 V on bottom right header

    J2

  2. Insert the resistors.

    Resistor

    From

    To

    R1 (470 Ω)

    A14

    A11

    R2 (470 Ω)

    A10

    A7

  3. Insert the switches

    Resistor

    From

    To

    SW1

    E8 and F8

    E10 and F10

    SW2

    E12 and F12

    E14 and F14

    Be sure to orient the switches correctly, as shown in the breadboard diagram.

  4. Insert the three-pin male-to-male header.

    The three pins should go in H1, H2, and H3.

  5. Connect the servo.

    Plug the three-pin servo connector into the three-pin male-to-male header. Ensure that the control wire (usually white) connects to H3.

  6. Open the Arduino Editor.
  7. Connect your Arduino to the computer and identify it in Arduino Editor.

    For more information about how to do this, see Chapter 1 of this minibook.

  8. Enter and run the following program to test that the servo is working:

    #include <Servo.h>

    Servo Servo1;

    void setup() {
    Servo1.attach(2);
    }

    void loop() {
    Servo1.write(45);
    delay(500);
    Servo1.write(135);
    delay(500);
    }

  9. Now try the program in Listing 5-4.

    This program uses the switches to control the servo’s action.

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

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