Main article: Playing popular songs with Arduino and a buzzer
Buzzer is used to generate sound, beep or even melody of a song. It can be found in alarm devices, computers, timers and confirmation of user input such as a mouse click or keystroke.
A piezo buzzer is not like a regular speaker that you might think of. It uses a material that actually changes shape when you apply electricity to it which in turn creates noise. The faster you bend the material, the higher the pitch of the noise that is produced.
Wiring schemaThe connection is pretty easy, it only has control signal and GND. Pin D9 will be used to control the tone.
Built-in Arduino functions will be used to generate the melody. Tone() generates a square wave of the specified frequency (and 50% duty cycle) on a pin. A duration can be specified, otherwise the wave continues until a call to noTone(). If you are trying to make tones for the human ear, then values between 2000 and 5000 are where our ears are most tuned.
The main program will iterate over notes and and use assigned duration for the note. The code has self explanatory comments to better understand what is being done.
#include "pitches.h"
#define BUZZER_PIN 9
int melody[] = {
// Notes goes here
};
int durations[] = {
// Notes duration goes here
};
void setup()
{
pinMode(BUZZER_PIN, OUTPUT);
}
void loop()
{
int size = sizeof(durations) / sizeof(int);
for (int note = 0; note < size; note++) {
//to calculate the note duration, take one second divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int duration = 1000 / durations[note];
tone(BUZZER_PIN, melody[note], duration);
//to distinguish the notes, set a minimum time between them.
//the note's duration + 30% seems to work well:
int pauseBetweenNotes = duration * 1.30;
delay(pauseBetweenNotes);
//stop the tone playing:
noTone(BUZZER_PIN);
}
}
Only one tone can be generated at a time. If a tone is already playing on a different pin, the call to tone() will have no effect. If the tone is playing on the same pin, the call will set its frequency. Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega). Also, it is not possible to generate tones lower than 31Hz.
Pitches libraryThe code used to generate the melody uses an extra library available on our GitHub. This file contains all the pitch values for typical notes.
To import a library, open the Arduino IDE, go to Sketch > Include Library > Add.ZIP Library and select the library file downloaded from our GitHub repository.
Then you can simply use include statement:
#include "pitches.h"
It will include the library with predefined pitch constants so the melody generation becomes easier.
Popular songsAt the moment, the following melodies are available. The list can be updated with new ones based on user requests. So, feel free to leave a comment with melodies you would like to hear.
SongsMoviesGamesOther
Comments