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),) BEEPBEEP = ((700,1100),(100,None),(600,1100)) # 0: BEEEEP BEEEEP BEEEEEP # 1: Alle Meine Entchen ALARMTONES = (((300,1200),(100,None),(200,1200),(300,None),(None,10)), ((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),(1600,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),(1600,c)),) class Buzzer(): def __init__(self,pin,duty = 1000): 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 #print("Play sound!") for i in range(len(self.sound)): s = self.sound[i] if s[0] == None: if s[1]-timesPlayed == 0: break else: i = 0 timesPlayed += 1 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 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