buzzer-melodie.ino

Arduino Nano (Classic, ATmega328P) · File : buzzer-melodie.ino · Language : Arduino · Use case : Jouer une mélodie sur un buzzer piézo

A passive buzzer on pin 9 sings a tune thanks to tone(), which generates the required square wave in hardware on the Nano's ATmega328P. The melody is a simple frequency/duration table, endlessly extensible.

Hardware

An Arduino Nano classic (ATmega328P at 16 MHz, 30-pin DIL breadboard footprint, mini-B USB, 5 V logic, RESET pin at the lower-left corner). Arduino Nano, 5 V passive piezo buzzer (not an active buzzer!), pin 9.

Wiring

Buzzer (+) wire to D9, (-) wire to GND. Active buzzers sound on plain voltage: useless for melodies.

How it works

tone() configures timer 1 or 2 to produce the frequency on the pin; noTone() stops the oscillation. The flash-resident table (const) keeps the program compact.

Running it

In the Arduino IDE, select the Arduino Nano board and ATmega328P processor, pick the serial port, then upload. The board's 5 V rail suits 5 V sensors; otherwise use 3.3 V on compatible pins.

Variants

Add a button to trigger the melody, play on several pins for a duet, or read notes from a light sensor.

buzzer-melodie.ino

// Melodie sur buzzer passif avec tone()/noTone() (Arduino Nano).
// Le Nano (ATmega328P) genere le carre sur n'importe quelle broche.
const int BUZZER = 9;

// note : frequence Hz, duree ms (0 = silence de meme duree)
const uint16_t MELODIE[][2] = {
  {262, 300}, {330, 300}, {392, 300}, {523, 600},
  {392, 300}, {523, 300}, {659, 900},
  {0, 400},
};
const int N = sizeof(MELODIE) / sizeof(MELODIE[0]);

void setup() {
  pinMode(BUZZER, OUTPUT);
}

void loop() {
  for (int i = 0; i < N; i++) {
    uint16_t freq = MELODIE[i][0];
    uint16_t duree = MELODIE[i][1];
    if (freq > 0) tone(BUZZER, freq);
    else noTone(BUZZER);
    delay(duree);
  }
  noTone(BUZZER);
  delay(2000); // pause avant reprise
}

← Back to the board