🛠 Mélodie sur buzzer LilyPad
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
- 1 LilyPad SimpleSnap + 3.7 V battery
- 1 passive buzzer (commercial LilyPad buzzers are often active, playing only one note — check the label)
- 2 push buttons for the trigger contact
- FTDI adapter for uploading
- >
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
- Treating an active buzzer as passive: an active buzzer plays only one fixed frequency; a melody requires a passive buzzer.
- Forgetting noTone: the pin continues to oscillate, draining the 110 mAh battery quickly.
- Using tone on a non-PWM pad: sound is absent or erratic depending on the AVR core variant.
- Missing debounce: the melody restarts in a loop as long as the contact is maintained.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinopwm-respiration.inoArduinoluxmetre-couture.inoArduinointerrupteur-tilt.inoArduinoservo-balayage.inoArduino