from machine import Pin, PWM
import utime
buzzer = PWM(Pin(20))
def tone(pin, freq, duration):
if freq == 0:
pin.duty_u16(0)
utime.sleep_ms(duration)
return
pin.freq(freq)
pin.duty_u16(30000)
utime.sleep_ms(duration)
pin.duty_u16(0)
utime.sleep_ms(50) # 余韻の間
# スーパーマリオBGM(周波数, 長さ[ms])
melody = [
(660, 100), (660, 100), (0, 200), (660, 100),
(0, 200), (520, 100), (660, 100), (0, 200),
(770, 100), (0, 500), (380, 100)
]
# 演奏処理
for note, duration in melody:
tone(buzzer, note, duration)