buzzer-melodie.ino

Arduino Mega 2560 (Rev3) · File : buzzer-melodie.ino · Language : Arduino · Use case : Jouer une mélodie sur un buzzer piézo avec tone()

tone() generates a square wave at the requested frequency on the buzzer pin; two arrays hold notes (Hz) and durations (beats). A passive piezo (no onboard oscillator) is required for melodies.

Hardware required

An Arduino Mega 2560 (ATmega2560, 16 MHz, 5 V): 54 digital I/O, 15 PWM, 16 analog inputs, 4 hardware UARTs. 1 passive 5 V buzzer.

Wiring

Buzzer + to pin 8, − to GND.

How it works

Each note plays for 90% of its slot, the remainder forming the gap between notes — that is what makes the melody readable. In the Arduino IDE, select « Arduino Mega 2560 » and the port, then Upload. PWM on 2-13 and 44-46; UART1=18/19, UART2=16/17, UART3=14/15; SPI on 50-53.

Going further

Add a button to switch melodies, or a potentiometer for tempo.

buzzer-melodie.ino

// Melodie sur buzzer passif : tableaux notes/durees.
const int BUZZER = 8;

const int MELODIE[] = {262, 330, 392, 523, 392, 330, 262}; // do mi sol do...
const int DUREES[]  = {4, 4, 4, 2, 4, 4, 2};              // en temps

void setup() {
  Serial.begin(9600);
}

void loop() {
  int tempo = 1000 / 4;
  for (size_t i = 0; i < sizeof(MELODIE) / sizeof(MELODIE[0]); i++) {
    int ms = tempo * 4 / DUREES[i];
    tone(BUZZER, MELODIE[i], ms * 9 / 10); // 90% de la note, puis silence
    delay(ms);
  }
  delay(1000);
}

← Back to the board