stepper-clock/Buzzer.py
2020-03-19 23:05:35 +01:00

69 lines
2.2 KiB
Python

import machine
import uasyncio as asyncio
c = 261 #Hz
d = 294 #Hz
e = 329 #Hz
f = 349 #Hz
g = 392 #Hz
a = 440 #Hz
b = 493 #Hz
C = 523 #Hz
# (Duration,Freq)
# If Last Duration is None play endlessly
# 0: Silent
# 1: BeepBeep
# 2: Alle Meine Entchen
SOUNDS = [((0,None),),\
((700,1000),(100,None),(600,1000)),\
((400,c),(100,None),(400,d),(100,None),(400,e),(100,None),(400,f),(100,None),\
(900,g),(100,None),(900,g),(100,None),(400,a),(100,None),(400,a),(100,None),\
(400,a),(100,None),(400,a),(100,None),(1900,g),(100,None),(400,a),(100,None),\
(400,a),(100,None),(400,a),(100,None),(400,a),(100,None),(1900,g),(100,None),\
(400,f),(100,None),(400,f),(100,None),(400,f),(100,None),(400,f),(100,None),\
(900,e),(100,None),(900,e),(100,None),(400,d),(100,None),(400,d),(100,None),\
(400,d),(100,None),(400,d),(100,None),(2000,c))]#,(None,None)
class Buzzer():
def __init__(self,pin,duty = 100):
self._pwm = machine.PWM(machine.Pin(2), freq=0, duty=0)
self.sound = None
self.duty = duty
self.newSound = True
loop = asyncio.get_event_loop()
loop.create_task(self._update_async())
async def _update_async(self):
while True:
if self.sound == None:
await asyncio.sleep_ms(200)
self._pwm.duty(0)
else:
self.newSound = False
for i in range(len(self.sound)):
s = self.sound[i]
if s[0] == None:
i = 0
if (s[1] != None):
self._pwm.freq(s[1])
self._pwm.duty(self.duty)
else:
self._pwm.duty(0)
await asyncio.sleep_ms(s[0])
if self.newSound or self.sound == None:
break
if (not self.newSound):
self.sound = None
self.newSound = False
def playSound(self,sound):
self.newSound = True
self.sound = sound
def stop(self):
self.sound = None
def isPlaying(self):
return self.sound == None