Arduino: Playing notes with simple components

Using an inexpensive component to play notes using your Arduino.

In this tutorial we’ll be using a passive buzzer and an Arduino to play a series of notes. You will see that the sketch loops the main sketch so that the notes continue to run over and over (void loop). At the start of the sketch, we give each note a name. This is simply to make the rest of the sketch more understandable, and it’s something that you should always keep in mind, as it can often make sketches easier to create.

You will need:

Making the Connections

Blog_6_fritzing

The Sketch

/* FILE:    HC_Exp_Kit_Peizo_Speaker_Example
   DATE:    19/06/13
   VERSION: 0.1
   
REVISIONS:

19/09/13 Created version 0.1

This sketch uses a peizo speaker connected to digital Pin D2 to play a series of notes.

You may copy, alter and reuse this code in any way you like, but please leave 
reference to HobbyComponents.com in your comments if you redistribute this code. 
This software may not be used directly for the purpose of selling products that 
directly compete with Hobby Components Ltd's own range of products. 

THIS SOFTWARE IS PROVIDED "AS IS". HOBBY COMPONENTS MAKES NO WARRANTIES, WHETHER 
EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ACCURACY OR LACK OF NEGLIGENCE.
HOBBY COMPONENTS SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR ANY DAMAGES, 
INCLUDING, BUT NOT LIMITED TO, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY 
REASON WHATSOEVER. */


/* The digital pin connected to speaker's '+' input */
#define SPEAKERPIN 2

/* Frequencies for musical scale notes */
#define NoteC1 262
#define NoteD1 294
#define NoteE1 330
#define NoteF1 349
#define NoteG1 392
#define NoteA1 440
#define NoteB1 494
#define NoteC2 523

/* Store a set of notes to play */
static int Song[] = {NoteC1,NoteD1,NoteE1,NoteF1,NoteG1,NoteA1,NoteB1,NoteC2,NoteC2};

/* Indexes the next note to play */
byte Index;


void setup()
{
  /* Set the DIO pin that the speaker is connected to as an output and then set it 
    low so that it isn't driving the speaker */
  pinMode(SPEAKERPIN, OUTPUT); 
  digitalWrite(SPEAKERPIN, LOW);
}

/* Main program */
void loop()
{
  /* Play each note in sequence */
  for(Index = 0; Index < 9; Index++)
  {
    /* Output the current note to the speaker for 500ms*/
    tone(SPEAKERPIN, Song[Index]) ;
    delay(500);
  }
  /* Stop playing the last note */
  noTone(SPEAKERPIN);
  /* Wait a second before starting again */
  delay(1000);
}

Add a Comment

Your email address will not be published.