How to use the Arduino tone function to play a melody on a piezo buzzer or speaker
Source: InternetPublisher:风向双子座 Keywords: Speaker Arduino Piezo Buzzer Updated: 2024/12/31
Arduino is a great way to simplify and speed up microcontroller projects, thanks to its community of developers who make almost everything look easy. There are a lot of Arduino projects out there for you to try and have fun with. Some of your projects may require some sound manipulation to announce something or just to impress your audience. What if I told you that almost any theme song that can be played on a piano can be imitated on your Arduino with the help of a simple program and a cheap piezo speaker?
In this tutorial, we'll learn how simple and easy it is to use the Arduino tone() function to play a melody on a piezo buzzer or speaker .
Required Hardware:
- Arduino (any version – UNO is used here)
- Piezo speaker/buzzer or any other 8 ohm speaker.
- Breadboard
- Connection line
- Button
- 1k resistor (optional)
Understanding Arduino's Tone() function:
Before we understand how tone() works , we should know how a piezo buzzer works. We might have learned about piezoelectric crystal in our school, it is nothing but a crystal that converts mechanical vibrations into electrical energy and vice versa. Here, we apply a variable current (frequency) and the crystal vibrates thereby producing sound. So, in order to make the piezo buzzer produce some noise, we have to make the piezoelectric crystal vibrate, the tone and pitch of the noise depends on the speed at which the crystal vibrates. So, the tone and pitch can be controlled by varying the frequency of the current.
Ok, so how do we get a variable frequency from Arduino ? This is where the tone() function comes in. tone() can generate a specific frequency on a specific pin. The duration can also be mentioned if required. The syntax of tone() is
tone(
The value of the pin can be any of your digital pins. I have used pin 8 here. The frequency that can be generated depends on the size of the timer in your Arduino board. For UNO and most other common boards, the minimum frequency that can be generated is 31Hz and the maximum frequency that can be generated is 65535Hz. However, we humans can only hear frequencies between 2000Hz and 5000Hz.
pitches.h header file:
Now, we know how to generate some noise using the Arduino tone() function . But how do we know what tone each frequency will produce?
Arduino gives us a note table that equates each frequency to a specific note type. This note table was originally written by Brett Hagman , and the tone() command is based on his work. We will use this note table to play our theme. If you are someone who is familiar with sheet music you should be able to understand this table, for everyone else like me these are just another block of code.
#define NOTE_B0 31#define NOTE_C1 33#define NOTE_CS1 35#define NOTE_D1 37#define NOTE_DS1 39#define NOTE_E1 41#define NOTE_F1 44#define NOTE_FS1 46#define NOTE_G1 49#define NOTE_GS1 52#define NOTE_A1 55#define NOTE_AS1 58#define NOTE_B1 62#define NOTE_C2 65#define NOTE_CS2 69#define NOTE_D2 73#define NOTE_DS2 78#define NOTE_E2 82#define NOTE_F2 87#define NOTE_FS2 93#define NOTE_G2 98#define NOTE_GS2 104#define NOTE_A2 110#define NOTE_AS2 117#define NOTE_B2 123#define NOTE_C3 131#define NOTE_CS3 139#define NOTE_D3 147#define NOTE_DS3 156#define NOTE_E3 165#define NOTE_F3 175#define NOTE_FS3 185#define NOTE_G3 196#define NOTE_GS3 208#define NOTE_A3 220#define NOTE_AS3 233#define NOTE_B3 247#define NOTE_C4 262#define NOTE_CS4 277#define NOTE_D4 294#define NOTE_DS4 311#define NOTE_E4 330#define NOTE_F4 349#define NOTE_FS4 370#define NOTE_G4 392#define NOTE_GS4 415#define NOTE_A4 440#define NOTE_AS4 466#define NOTE_B4 494#define NOTE_C5 523#define NOTE_CS5 554#define NOTE_D5 587#define NOTE_DS5 622#define NOTE_E5 659#define NOTE_F5 698#define NOTE_FS5 740#define NOTE_G5 784#define NOTE_GS5 831#define NOTE_A5 880#define NOTE_AS5 932#define NOTE_B5 988#define NOTE_C6 1047#define NOTE_CS6 1109#define NOTE_D6 1175#define NOTE_DS6 1245#define NOTE_E6 1319#define NOTE_F6 1397#define NOTE_FS6 1480#define NOTE_G6 1568#define NOTE_GS6 1661#define NOTE_A6 1760#define NOTE_AS6 1865#define NOTE_B6 1976#define NOTE_C7 2093#define NOTE_CS7 2217#define NOTE_D7 2349#define NOTE_DS7 2489#define NOTE_E7 2637#define NOTE_F7 2794#define NOTE_FS7 2960#define NOTE_G7 3136#define NOTE_GS7 3322#define NOTE_A7 3520#define NOTE_AS7 3729#define NOTE_B7 3951#define NOTE_C8 4186#define NOTE_CS8 4435#define NOTE_D8 4699#define NOTE_DS8 4978
Playing musical notes on the Arduino:
To play decent melodies using Arduino, we should know what these melodies consist of. The three main factors required to play a theme are
- Annotation Value
- Annotation Duration
- speed
We have the pitches.h header file to play any note value, now we should find out its specific note duration to play it. Tempo is nothing but how fast the melody should be played. Once you know the note value and note duration, you can use them with tone() like
tone (pinName, Note Value, Note Duration);
For the tones played in this tutorial, I have provided you the note values and note durations in the "themes.h" header file, which you can use to play them in your project. However, if you have any particular tone in your mine, and want to play it in your project, then continue reading...otherwise skip this topic and drop to the next one.
To play any particular tune , you have to get the sheet music of that particular music and convert the score into Arduino sketch by reading the note values and note duration from it . If you are a music student, this will be a piece of cake for you, otherwise spend some time to break your head like me. But at the end of the day, when your tune plays on the piezo buzzer, you will find your efforts worth it.
After getting the note value and note duration, load them into the program in the "themes.h" header file as shown below
//##############**"HE IS A PIRATE" Theme song of Pirates of caribbean**##############//int Pirates_note[] = {
NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4,
NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4,
NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4,
NOTE_A3, NOTE_C4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_F4,
NOTE_F4, NOTE_G4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_C4, NOTE_D4,0, NOTE_A3, NOTE_C4, NOTE_B3, NOTE_D4, NOTE_B3, NOTE_E4, NOTE_F4,
NOTE_F4, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4,
NOTE_D4, 0, 0, NOTE_A3, NOTE_C4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_F4,
NOTE_G4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_G4,
NOTE_A4, NOTE_D4, 0, NOTE_D4, NOTE_E3, NOTE_F4, NOTE_F4, NOTE_G4, NOTE_A4,
NOTE_D4, 0, NOTE_D4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_F4, NOTE_D4
};
int Pirates_duration[] = {4,8,4,8,4,8,8,8,8,4,8,4,8,4,8,8,8,8,4,8,4,8,4,8,8,8,8,4,4,8,8,4,4,8,8,4,4,8,8,8,4,8,8,8,4,4,8,8,4,4,8,8,4,4,8,4,4,8,8,8,8,4,4,8,8,4,4,8,8,4,4,8,8,8,4,8,8,8,4,4,4,8,4,8,8,8,4,4,8,8};//###########End of He is a Pirate song#############//
The above code block displays the note values and note durations of the "He's a Pirate" theme from the movie "Pirates of the Caribbean". You can add themes like this.
Schematics and Hardware:
The schematic diagram for this Arduino Tone Generator project is shown in the image below:
The connections are pretty simple, we have a piezo speaker connected to pin 1 and the ground of the Arduino via an 8K resistor. The 1k resistor is a current limiting resistor and is used to keep the current within safe limits. We also have four switches to select the desired melody. One end of the switch is connected to ground and the other end is connected to pins 2, 3, 4, and 5 respectively. The switches will enable pull-up resistors internally using the software. Since the circuit is pretty simple, it can be connected using a breadboard as shown below:
Arduino Program Description:
Arduino programming is very simple once you understand the concept. The complete code is given at the end of this tutorial. If you are not familiar with adding header files, you can download the code as a ZIP file from here and upload it directly to the Arduino.
The above two are the header files that must be added. "Pitches.h " is used to equate each note to a specific frequency, and "themes.h" contains the note values and note durations for all four pitches.
#include "pitches.h"#include "themes.h"
Create a function to play each tone when needed. Here, when the function Play_Pirates() is called the "He's a Pirate" tone will be played. This function consists of the tone function that generates a frequency at pin number 8. noTone(8) is called to stop the music after it has played. If you want to play your own tone, change the Pirates_note and Pirates_duration to the new note and duration values saved in the "themes.h" values.
void Play_Pirates(){ for (int thisNote = 0; thisNote < (sizeof(Pirates_note)/sizeof(int)); thisNote++) {int noteDuration = 1000 / Pirates_duration[thisNote];//convert duration to time delaytone(8, Pirates_note[thisNote], noteDuration);int pauseBetweenNotes = noteDuration * 1.05; //Here 1.05 is tempo, increase to play it slowerdelay(pauseBetweenNotes);
noTone(8);
}
}
Pins 2, 3, 4, and 5 are used to select a specific tone to play. By default, these pins are held high using internal pull-up resistors, which are pulled to ground when the button is pressed using the above line of code.
pinMode(2, INPUT_PULLUP);pinMode(3, INPUT_PULLUP);pinMode(4, INPUT_PULLUP);pinMode(5, INPUT_PULLUP);
The following code block is used to play a song when a button is pressed. It reads the digital value of each button and when it goes low (zero), it assumes that the button is pressed and plays the corresponding tone by calling the required function.
if (digitalRead(2)==0)
{ Serial.println("Selected -> ’He is a Pirate’ "); Play_Pirates(); }if (digitalRead(3)==0)
{ Serial.println("Selected -> ’Crazy Frog’ "); Play_CrazyFrog(); }if (digitalRead(4)==0)
{ Serial.println("Selected -> ’Mario UnderWorld’ "); Play_MarioUW(); }if (digitalRead(5)==0)
{ Serial.println("Selected -> ’He is a Pirate’ "); Play_Pirates(); }
Working of this Melody Player Arduino Circuit:
Once the code and hardware are ready, just burn the program into your Arduino and you can play the tone just by pressing the button. If you have any problems, check the serial monitor for debugging or use the comments section to report the problem, I will be happy to help you.
#include "pitches.h" //add Equivalent frequency for musical note#include "themes.h" //add Note vale and duration void Play_Pirates(){
for (int thisNote = 0; thisNote < (sizeof(Pirates_note)/sizeof(int)); thisNote++) {int noteDuration = 1000 / Pirates_duration[thisNote];//convert duration to time delaytone(8, Pirates_note[thisNote], noteDuration);int pauseBetweenNotes = noteDuration * 1.05; //Here 1.05 is tempo, increase to play it slowerdelay(pauseBetweenNotes);noTone(8); //stop music on pin 8 }
}void Play_CrazyFrog(){ for (int thisNote = 0; thisNote < (sizeof(CrazyFrog_note)/sizeof(int)); thisNote++) {int noteDuration = 1000 / CrazyFrog_duration[thisNote]; //convert duration to time delaytone(8, CrazyFrog_note[thisNote], noteDuration);int pauseBetweenNotes = noteDuration * 1.30;//Here 1.30 is tempo, decrease to play it fasterdelay(pauseBetweenNotes);noTone(8); //stop music on pin 8 }
}void Play_MarioUW(){for (int thisNote = 0; thisNote < (sizeof(MarioUW_note)/sizeof(int)); thisNote++) {int noteDuration = 1000 / MarioUW_duration[thisNote];//convert duration to time delaytone(8, MarioUW_note[thisNote], noteDuration);int pauseBetweenNotes = noteDuration * 1.80;delay(pauseBetweenNotes);noTone(8); //stop music on pin 8 }
}void Play_Titanic(){for (int thisNote = 0; thisNote < (sizeof(Titanic_note)/sizeof(int)); thisNote++) {int noteDuration = 1000 / Titanic_duration[thisNote];//convert duration to time delaytone(8, Titanic_note[thisNote], noteDuration);int pauseBetweenNotes = noteDuration * 2.70;delay(pauseBetweenNotes);noTone(8); //stop music on pin 8 }
}void setup() {pinMode(2, INPUT_PULLUP); //Button 1 with internal pull uppinMode(3, INPUT_PULLUP); //Button 2 with internal pull uppinMode(4, INPUT_PULLUP); //Button 3 with internal pull uppinMode(5, INPUT_PULLUP); //Button 4 with internal pull upSerial.begin(9600);
}void loop() {if (digitalRead(2)==0)
{ Serial.println("Selected -> ’He is a Pirate’ "); Play_Pirates(); }if (digitalRead(3)==0)
{ Serial.println("Selected -> ’Crazy Frog’ "); Play_CrazyFrog(); }if (digitalRead(4)==0)
{ Serial.println("Selected -> ’Mario UnderWorld’ "); Play_MarioUW(); }if (digitalRead(5)==0)
{ Serial.println("Selected -> ’Titanic’ "); Play_Titanic(); }
}
- TDA2009A power amplifier circuit
- 75W audio power amplifier made with TMOS150
- Two unique tube preamplifiers
- Biliary duct 2A3C Class A amplifier
- FU-7 Tube Amplifier Homemade
- Telephone volume amplifier circuit
- Preamplifier made of 6P15 tube
- Class AB2 Amplifier-McIntosh MC80
- High gain audio amplifier circuit composed of LM4818
- LM4915 is used for dual-channel amplifier circuit