def play_show(tune, pin=27, display=matrix.display, duration=None): from machine import Pin, PWM from utime import sleep_ms try: pwm = PWM(Pin(pin)) if duration is None: set_default(tune[0]) else: set_duration(duration) for tone in tune: tone = tone.upper() # all to upper if tone[0] not in Letter: continue if len(tone)==4: display.showstatic(tone.replace(":","")) else: display.showstatic(tone) m = midi(tone) pwm.freq(m[0]) # set frequency pwm.duty(m[1]) # set duty cycle sleep_ms(m[1]) display.clear() finally: pwm.deinit()
class Tft(display.TFT): "Bots specific TFT wrapper for display library." def __init__(self, backlight_pin, default_brightness=30): super().__init__() self.backlight = PWM(backlight_pin, freq=200, duty=default_brightness) def init(self, tft_type, **kwargs): super().init(tft_type, **kwargs) self.tft_writecmd(_SWRESET) # Software Rest sleep(0.2) self.tft_writecmd(_SLPOUT) # sleep out sleep(0.2) self.tft_writecmddata(_COLMOD, bytearray([0x05])) # set 16 bit color self.tft_writecmd(_DISPON) # Display on # this is orienation for my screen self.tft_writecmddata(_MADCTL, bytearray([0b10110000])) self.tft_writecmddata(_CASET, pack(">HH", 0, 159)) # set width from 0 to 159 # set height from 0 to 127 self.tft_writecmddata(_PASET, pack(">HH", 0, 127)) def brightness(self, percentage): self.backlight.duty(percentage) def deinit(self): super().deinit() self.backlight.deinit()
def onofflight(): SWon = False while (1): buzzer = PWM(Pin(2)) if SW.value() == 0 and SWon == False: SWon = True while (1): buzzer.freq(20) R.value(1) G.value(0) B.value(0) sleep(0.5) R.value(0) G.value(0) B.value(1) sleep(0.5) if SW.value() == 0: break buzzer.deinit() R.value(0) G.value(0) B.value(0) SWon = False
class LED: def __init__(self, pin_number): self._level = 0 self.pwm = PWM(Pin(pin_number, mode=Pin.OUT), freq=1024) # for some reason this is needed? sleep_ms(10) self.pwm.duty(0) @property def level(self): return self._level @level.setter def level(self, l): if l<0: l = 0 if l>1: l = 1 self._level = l self.pwm.duty(int(1023*l)) def deinit(self): self.pwm.deinit() self.pwm = None def __enter__(self): return self def __exit__(self, *args): self.deinit()
def playTone(self, tone, tone_duration, total_duration): if self.playSound: print(str(tone_duration) + " " + str(total_duration)) beeper = PWM(Pin(self.Buzzer, Pin.OUT), freq=tones[tone], duty=512) utime.sleep_ms(tone_duration) beeper.deinit() utime.sleep_ms(int(total_duration * 1000) - tone_duration)
def laser(): global statBuzzer #statBuzzer = 'off' while (1): infra.value(1) sleep(2) if ldr.read() > 4000 and infra.value() == 1: while (1): buzzer = PWM(Pin(2)) buzzer.freq(20) #statBuzzer = 'on' R.value(1) G.value(0) B.value(0) sleep(0.5) R.value(0) G.value(0) B.value(1) sleep(0.5) #print(SW.value()) if SW.value() == 0 or count % 2 == 1: buzzer.deinit() #statBuzzer = 'off' R.value(0) G.value(0) B.value(0) break sleep(0.2) if SW.value() == 0 or count % 2 == 1: infra.value(0) break
def play_show(tune, pin=27, display=matrix.display, duration=None): from machine import Pin, PWM from utime import sleep_ms try: pwm = PWM(Pin(pin)) if duration is None: set_default(tune[0]) else: set_duration(duration) for tone in tune: tone = tone.upper() # all to upper if tone[0] not in Letter: continue if len(tone) == 4: display.showstatic(tone.replace(":", "")) else: display.showstatic(tone) m = midi(tone) pwm.freq(m[0]) # set frequency pwm.duty(m[1]) # set duty cycle sleep_ms(m[1]) display.clear() finally: pwm.deinit()
class SOUND(): def __init__(self): pin = Pin(piNo) self.buzzer = PWM(pin) self.buzzer.duty(0) self.pr = False def __del__(self): self.buzzer.duty(0) self.buzzer.deinit() def debug(self, deb=True): self.pr = deb def sound(self, freq, duration=1, duty=512): if self.pr: print("sound start:" + str(freq) + " :" + str(duration) + " :" + str(duty)) self.buzzer.duty(duty) self.buzzer.freq(freq) sleep_ms(int(duration * 1000)) self.buzzer.duty(0) #self.buzzer.deinit() def sound_off(self): self.buzzer.freq(0) self.buzzer.duty(0)
def play_mario(): """ play Mario Bros tone example source from here http://www.linuxcircle.com/2013/03/31/playing-mario-bros-tune-with-arduino-and-piezo-buzzer/ """ p5 = Pin(5, Pin.OUT) pwm5 = PWM(p5) # mario = [E7, E7, 0, E7, 0, C7, E7, 0, G7, 0, 0, 0, G6, 0, 0, 0, C7, 0, 0, G6, 0, 0, E6, 0, 0, A6, 0, B6, 0, AS6, A6, 0, G6, E7, 0, G7, A7, 0, F7, G7, 0, E7, 0,C7, D7, B6, 0, 0, C7, 0, 0, G6, 0, 0, E6, 0, 0, A6, 0, B6, 0, AS6, A6, 0, G6, E7, 0, G7, A7, 0, F7, G7, 0, E7, 0,C7, D7, B6, 0, 0] mario = [ E5, E5, 0, E5, 0, C5, E5, 0, G5, 0, 0, 0, G4, 0, 0, 0, C5, 0, 0, G4, 0, 0, E4, 0, 0, A4, 0, B4, 0, AS4, A4, 0, G4, E5, 0, G5, A5, 0, F5, G5, 0, E5, 0, C5, D5, B4, 0, 0, C5, 0, 0, G4, 0, 0, E4, 0, 0, A4, 0, B4, 0, AS4, A4, 0, G4, E5, 0, G5, A5, 0, F5, G5, 0, E5, 0, C5, D5, B4, 0, 0 ] for note in mario: if note == 0: pwm5.duty(0) else: pwm5.freq(note) # change frequency for change tone pwm5.duty(30) sleep_ms(150) pwm5.deinit()
def releaseServo(pinNo, override=False): if not override: servoPin = getMappedPin(pinNo) else: servoPin = pinNo servo = PWM(pin(servoPin)) servo.deinit()
class Servo: def __init__(self,pin): self.pwm = PWM(Pin(pin),freq=50) self.max=self._map(2.35,0,20,0,1023) self.min=self._map(0.54,0,20,0,1023) self.angle(0) self.id = pin print("init %s"% (self.id)) self.lastStat=0 def angle(self,ang): if ang >= 180: ang=180 if ang < 0: ang=0 self.turn = self._map(ang,0,180,self.min,self.max) self.pwm.duty((int)(self.turn)) self.lastStat=ang def read(self): return self.lastStat def _map(self,x,inMin,inMax,outMin,outMax): return (x-inMin)*(outMax-outMin)/(inMax-inMin)+outMin def deinit(self): print("deinit %s"% (self.id)) self.pwm.deinit()
def marioTheme(gg): tempo = 5 beeper = PWM(Pin(gg.Buzzer, Pin.OUT), freq=440, duty=512) melody = ['e5', 'e5', 'e5', 'c5', 'e5', 'g5', 'g4', # bar 1 'c5', 'g4', 'e4', 'a4', 'b4', 'a#4', 'a4', # bar 2 'g4', 'e5', 'g5', 'a5', 'f5', 'g5', 'e5', 'c5', 'd5', 'b4', # bar 3 'c5', 'g4', 'e4', 'a4', 'b4', 'a#4', 'a4', # bar 4 'g4', 'e5', 'g5', 'a5', 'f5', 'g5', 'e5', 'c5', 'd5', 'b4', # bar 5 'g5', 'f#5', 'f5', 'd#5', 'e5', 'g#4', 'a4', 'c5', 'a4', 'c5', 'd5', # bar 6 'g5', 'f#5', 'f5', 'd#5', 'e5', 'c6', 'c6', 'c6', # bar 7 'g5', 'f#5', 'f5', 'd#5', 'e5', 'g#4', 'a4', 'c5', 'a4', 'c5', 'd5', # bar 8 'd#5', 'd5', 'c5'] # bar 9 rhythm = [8, 16, 8, 16, 16, 4, 4, # bar 1 8, 8, 8, 16, 16, 16, 16, # bar 2 8, 16, 16, 8, 8, 8, 8, 16, 16, 8, # bar 3 8, 8, 8, 16, 16, 16, 16, # bar 4 8, 16, 16, 8, 8, 8, 8, 16, 16, 8, # bar 5 16, 16, 16, 16, 8, 16, 16, 8, 16, 16, 8, # bar 6 16, 16, 16, 16, 8, 8, 16, 8, # bar 7 16, 16, 16, 16, 8, 16, 16, 8, 16, 16, 8, # bar 8 8, 8, 8] # bar 9 for tone, length in zip(melody, rhythm): print(tone) print(length) APressed, BPressed = gg.getButtons() if BPressed: break beeper.freq(tones[tone]) time.sleep(tempo / length) beeper.deinit()
class Feeder(object): def __init__( self, pin_servo=None, ): """ servo's minimum duty 27 """ self._open_position = 42 self._pause_open = 1 self._close_position = 77 self._servo = PWM(Pin(pin_servo, Pin.OUT), freq=50, duty=self._close_position) def deinit_servo(self): """""" self._servo.deinit() def feed(self): """""" print('Opening to: %i degrees.' % self._open_position) print('Pausing for: %f sec.\n' % self._pause_open) self._servo.duty(int(round(self._open_position))) time.sleep(self._pause_open) self._servo.duty(self._close_position)
class Motor: def __init__(self, pin1, pin2, pmin=0, pmax=1023): self.pin1 = PWM(Pin(pin1), freq=10000) self.pin2 = PWM(Pin(pin2), freq=10000) self.min = pmin self.max = pmax def deinit(self): self.pin1.deinit() self.pin2.deinit() def drive(self, power): span = self.max - self.min if power < 0: self.pin1.duty(0) self.pin2.duty(int(self.min + (-power) * span / 100)) elif power > 0: self.pin1.duty(int(self.min + power * span / 100)) self.pin2.duty(0) else: self.pin1.duty(1023) self.pin2.duty(1023) def stop(self): self.drive(0)
def motor(dir, speed, state, duty_cycle=750): stepper1 = PWM(Pin(2), freq=speed, duty=duty_cycle) if state == 0: stepper1.deinit() else: stepper1 = PWM(Pin(2), freq=speed, duty=duty_cycle) direction1 = Pin(4, Pin.OUT, value=dir)
class SpeakerController: def __init__(self, pin): from machine import Pin, PWM """ Controller for the speaker :param pin: the bin of the low voltage audio amplifier """ self.pin = Pin(pin, Pin.OUT) self.pwm = PWM(self.pin) self.pwm.deinit() self.pin.on() def alarm(self, freq=500, duty=550): """ Makes a pwm. This pwm gives a signal to the audio amplifier who then amplifies the pwm to the speaker :param freq: frequency of the pwm :param duty: the duty of the pwm """ from machine import PWM self.pwm = PWM(self.pin) self.pwm.init(freq=freq, duty=duty) def stop(self): """ Stops/de-inits the pwm """ self.pwm.deinit()
def sound_on_off(): buzzer = 0 for i in range(5): buzzer = PWM(Pin(25)) buzzer.freq(10) sleep(1) buzzer.deinit()
class Switch(): """ 创建一个开关类 """ def __init__(self, pin, freq=1000): """ 初始化绑定一个引脚,设置默认的PWM频率为1000 """ self.pwm = PWM(pin, freq=freq) def change_duty(self, duty): """ 改变占空比 """ if 0 <= duty and duty <= 1023: self.pwm.duty(duty) else: print('警告:占空比只能为 [0-1023] ') def deinit(self): """ 销毁 """ self.pwm.deinit() def pulse(self, period, gears): # 呼吸灯核心代码 # 借用sin正弦函数,将PWM范围控制在 23 - 1023范围内 # self 开关对象 # period 呼吸一次的周期 单位/毫秒 # gears 呼吸过程中经历的亮度档位数 for i in range(2 * gears): self.change_duty(int(math.sin(i / gears * math.pi) * 500) + 523) # 延时 utime.sleep_ms(int(period / (2 * gears)))
def playTone(self, tone, tone_duration, rest_duration=0): beeper = PWM(self.PinBuzzer, freq=self.tones[tone], duty=self.duty[self.vol]) sleep_ms(tone_duration) beeper.deinit() sleep_ms(rest_duration)
class myServo(object): def __init__(self, pin: int=15, hz: int=50, duty: int=512): self._servo = PWM(Pin(pin),hz,duty) def myServoWriteDuty(self, duty): if duty <= 26: duty = 26 if duty >= 128: duty = 128 self._servo.duty(duty) def myServoWriteAngle(self, pos): if pos <= 0: pos = 0 if pos >= 180: pos = 180 pos_buffer=(pos/180)*(128-26) self._servo.duty(int(pos_buffer)+26) def myServoWriteTime(self, us): if us <= 500: us = 500 if us >= 2500: us = 2500 pos_buffer=(1024*us)/20000 self._servo.duty(int(pos_buffer)) def deinit(self): self._servo.deinit()
class Motor: def __init__(self, m1, m2, dir, step, freq=50, duty=0): self.m1 = Pin(m1, Pin.OUT) self.m2 = Pin(m2, Pin.OUT) self.dir = Pin(dir, Pin.OUT) self.drive = PWM(Pin(step), freq, 0) self.duty = getDuty(duty) self.m1.value(0) self.m2.value(0) self.dir.value(0) def setDuty(self, duty): self.duty = duty self.drive.duty(duty) def setFreq(self, freq): self.drive.freq(freq) def setStepMode(self, mode): if 0 <= mode and mode <= 3: self.m1.value(1 & mode) self.m2.value(1 & (mode >> 1)) def setDir(self, dir): if 0 == dir or 1 == dir: self.dir.value(dir) def driveOn(self): self.drive.init() self.drive.duty(self.duty) def driveOff(self): self.drive.deinit()
class Servo: def __init__(self, pin: int or Pin or PWM, minVal=2500, maxVal=7500, maxDegrees=180): if isinstance(pin, int): pin = Pin(pin, Pin.OUT) if isinstance(pin, Pin): self.__pwm = PWM(pin) if isinstance(pin, PWM): self.__pwm = pin self.__pwm.freq(50) self.minVal = minVal self.maxVal = maxVal self.maxDegrees = maxDegrees def deinit(self): self.__pwm.deinit() def goto(self, value: int): delta = self.maxVal - self.minVal target = int(self.minVal + ((value / 1024) * delta)) self.__pwm.duty_u16(target) def gotoDeg(self, value: int): diff = int(self.maxVal - self.minVal) oneDegree = int(diff / self.maxDegrees) self.__pwm.duty_u16(self.minVal + (oneDegree * value)) def free(self): self.__pwm.duty_u16(0)
def pitch(freq, tim): pwm = PWM(Pin(25)) pwm.freq(freq) # set frequency # print('pwm.freq ' + str(pwm.freq())) # get current frequency pwm.duty(500) # set duty cycle sleep_ms(tim) pwm.deinit()
def blues(self): buz = PWM(self.pin) buz.freq(523) buz.duty(512) sleep_ms(100) buz.freq(622) sleep_ms(100) buz.freq(698) sleep_ms(100) buz.freq(739) sleep_ms(100) buz.freq(783) sleep_ms(100) buz.freq(987) sleep_ms(100) buz.freq(1046) sleep_ms(100) buz.freq(987) sleep_ms(100) buz.freq(783) sleep_ms(100) buz.freq(739) sleep_ms(100) buz.freq(698) sleep_ms(100) buz.freq(622) buz.deinit()
def timeset(): from machine import Pin, PWM LED_timeset = PWM(Pin(14), freq=2,duty=512) # flash LED indicates the timeset is not finished #flash frequency=1Hz, dutycycle=50% client.set_callback(sub_cb) # indicates that function 'sub_cb' will be executed after messsage has been received client.subscribe('esys/time') client.wait_msg() # blocking wait receiving datetime from the broker LED_timeset.deinit() # turn off PWM on the pin
def sound_after_1_count(): buzzer = 0 for i in range(2): buzzer = PWM(Pin(25)) buzzer.freq(10) sleep(1) buzzer.deinit()
class PWMOut(object): """PWM output.""" def __init__(self, pin, freq=50, duty=0, verbose=False, channel=-1): self._pin = PWM(Pin(pin)) self._pin.freq(freq) self._pin.duty_u16(duty) self._verbose = verbose if self._verbose: self.__logFrequency() def deinit(self): self._pin.deinit() @property def duty_percent(self): """ duty in percent """ return self._pin.duty_u16() / MAX_DUTY * 100 @duty_percent.setter def duty_percent(self, value): self._pin.duty_u16(int(min(max(0, value / 100.0 * MAX_DUTY), MAX_DUTY))) @property def duty(self): """ duty as raw value """ return self._pin.duty_u16() @duty.setter def duty(self, value): self._pin.duty_u16(int(value)) @property def freq_Hz(self): """ frequency in [Hz] """ return self._pin.freq() @freq_Hz.setter def freq_Hz(self, value): self._pin.freq(value) if self._verbose: self.__logFrequency() @property def max_duty(self): return MAX_DUTY @property def uses_rmt(self): return False def __logFrequency(self): print("PWM frequency is {0:.1f} kHz".format(self.freq_Hz / 1000)) def __setRMTDuty(self, value): pass
def stop(pin=27): from machine import Pin, PWM try: pwm = PWM(Pin(pin)) pwm.duty(0) pwm.freq(1) finally: pwm.deinit()
def tone(frequency, duration=100, pin=None, volume=1): if pin is None: pin = Pin(SPEAKER_PIN) pwm = PWM(pin, duty=volume % 50) pwm.freq(frequency) time.sleep_ms(duration) pwm.deinit()
def buzz(what): """ callback function for the timer """ global timer_running buzz = Pin(12, Pin.OUT) pwm = PWM(buzz, freq=500, duty=770) sleep(0.05) pwm.deinit() timer_running = False
def _tone(self, freq, duration, silentDur): if self.buzzer >= 0: if silentDur <= 0: silentDur = 1 # -- use 50% duty cycle pwm = PWM(self.buzzerPin, int(round(freq)), 512) utime.sleep_ms(duration) pwm.deinit() utime.sleep_ms(silentDur)
def pitch(freq,pin=27,tim=1000): from machine import Pin,PWM from utime import sleep_ms try: pwm=PWM(Pin(pin)) pwm.freq(freq) pwm.duty(tim) sleep_ms(tim) finally: pwm.deinit()
def pitch(self,pin=27,freq=440,tim=0): from machine import Pin,PWM from utime import sleep_ms pwm=PWM(Pin(pin)) if freq>0: pwm.freq(int(freq)) else: pwm.duty(0) if tim>0: sleep_ms(tim) pwm.deinit()
def pulse(): for i in range(0, 101): p = PWM(0, Pin("P17", mode=Pin.OUT), freq=PWM.FREQ_16MHZ, duty=i, period=16000) p.init() time.sleep_ms(10) p.deinit() for i in range(0, 101): p = PWM(0, Pin("P17", mode=Pin.OUT), freq=PWM.FREQ_16MHZ, duty=100-i, period=16000) p.init() time.sleep_ms(10) p.deinit()
def play(self,tune,pin=27,duration=None): from machine import Pin,PWM from utime import sleep_ms pwm=PWM(Pin(pin)) if duration is None: self.set_default(tune[0]) else: self.set_duration(duration) for tone in tune: tone=tone.upper() if tone[0]not in Letter: continue midi=self.midi(tone) pwm.freq(midi[0]) sleep_ms(midi[1]) pwm.deinit()
class Buzz(object): def __init__(self,pin=6): self.id=pins_remap_esp32[pin] self.io=Pin(self.id) self.io.value(1) self.isOn=False def on(self,freq=500): if self.isOn is False: self.pwm=PWM(self.io,freq,512) self.isOn=True def off(self): if self.isOn: self.pwm.deinit() self.io.init(self.id,Pin.OUT) self.io.value(1) self.isOn=False def freq(self,freq): self.pwm.freq(freq)
def play(tune,pin=27,duration=None): from machine import Pin,PWM from utime import sleep_ms try: pwm=PWM(Pin(pin)) if duration is None: set_default(tune[0]) else: set_duration(duration) for tone in tune: tone=tone.upper() if tone[0]not in Letter: continue m=midi(tone) pwm.freq(m[0]) pwm.duty(m[1]) sleep_ms(m[1]) finally: pwm.deinit()
def play_show(self,tune,pin=27,display=matrix.display,duration=None): from machine import Pin,PWM from utime import sleep_ms pwm=PWM(Pin(pin)) if duration is None: self.set_default(tune[0]) else: self.set_duration(duration) for tone in tune: tone=tone.upper() if tone[0]not in Letter: continue if len(tone)==4: display.showstatic(tone.replace(":","")) else: display.showstatic(tone) midi=self.midi(tone) pwm.freq(midi[0]) sleep_ms(midi[1]) display.clear() pwm.deinit()
def stop(self, pin=27): from machine import Pin, PWM pwm = PWM(Pin(pin)) pwm.duty(0) pwm.freq(1) pwm.deinit()
def right(self): p = PWM(0, self.pin, freq=PWM.FREQ_125KHZ, pulse_width=275, period=2500, mode=PWM.MODE_HIGH_LOW) p.init() time.sleep_ms(200) p.deinit()
class ServoController: _pwm_freq = 200 _tone_duty = { 'l': 342, 'm': 318, 'h': 293} _mallet_duty = { 'd': 265, 'u': 350} _servo_tone = None _servo_mallet = None def __init__(self, pin_tone, pin_mallet): self._servo_tone = PWM(Pin(pin_tone), freq=self._pwm_freq) self._servo_mallet = PWM(Pin(pin_mallet), freq=self._pwm_freq) def ring(self, tone, move=True, raise_time=0.12): if move: self.rot_tone(tone) time.sleep(0.7) self.rot_mallet('d') time.sleep(raise_time) self.rot_mallet('u') time.sleep(0.3 - raise_time) def rot_tone(self, tone): self._servo_tone.duty(self._tone_duty[tone]) time.sleep(0.05) self._servo_tone.deinit() def rot_mallet(self, state): self._servo_mallet.duty(self._mallet_duty[state]) def init(self): self._servo_tone.init() self._servo_mallet.init() def deinit(self, servo=None): if servo is None: self._servo_tone.deinit() self._servo_mallet.deinit() elif servo == 'tone': self._servo_tone.deinit() elif servo == 'mallet': self._servo_mallet.deinit() def _use_servo(fn): def inner(self): self.init() self.rot_mallet('u') fn(self) self.deinit() return inner @_use_servo def morning(self): self.ring('m') self.ring('m', move=False) self.ring('m', move=False) self.ring('h') @_use_servo def finish1(self): self.ring('m') @_use_servo def finish2(self): self.ring('h')