We use tone() to play sounds or melodies on a speaker connected to an Arduino. It helps make projects more fun and interactive.
Playing melodies with tone() in Arduino
tone(pin, frequency, duration);
pin is the Arduino pin connected to the speaker.
frequency is the sound pitch in Hertz (Hz).
duration is how long the tone plays in milliseconds (optional).
tone(8, 440);
tone(8, 523, 500);
noTone(8);This program plays a simple melody of 8 notes on a speaker connected to pin 8. Each note plays for a quarter note duration, then pauses briefly before the next note. The melody repeats forever.
const int speakerPin = 8; // Notes in the melody (frequencies in Hz) int melody[] = {262, 294, 330, 349, 392, 440, 494, 523}; // Note durations: 4 = quarter note, 8 = eighth note, etc. int noteDurations[] = {4, 4, 4, 4, 4, 4, 4, 4}; void setup() { // no setup needed } void loop() { for (int thisNote = 0; thisNote < 8; thisNote++) { int noteDuration = 1000 / noteDurations[thisNote]; tone(speakerPin, melody[thisNote], noteDuration); // Pause between notes int pauseBetweenNotes = noteDuration * 1.3; delay(pauseBetweenNotes); noTone(speakerPin); } delay(1000); // Wait before repeating melody }
You must connect a piezo speaker or buzzer to the Arduino pin and ground to hear the sound.
Use noTone(pin) to stop the sound before playing the next note.
Delays control the timing between notes to make the melody sound right.
tone() plays a sound at a specific pitch on a speaker pin.
You can create melodies by playing notes one after another with pauses.
Use noTone() to stop sounds before playing new ones.
