Melody

You can use the component of piezo to play some basic sound with Arduino. Here we use the Melody library to play a music sample, from a list of notes and durations.

Materials

  • 1 Arduino Uno board
  • 1 Basic Education shield
  • 2 jumper wires 1 piezo

Instructions

  1. Connect the piezos red jumper wire to digital pin 8 and the black cable to ground (GND).
  2. Open Example>BasicEducationShield>Help>Melody.
/*
Melody
*/
#include <BasicEducationShield.h>

#include "pitches.h"

//8 is the pin the piezo is connected to.
Melody me=Melody(8);

void setup(){
}

void loop(){
//Defining the notes used in the music. No more than 30.
int notes[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};

//Duration of each note. should be corresponding to the notes above.
int noteDurations[] = {
4, 8, 8, 4,4,4,4,4 };

//Play the notes defined above
me.play(8,notes,noteDurations,1.4);

delay(3000);

//Make a beep sound
me.beep();

delay(3000);
}

Upload the code. The piezo should now play a small melody, be quiet for 3 seconds, then play a short beep.

To change the melody you need to change the notes and the notes duration. The line defining the notes used in the Melody code is:int notes[] = {NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4}To change a note replace it with a note declared in the tab pitches.h. You can add up to 30 notes per melody. Don’t forget a comma between each note. If you want the piezo to be silent for a note just write a “0”.

Now each note needs a duration. These durations are defined in the line: int noteDurations[] = {4, 8, 8, 4,4,4,4,4 } 4 = a quarter note, 8 = eighth note etc. Each number belongs to a note. NOTE_C4 is played a quarter, NOTE_G3 an eighth,  next NOTE_G3 an eight etc. There has to be as many notes as noelody.

The melody is played with this line of code:me.play(8,notes,noteDurations,1.4) “8” is the number of notes. If you add notes to the melody this number must be changed to match the number of notes, notes are the notes in the melody, noteDuration are the note durations and 1.4 is the speed. Try changing the last number to see what happens to the melody.

If you want to write your own program and use the notes, make sure to put “pitches.h” in your sketch folder, and put #include pitches.h at the beginning of your program.

It’s not working?

  1. Make sure that the piezo is properly connected to a digital pin and to ground (GND).
  2. Make sure you’ve connected the piezo to the same pin as stated in your code.