buzzer-melodie.ino

Arduino Pro Mini · File : buzzer-melodie.ino · Language : Arduino · Use case : Jouer une mélodie sur un buzzer piézo avec les notes nommées

A passive piezo buzzer plays the start of "Au clair de la lune". tone() generates an exact frequency on a pin; the melody is stored in a (note, duration) table like a score, easy to extend.

Hardware

An Arduino Pro Mini (ATmega328P, 5 V/16 MHz or 3.3 V/8 MHz variants) wired to a USB-serial adapter (FTDI) or an ICSP programmer. 1 passive buzzer (5 V) — an active buzzer only beeps, no tone().

Wiring

Buzzer + wire to pin 8, - wire to GND. On AVR, tone() avoids pins whose timers Servo occupies.

How it works

tone(pin, frequency, duration) sets a timer to produce the audio square wave. The note table is read sequence by sequence with a proportional delay.

Running it

Select « Arduino Pro Mini » in the IDE (5 V/16 MHz or 3.3 V/8 MHz per your model), ATmega328P processor, the right port, then Upload. The adapter must be wired DTR-DTR, RX-TX, TX-RX, VCC-VCC, GND-GND.

Variants

Add a button to trigger the melody, or play from a table stored in EEPROM/flash (PROGMEM) to save RAM.

buzzer-melodie.ino

// Melodie sur buzzer passif avec la fonction tone() et une table de notes.
const int BUZZER = 8; // broche tone() sur les AVR (pas 9/10 si Servo actif)

// Frequences (Hz) des notes d'une octave.
const int NOTE_DO = 262, NOTE_RE = 294, NOTE_MI = 330, NOTE_FA = 349,
          NOTE_SOL = 392, NOTE_LA = 440, NOTE_SI = 494, NOTE_DO2 = 523;

// "Au clair de la lune" (debut) : note, duree en temps.
const int melody[][2] = {
  {NOTE_DO, 1}, {NOTE_DO, 1}, {NOTE_DO, 1}, {NOTE_RE, 2},
  {NOTE_MI, 1}, {NOTE_MI, 1}, {NOTE_RE, 2}, {NOTE_DO, 4},
  {NOTE_RE, 1}, {NOTE_RE, 1}, {NOTE_RE, 2}, {NOTE_MI, 1},
  {NOTE_SOL, 1}, {NOTE_MI, 1}, {NOTE_DO, 4},
};

void setup() {
  Serial.begin(9600);
  Serial.println(F("Lecture de la melodie..."));
}

void loop() {
  const int TEMPS = 220; // ms par unite de duree
  for (unsigned int i = 0; i < sizeof(melody) / sizeof(melody[0]); i++) {
    int note = melody[i][0];
    int duree = melody[i][1] * TEMPS;
    tone(BUZZER, note, duree * 9 / 10); // petite pause entre les notes
    delay(duree);
  }
  delay(3000); // pause avant repetition
}

← Back to the board