🛠 Mélodie sur buzzer LilyPad

LilyPad Arduino · intermediaire · Schéma : IMG-lilypad-intermediaire-2-lilypad-buzzer-melodie.svg — Buzzer LilyPad sur la pastille 10, notes de musique et contact de déclenchement cousu sur la pastille 2.

Objectives

Play a melody with a sewn buzzer: generating a square wave signal with tone on a PWM pad, triggering via contact, and respecting the battery budget (the SimpleSnap's integrated battery is only 110 mAh). You will also learn how to stop the oscillation to avoid draining the LiPo.

Materials

Complete code

// Mélodie sur buzzer passif — pastille PWM 10, contact sur 2
const uint8_t BUZZER = 10; // pastille PWM (5/6/9/10/11 sur Simple/SimpleSnap)
const uint8_t BOUTON = 2;  // contact cousu vers « − », pull-up interne

const uint16_t MELODIE[] = {523, 659, 784, 1047}; // do mi sol do aigu (Hz)
const uint16_t DUREE[]   = {180, 180, 180, 400};  // ms

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

void loop {
  if (digitalRead(BOUTON) == LOW) {       // contact fermé -> on joue
    for (uint8_t i = 0; i < 4; i++) {
      tone(BUZZER, MELODIE[i], DUREE[i]); // carré ~50 % sur la pastille PWM
      delay(DUREE[i] + 40);               // petite pause entre les notes
    }
    noTone(BUZZER);                       // ne pas laisser la broche osciller
    while (digitalRead(BOUTON) == LOW) {} // anti-réenchaînement
  }
}

Expected verification

When the two push buttons are contacted, four ascending notes (C–E–G–high C) sound, the last one being longer, followed by total silence. The sound is clear and does not buzz continuously: noTone properly stops the oscillation. Each new contact restarts the melody only once.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials