Tone Melody example script (phyduino.py) Plays a short tune on a piezo buzzer on D8, then waits two seconds and plays it again. MicroPython has no tone(): a PWM output at 50 % duty makes the note, and a duty of 0 is silence.
- Wiring
- A piezo buzzer between D8 and GND (or a small speaker in series with a 100 Ohm resistor).
- Uses
- pwm()
import time
import phyduino as mcu
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 play(buzzer, frequency, duration_ms):
"""Plays one note (or a rest, if frequency is 0) on buzzer for duration_ms."""
if frequency:
buzzer.freq(frequency)
buzzer.duty_u16(32768)
time.sleep_ms(duration_ms)
buzzer.duty_u16(0)
buzzer = mcu.pwm("D8")
while True:
for note, duration in zip(MELODY, DURATIONS):
length_ms = 1000 // duration
play(buzzer, note, length_ms)
time.sleep_ms(length_ms * 3 // 10)
time.sleep(2)