Bird
0
0
Arduinoprogramming~5 mins

Playing melodies with tone() in Arduino

Choose your learning style9 modes available
Introduction

We use tone() to play sounds or melodies on a speaker connected to an Arduino. It helps make projects more fun and interactive.

You want to add simple music or sound effects to your Arduino project.
You want to alert someone with a beep or melody when an event happens.
You want to learn how to control sound with code on Arduino.
Syntax
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).

Examples
Play a 440 Hz tone (A note) on pin 8 until stopped.
Arduino
tone(8, 440);
Play a 523 Hz tone (C note) on pin 8 for 500 milliseconds.
Arduino
tone(8, 523, 500);
Stop any tone playing on pin 8.
Arduino
noTone(8);
Sample Program

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.

Arduino
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
}
OutputSuccess
Important Notes

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.

Summary

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.