93 lines
2.9 KiB
Python
93 lines
2.9 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
|
|
|
|
# Sounds
|
|
# (Duration,Freq)
|
|
# If Last Duration is None play last Freq times (negative = infinite)
|
|
|
|
BEEP = ((100,1100),(100,None))
|
|
BEEPBEEP = ((700,1100),(100,None),(600,1100))
|
|
BOOP = ((100,120),(100,None))
|
|
|
|
# 0: BEEEEP BEEEEP BEEEEEP
|
|
# 1: Alle Meine Entchen
|
|
# 2: BIYIIIIEP
|
|
ALARMTONES = (((300,1200),(80,None),(200,1200),(300,None),(None,10)),
|
|
((400,c),(80,None),(400,d),(80,None),(400,e),(80,None),(400,f),(80,None),\
|
|
(900,g),(80,None),(900,g),(80,None),(400,a),(80,None),(400,a),(80,None),\
|
|
(400,a),(80,None),(400,a),(80,None),(1900,g),(80,None),(400,a),(80,None),\
|
|
(400,a),(80,None),(400,a),(80,None),(400,a),(80,None),(1600,g),(80,None),\
|
|
(400,f),(80,None),(400,f),(80,None),(400,f),(80,None),(400,f),(80,None),\
|
|
(900,e),(80,None),(900,e),(80,None),(400,d),(80,None),(400,d),(80,None),\
|
|
(400,d),(80,None),(400,d),(80,None),(1600,c)),\
|
|
((1000,10000),(None,10)),)
|
|
|
|
class Buzzer():
|
|
def __init__(self,pin,duty = 512):
|
|
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
|
|
timesPlayed = 0
|
|
i = 0
|
|
while i < len(self.sound):
|
|
s = self.sound[i]
|
|
if s[0] == None:
|
|
if s[1]-timesPlayed == 0:
|
|
break
|
|
else:
|
|
i = 0
|
|
timesPlayed += 1
|
|
continue
|
|
if (s[1] != None):
|
|
self._pwm.freq(s[1])
|
|
self._pwm.duty(self.duty)
|
|
pass
|
|
else:
|
|
self._pwm.duty(0)
|
|
await asyncio.sleep_ms(s[0])
|
|
if self.newSound or self.sound == None:
|
|
break
|
|
i+=1
|
|
if not self.newSound:
|
|
self.newSound = False
|
|
self.sound = None
|
|
self._pwm.duty(0)
|
|
|
|
async def awaitFinish(self):
|
|
while self.isPlaying():
|
|
await asyncio.sleep_ms(50)
|
|
|
|
def awaitFinish_nonasync(self):
|
|
asyncio.get_event_loop().run_until_complete(self.awaitFinish())
|
|
|
|
def playSound(self,sound):
|
|
self.newSound = sound != None
|
|
self.sound = sound
|
|
|
|
def stop(self):
|
|
self.sound = None
|
|
self._pwm.duty(0)
|
|
|
|
def isPlaying(self):
|
|
return self.sound != None |