Tone Melody example script (arduino.py) Plays a short tune on a piezo buzzer on D8, then waits two seconds and plays it again. tone() returns straight away, so delay() waits while the note plays.
- Wiring
- A piezo buzzer between D8 and GND (or a small speaker in series with a 100 Ohm resistor).
- Uses
- tone(), noTone(), delay()
from arduino import *
BUZZER_PIN = 8
NOTE_G3 = 196
NOTE_A3 = 220
NOTE_B3 = 247
NOTE_C4 = 262
MELODY = (NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4)
DURATIONS = (4, 8, 8, 4, 4, 4, 4, 4)
def setup():
pass
def loop():
for note, duration in zip(MELODY, DURATIONS):
length_ms = 1000 // duration
tone(BUZZER_PIN, note, length_ms)
delay(length_ms * 13 // 10)
noTone(BUZZER_PIN)
delay(2000)
def main():
setup()
while True:
loop()
if __name__ == "__main__":
main()