buzzer-melodie.ino

Teensy 4.0 · File : buzzer-melodie.ino · Language : Arduino · Use case : Mélodie sur buzzer avec tone() et table de notes

A rising then falling scale plays on a passive buzzer through tone(). The melody lives in flash (PROGMEM + pgm_read_near_int), a healthy habit that keeps RAM free for audio or sensor processing.

Hardware

A Teensy 4.0 (NXP i.MX RT1062, Cortex-M7 @ 600 MHz, 3.3 V logic) powered over USB. 1 passive buzzer 3.3-5 V.

Wiring

Buzzer between pin 16 and GND. On Teensy, tone() works on nearly every pin without timer conflicts.

How it works

tone(pin, frequency, duration) sets an audio PWM; reading the table from flash spares RAM. A 0 entry in the table marks a rest.

Running it

With Teensyduino in the Arduino IDE, select « Teensy 4.0 », Upload then confirm in the Teensy Loader. Pins are 3.3 V; the 4.0 is pin-compatible with the 3.2.

Variants

Move to the Teensy Audio library to mix several sound voices, or play a melody received over USB MIDI.

buzzer-melodie.ino

// Melodie sur buzzer passif : tone() + table de notes en flash.
const int BUZZER = 16;

const int MELODIE[] PROGMEM = {
  523, 587, 659, 698, 784, 880, 988, 1046, // gamme montante (Hz)
  1046, 988, 880, 784, 698, 659, 587, 523, // gamme descendante
  0 // 0 = silence
};

void setup() {
  Serial.begin(9600);
  Serial.println(F("Melodie Teensy"));
}

void loop() {
  int n = sizeof(MELODIE) / sizeof(MELODIE[0]);
  for (int i = 0; i < n; i++) {
    int f = pgm_read_near_int(&MELODIE[i]); // lecture depuis la flash
    if (f == 0) {
      noTone(BUZZER);
      delay(300);
    } else {
      tone(BUZZER, f, 180); // 180 ms par note
      delay(200);
    }
  }
  delay(2000);
}

// Sur Teensy, tone() fonctionne sur a peu pres toutes les broches
// et ne gene pas les autres timers (contrairement aux AVR).

← Back to the board