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 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()
class Buzzer: """ A buzzer that plays musical notes. Usage: buzzer = Buzzer() buzzer.force() """ NOTES = dict( c=261, d=294, e=329, f=349, g=391, gS=415, a=440, aS=455, b=466, cH=523, cSH=55, dH=587, dSH=62, eH=659, fH=698, fSH=74, gH=784, gSH=83, aH=880, ) def __init__(self, pin=12): self.pwm = PWM(pin, duty=0) def tone(self, freq, duration): freq = round(freq) duration = round(duration * 0.9) pause = round(duration * 0.1) if freq > 0: self.pwm.init(freq=freq, duty=50) time.sleep_ms(duration) self.pwm.duty(0) time.sleep_ms(pause) def random_song(self): tune = RTTTL(random_song()) for freq, duration in tune.notes(): self.tone(freq, duration) def play_song_num(self, num): tune = RTTTL(song_num(num)) for freq, duration in tune.notes(): self.tone(freq, duration) def on(self, note): self.pwm.init(freq=Buzzer.NOTES[note], duty=50) def off(self): self.pwm.duty(0)
class DCMOTOR: """ A simple class for controlling DC motors with a motor driver. Args: Direction turn pin (int): This pin must support PWM. Opposite direction turn pin (int): The pin must support PWM. """ # vel_vals=[2000,2500,3000,3500,25000] def __init__(self, direction_pin, oppo_pin): self.direction_pin = PWM(Pin(direction_pin), freq=50, duty=0) self.direction_pin.deinit() self.oppo_pin = PWM(Pin(oppo_pin), freq=50, duty=0) self.oppo_pin.deinit() self.freq = 50 def move(self, direction, delay_vel): self.direction_pin.deinit() self.oppo_pin.deinit() if direction == 1: self.direction_pin.init(duty=delay_vel) elif direction == 0: self.oppo_pin.init(duty=delay_vel) else: pass def stop(self): self.direction_pin.deinit() self.oppo_pin.deinit()
class Speaker: def __init__(self, pin): self.speaker = PWM(pin) self.volume = 1 def play_tone(self, frequency, duration=1): self.speaker.init(frequency, self.volume) sleep(duration) self.speaker.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()
def pulse(self, duty=25, ms=40): """Briefly pulse the motor. :param int duty: Duty cycle, in percent. :param int ms: Duration, in milliseconds. """ pwm = PWM(0, self.pin, freq=self.freq, duty=duty, period=self.period) pwm.init() time.sleep_ms(ms) pwm.deinit() self.pin.value(self.active_low)
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()
class Buzzer(): """Wrap a buzzer :param pin: The pin the buzzer is attached to """ def __init__(self, pin): self._pin = Pin(pin) self._pwm = PWM(self._pin) self.off() def on(self, f=440): """Turn the buzzer on :param f: The frequency to buzz at """ self._pwm.freq(f) self._pwm.duty(512) self._pwm.init() def off(self): """Turn the buzzer off """ self._pwm.duty(0) self._pwm.deinit() self._pin.off() def buzz(self, f=440, t=500): """Buzz at a given frequency for a given time :param f: The frequency to buzz at :param t: The time to buzz (ms) """ self.on(f) sleep_ms(t) self.off() def tune(self, sequence=melody): """Play a tune :param sequence: Sequence of tuple (freq, time) """ idx = 0 while idx < len(sequence): f, t = sequence[idx] idx += 1 self.buzz(f, t) if idx < len(sequence): t = sequence[idx] idx += 1 sleep_ms(t)
class Servo: """ A simple class for controlling hobby servos. Args: pin (machine.Pin): The pin where servo is connected. Must support PWM. freq (int): The frequency of the signal, in hertz. min_us (int): The minimum signal length supported by the servo. max_us (int): The maximum signal length supported by the servo. angle (int): The angle between the minimum and maximum positions. """ def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180): self.min_us = min_us self.max_us = max_us self.us = 0 self.freq = freq self.angle = angle self.pin = pin self.pwm = PWM(self.pin, freq=self.freq, duty=0) self.init() def init(self): self.pwm.init() def write_us(self, us): """Set the signal to be ``us`` microseconds long. Zero disables it.""" if us == 0: self.pwm.duty(0) return us = min(self.max_us, max(self.min_us, us)) duty = us * 1024 * self.freq // 1000000 self.pwm.duty(duty) def write_angle(self, degrees=None, radians=None): """Move to the specified angle in ``degrees`` or ``radians``.""" if degrees is None: degrees = math.degrees(radians) degrees = degrees % 360 total_range = self.max_us - self.min_us us = self.min_us + total_range * degrees // self.angle self.write_us(us) def release(self): self.pwm.deinit()
class PWMOut(object): """PWM output.""" def __init__(self, pin, freq=5000, duty=0): self._pin = PWM(Pin(pin)) self._pin.init(freq=freq, duty=duty) def deinit(self): self._pin.deinit() @property def duty_percent(self): """ duty in percent """ return self._pin.duty() /MAX_DUTY *100 @duty_percent.setter def duty_percent(self, value): self._pin.duty(int(min(max(0, value/100.0 *MAX_DUTY), MAX_DUTY))) @property def duty(self): """ duty as raw value """ return self._pin.duty() @duty.setter def duty(self, value): self._pin.duty(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) @property def max_duty(self): return MAX_DUTY
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 pulse(self, duty=25, ms=40): pwm = PWM(0, self.pin, freq=self.freq, duty=duty, period=self.period) pwm.init() time.sleep_ms(ms) pwm.deinit() self.pin.value(self.active_low)
class IR: _active_high = True # Hardware turns IRLED on if pin goes high. _space = 0 # Duty ratio that causes IRLED to be off timeit = False # Print timing info @classmethod def active_low(cls): if ESP32: raise ValueError('Cannot set active low on ESP32') cls._active_high = False cls._space = 100 def __init__(self, pin, cfreq, asize, duty, verbose): if ESP32: self._pwm = PWM(pin[0]) # Continuous 36/38/40KHz carrier self._pwm.deinit() # ESP32: 0 <= duty <= 1023 self._pwm.init(freq=cfreq, duty=round(duty * 10.23)) self._rmt = RMT(0, pin=pin[1], clock_div=80) # 1μs resolution else: # Pyboard if not IR._active_high: duty = 100 - duty tim = Timer(2, freq=cfreq) # Timer 2/pin produces 36/38/40KHz carrier self._ch = tim.channel(1, Timer.PWM, pin=pin) self._ch.pulse_width_percent(self._space) # Turn off IR LED # Pyboard: 0 <= pulse_width_percent <= 100 self._duty = duty self._tim = Timer(5) # Timer 5 controls carrier on/off times self._tcb = self._cb # Pre-allocate self._arr = array('H', 0 for _ in range(asize)) # on/off times (μs) self._mva = memoryview(self._arr) # Subclass interface self.verbose = verbose self.carrier = False # Notional carrier state while encoding biphase self.aptr = 0 # Index into array def _cb(self, t): # T5 callback, generate a carrier mark or space t.deinit() p = self.aptr v = self._arr[p] if v == STOP: self._ch.pulse_width_percent(self._space) # Turn off IR LED. return self._ch.pulse_width_percent(self._space if p & 1 else self._duty) self._tim.init(prescaler=84, period=v, callback=self._tcb) self.aptr += 1 # Public interface # Before populating array, zero pointer, set notional carrier state (off). def transmit(self, addr, data, toggle=0, validate=False): # NEC: toggle is unused t = ticks_us() if validate: if addr > self.valid[0] or addr < 0: raise ValueError('Address out of range', addr) if data > self.valid[1] or data < 0: raise ValueError('Data out of range', data) if toggle > self.valid[2] or toggle < 0: raise ValueError('Toggle out of range', toggle) self.aptr = 0 # Inital conditions for tx: index into array self.carrier = False self.tx(addr, data, toggle) # Subclass populates ._arr self.trigger() # Initiate transmission if self.timeit: dt = ticks_diff(ticks_us(), t) print('Time = {}μs'.format(dt)) # Subclass interface def trigger(self): # Used by NEC to initiate a repeat frame if ESP32: self._rmt.write_pulses(tuple(self._mva[0:self.aptr]), start=1) else: self.append(STOP) self.aptr = 0 # Reset pointer self._cb(self._tim) # Initiate physical transmission. def append(self, *times): # Append one or more time peiods to ._arr for t in times: self._arr[self.aptr] = t self.aptr += 1 self.carrier = not self.carrier # Keep track of carrier state self.verbose and print('append', t, 'carrier', self.carrier) def add(self, t): # Increase last time value (for biphase) assert t > 0 self.verbose and print('add', t) # .carrier unaffected self._arr[self.aptr - 1] += t
i2c.readfrom_mem_into(acc_id, 0x32, read) x = (read[1] << 8 | read[0]) & 1023 x = acc_trans(x, 10) y = (read[3] << 8 | read[2]) & 1023 y = acc_trans(y, 10) z = (read[5] << 8 | read[4]) & 1023 z = acc_trans(z, 10) - offset[0] sleep(1) return x, y, z while True: if interrupt2 > 0: led_board.value(0) pwm.init() offset = bytearray(1) i2c.readfrom_mem_into(acc_id, 0x20, offset) read = bytearray(6) i2c.readfrom_mem_into(acc_id, 0x32, read) value_x = (read[1] << 8 | read[0]) & 1023 value_x = acc_trans(value_x, 10) value_y = (read[3] << 8 | read[2]) & 1023 value_y = acc_trans(value_y, 10) value_z = (read[5] << 8 | read[4]) & 1023 value_z = acc_trans(value_z, 10) / acc_trans(value_z, 10) vel_x = pre_vel_x + value_x * 0.3 vel_y = pre_vel_y + value_y * 0.3 vel_z = pre_vel_z + value_z * 0.3
from time import sleep import sys from gc import collect led_red_pwm, led_green_pwm = PWM(Pin(14)), PWM(Pin(33)) led_red_pwm.deinit() led_green_pwm.deinit() year = int(input("Year? ")) month = int(input("Month? ")) day = int(input("Day? ")) weekday = int(input("Weekday? ")) hour = int(input("Hour? ")) minute = int(input("Minute? ")) second = int(input("Second? ")) microsecond = int(input("Microsecond? ")) led_red_pwm.init() led_green_pwm.init() #Hardware Timer def hardDispTime(timer): print("Date: " + str(rtc.datetime()[1]) + "." + str(rtc.datetime()[2]) + "." + str(rtc.datetime()[0])) print("Time: " + str(rtc.datetime()[4]) + ":" + str(rtc.datetime()[5]) + ":" + str(rtc.datetime()[6])) #print(rtc.datetime()) hardTimer = Timer(0) rtc = RTC() rtc.datetime((year, month, day, weekday, hour, minute, second, microsecond))
class Buzzer(): B0 = 31 C1 = 33 CS1 = 35 D1 = 37 DS1 = 39 E1 = 41 F1 = 44 FS1 = 46 G1 = 49 GS1 = 52 A1 = 55 AS1 = 58 B1 = 62 C2 = 65 CS2 = 69 D2 = 73 DS2 = 78 E2 = 82 F2 = 87 FS2 = 93 G2 = 98 GS2 = 104 A2 = 110 AS2 = 117 B2 = 123 C3 = 131 CS3 = 139 D3 = 147 DS3 = 156 E3 = 165 F3 = 175 FS3 = 185 G3 = 196 GS3 = 208 A3 = 220 AS3 = 233 B3 = 247 C4 = 262 CS4 = 277 D4 = 294 DS4 = 311 E4 = 330 F4 = 349 FS4 = 370 G4 = 392 GS4 = 415 A4 = 440 AS4 = 466 B4 = 494 C5 = 523 CS5 = 554 D5 = 587 DS5 = 622 E5 = 659 F5 = 698 FS5 = 740 G5 = 784 GS5 = 831 A5 = 880 AS5 = 932 B5 = 988 C6 = 1047 CS6 = 1109 D6 = 1175 DS6 = 1245 E6 = 1319 F6 = 1397 FS6 = 1480 G6 = 1568 GS6 = 1661 A6 = 1760 AS6 = 1865 B6 = 1976 C7 = 2093 CS7 = 2217 D7 = 2349 DS7 = 2489 E7 = 2637 F7 = 2794 FS7 = 2960 G7 = 3136 GS7 = 3322 A7 = 3520 AS7 = 3729 B7 = 3951 C8 = 4186 CS8 = 4435 D8 = 4699 DS8 = 4978 def __init__(self): self.notes = { 'cdef': [ self.C6, self.D6, self.E6, self.F6, self.G6, self.A6, self.B6, self.C7, self.D7, self.E7, self.F7, self.G7, self.A7, self.B7, self.C8, 0 ], 'mario': [ self.E7, self.E7, 0, self.E7, 0, self.C7, self.E7, 0, self.G7, 0, 0, 0, self.G6, 0, 0, 0, self.C7, 0, 0, self.G6, 0, 0, self.E6, 0, 0, self.A6, 0, self.B6, 0, self.AS6, self.A6, 0, self.G6, self.E7, 0, self.G7, self.A7, 0, self.F7, self.G7, 0, self.E7, 0, self.C7, self.D7, self.B6, 0, 0, self.C7, 0, 0, self.G6, 0, 0, self.E6, 0, 0, self.A6, 0, self.B6, 0, self.AS6, self.A6, 0, self.G6, self.E7, 0, self.G7, self.A7, 0, self.F7, self.G7, 0, self.E7, 0, self.C7, self.D7, self.B6, 0, 0 ], 'starwars': [ self.A4, 0, 0, 0, self.A4, 0, 0, 0, self.A4, 0, 0, 0, self.F4, 0, 0, self.C5, self.A4, 0, 0, 0, self.F4, 0, 0, self.C5, self.A4, 0, 0, 0, 0, 0, 0, 0, self.E5, 0, 0, 0, self.E5, 0, 0, 0, self.E5, 0, 0, 0, self.F5, 0, 0, self.C5, self.GS4, 0, 0, 0, self.F4, 0, 0, self.C5, self.A4, 0, 0, 0, 0, 0, 0, 0, ], } # Init self.pwm = PWM(Pin(27, Pin.OUT)) self.pwm.duty(0) def playnotes(self, title, length=150, duty=64): if title not in self.notes: print('unknown title: {}'.format(title)) return melody = self.notes[title] print('Play', title) for i in melody: if i == 0: self.pwm.duty(0) else: self.pwm.freq(i) self.pwm.duty(duty) time.sleep_ms(length) self.pwm.duty(0) def beep(self, freq=440, duty=64): self.pwm.freq(freq) self.pwm.duty(duty) def mute(self): self.pwm.duty(0) def reset(self): self.pwm.duty(0) self.pwm.deinit() self.pwm.init()
def pwmled(pin): #all leds use the same timer led = PWM(pin, timer=1) led.init(freq=10000) led.duty(100) return led
class PWMOut(object): """PWM output.""" def __init__(self, pin, freq=50, duty=0, verbose=False, channel=-1): if channel in [i for i in range(RMT_MAX_CHAN)]: self._chanRMT = channel self._pin = RMT(channel, pin=Pin(pin), clock_div=RMT_CLOCK_DIV) self.__setRMTDuty(duty) self._pin.loop(True) else: self._chanRMT = -1 self._pin = PWM(Pin(pin)) self._pin.init(freq=freq, duty=duty) self._verbose = verbose if self._verbose: self.__logFrequency() def deinit(self): self._pin.deinit() @property def duty_percent(self): """ duty in percent """ if self._chanRMT < 0: return self._pin.duty() / MAX_DUTY * 100 else: return self._dutyRMT / RMT_DUTY_SCALER @duty_percent.setter def duty_percent(self, value): if self._chanRMT < 0: self._pin.duty(int(min(max(0, value / 100.0 * MAX_DUTY), MAX_DUTY))) else: self.__setRMTDuty( min(max(0, value / 100. * RMT_MAX_DUTY), RMT_MAX_DUTY)) @property def duty(self): """ duty as raw value """ if self._chanRMT < 0: return self._pin.duty() else: return self._dutyRMT @duty.setter def duty(self, value): if self._chanRMT < 0: self._pin.duty(int(value)) else: self.__setRMTDuty(value) @property def freq_Hz(self): """ frequency in [Hz] """ if self._chanRMT < 0: return self._pin.freq() else: return self._pin.source_freq() / RMT_CLOCK_DIV @freq_Hz.setter def freq_Hz(self, value): if self._chanRMT < 0: self._pin.freq(value) else: if value == 0: self._pin.loop(False) else: self._pin.loop(True) d2 = int( (self._pin.source_freq() / RMT_CLOCK_DIV) / value // 2) self._pin.write_pulses((d2, d2)) if self._verbose: self.__logFrequency() @property def max_duty(self): if self._chanRMT < 0: return MAX_DUTY else: return RMT_MAX_DUTY @property def uses_rmt(self): return self._chanRMT >= 0 def __logFrequency(self): print("PWM frequency is {0:.1f} kHz".format(self.freq_Hz / 1000)) def __setRMTDuty(self, value): self._dutyRMT = int(min(max(1, value), RMT_MAX_DUTY)) self._pin.write_pulses((self._dutyRMT, RMT_MAX_DUTY - self._dutyRMT))
class Buzz(Notes): def __init__(self, pin=None): super(__class__, self).__init__() self.buz = PWM(Pin(pin)) if pin else None self.buz.deinit() self.listening = False self.instructions = [] async def tone(self, freq, duration, duty=50): if not self.buz: return None self.buz.init() self.buz.freq(int(freq)) self.buz.duty(duty) await asyncio.sleep(duration) self.buz.deinit() async def tones(self, freq_list, interval, duty=50): if not self.buz: return None self.buz.init() self.buz.duty(duty) for f in freq_list: self.buz.freq(int(f)) await asyncio.sleep(interval) self.buz.deinit() def play(self, note, duration=1, duty=50): loop.create_task(self.tone(self.notes[note.upper()], duration, duty)) def rand(self, n, duration=1, octaves=[4]): n_dur = duration / float(n) def gen(): for i in range(n): note = self.note_names[random.getrandbits(4) % 12] yield self.notes[note + str(get_random(octaves))] loop.create_task(self.tones(gen(), n_dur)) async def _wave(self, y_func, max_x, step_size): if not self.buz: return None self.buz.init() self.buz.duty(50) for x in range(int(max_x)): self.buz.freq(int(y_func(x))) await asyncio.sleep(step_size) self.buz.deinit() def sine(self, period=1, smoothness=100): max_x = period * smoothness step_size = 1.0 / smoothness y = lambda x: 550 + (450 * math.sin(2 * math.pi * x / max_x)) loop.create_task(self._wave(y_func=y, max_x=max_x, step_size=step_size)) def cos(self, period=1, smoothness=100): max_x = period * smoothness step_size = 1.0 / smoothness y = lambda x: 550 + (450 * math.cos(2 * math.pi * x / max_x)) loop.create_task(self._wave(y_func=y, max_x=max_x, step_size=step_size)) def log(self, period=1, smoothness=100): max_x = period * smoothness step_size = 1.0 / smoothness y = lambda x: (math.log(x + 1) * 100) + 100 loop.create_task(self._wave(y_func=y, max_x=max_x, step_size=step_size))
class LED_a(): isPWMinit = False def __init__(self, pin, freq=1000): self.pin = pin self.freq = freq self.led = Pin(self.pin, Pin.OUT) self.led.value(1) def deinit(self): if self.isPWMinit: self.led.deinit() self.isPWMinit = False self.led = Pin(self.pin, Pin.OUT) self.led.value(1) def brightness(self, value=None): if value == None: if self.isPWMinit: return 255 - (self.led.duty() >> 2) else: return (self.led.value() + 1) % 2 elif value >= 255: value = 255 self.on() elif value <= 0: value = 0 self.off() else: if not self.isPWMinit: self.led = PWM(Pin(self.pin), self.freq) self.led.init() self.isPWMinit = True self.led.duty(((256 - value) << 2) - 1) def fade_up(self, delay=5): # pwmIntervals = 100 # R = (pwmIntervals * math.log10(2))/(math.log10(255)); # for i in range(pwmIntervals): # led_red.brightness(int(math.pow(2, (i / R)) - 1)) # time.sleep_ms(t) for i in range(100): self.brightness(int(sin((i - 50) / 100 * pi) * 128 + 128)) sleep_ms(delay) def fade_down(self, delay=5): for i in range(100): self.brightness(int(sin((i + 50) / 100 * pi) * 128 + 127)) sleep_ms(delay) def pulse(self, delay=5): self.fade_up(delay) self.fade_down(delay) def on(self): self.deinit() self.led.value(0) def off(self): self.deinit() self.led.value(1) def toggle(self): self.deinit() self.led.value((self.led.value() + 1) % 2)
class LED(): isPWMinit = False def __init__(self, pin, freq=1000): self.pin = pin self.freq = freq self.led = Pin(self.pin, Pin.OUT) #self.pwmIntervals = 255 #self.R = self.pwmIntervals /log(1023) #R = 36.79391 def deinit(self): if self.isPWMinit: self.led.deinit() self.isPWMinit = False self.led = Pin(self.pin, Pin.OUT) self.led.value(1) def brightness(self, value=None): if value == None: if self.isPWMinit: return (self.led.duty() >> 2) else: return self.led.value() elif not 0 <= value <= 255: raise ValueError("Brightness out of range") else: if not self.isPWMinit: self.led = PWM(Pin(self.pin), self.freq) self.led.init() self.isPWMinit = True self.led.duty(value << 2) # Next Line was inspired by # https://diarmuid.ie/blog/pwm-exponential-led-fading-on-arduino-or-other-platforms/ # but i dropped it because it doesn't look better than linear fading for me. #self.led.duty(int(exp( (value / 36.79391)) - 1)) # Next Line was inspired by this post: # https://electronics.stackexchange.com/a/11100 # but it looked even worse #self.led.duty(int(1 / (1 + exp( ((value / 21) -6) * -1)) * 1024)) def fade_up(self, delay=5): for i in range(100): self.brightness(int(sin((i - 50) / 100 * pi) * 128 + 128)) sleep_ms(delay) def fade_down(self, delay=5): for i in range(100): self.brightness(int(sin((i + 50) / 100 * pi) * 128 + 127)) sleep_ms(delay) def pulse(self, delay=5): self.fade_up(delay) self.fade_down(delay) def on(self): self.deinit() self.led.value(1) def off(self): self.deinit() self.led.value(0) def toggle(self): self.deinit() self.led.value((self.led.value() + 1) % 2)
class NOTIFIER: def __init__(self, buzz_pin, led_pin, fq=4000, on_time=150, n_times=2, off_time=50, timer=None, period=5000): self.led = Pin(led_pin, Pin.OUT) self.fq = fq self.duty = 512 self.buzz = PWM(Pin(buzz_pin), freq=self.fq, duty=self.duty) self.buzz.deinit() self.on_time = on_time self.n_times = n_times self.off_time = off_time self.period = period self.irq_busy = False self.tim = timer self.blink = True self.use_dict = {'buzz': self.buzzer_call, 'led': self.blink_call} if timer is not None: self.tim = Timer(timer) def buzz_beep(self, beep_on_time, n_times, beep_off_time, fq, led=True): self.buzz.freq(fq) if led: for i in range(n_times): self.buzz.init() self.led.on() time.sleep_ms(beep_on_time) self.buzz.deinit() self.led.off() time.sleep_ms(beep_off_time) else: for i in range(n_times): self.buzz.init() time.sleep_ms(beep_on_time) self.buzz.deinit() time.sleep_ms(beep_off_time) def led_blink(self, led_on_time, n_times, led_off_time): for i in range(n_times): self.led.on() time.sleep_ms(led_on_time) self.led.off() time.sleep_ms(led_off_time) def buzzer_call(self, x): if self.irq_busy: return else: self.irq_busy = True self.buzz_beep(self.on_time, self.n_times, self.off_time, self.fq, self.blink) self.irq_busy = False def blink_call(self, x): if self.irq_busy: return else: self.irq_busy = True self.led_blink(self.on_time, self.n_times, self.off_time) self.irq_busy = False def notify(self, use='buzz', mode='SHOT', timeout=5000, on_init=None): self.irq_busy = False if on_init is not None: on_init() notify_call = self.use_dict[use] if mode == 'SHOT': self.tim.init(period=timeout, mode=Timer.ONE_SHOT, callback=notify_call) elif mode == 'PERIODIC': self.tim.init(period=timeout, mode=Timer.PERIODIC, callback=notify_call) def stop_notify(self): self.tim.deinit() self.irq_busy = False
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')
from machine import Pin, PWM, ADC, reset, RTC, Timer, I2C, UART import ssd1306, network, time, ujson, ure, binascii from umqtt.simple import MQTTClient # define basic objects : screen, clock, led,adc i2c = I2C(1,scl=Pin(23),sda=Pin(22)) display = ssd1306.SSD1306_I2C(128,32,i2c) rtc = RTC tim = Timer(-1) blue = Pin(2,Pin.OUT) riner_low = Pin(19,Pin.OUT) riner_low.value(0) riner_pwm = PWM(Pin(18), freq=550, duty=512) riner_pwm.init() adc0=ADC(Pin(32)) adc0.atten(ADC.ATTN_11DB) adc0.width(ADC.WIDTH_12BIT) # define basic connetion info nbiot_upload_addr = "http://sager.ga:888" nbiot_upload_path = "/test" #SSID="CQUPTHub" #password="******" key = 'This is the key!' url = 'a15f12ce46.iot-mqtts.cn-north-4.myhuaweicloud.com' port = 1883
class BuzzPlayer(): def __init__(self, bee_gpio_num, timer_id_num): self.__pwm = PWM(Pin(bee_gpio_num), freq=_FREQ_QUITE, duty=_VOLUME_DUTY[0]) self.__timer = get_shared_timer(timer_id_num) self.__timer_id = 0 self.__target_note_time = ticks_ms() self.__volume = len(_VOLUME_DUTY) - 1 self.__note_shift = 0 self.__buzz_file = None # self.__ticks_per_beat = _DEFAULT_TICKS_PER_BEAT # self.__frame_count = 0 self.__frame_pointer = 0 self.__tempo = _DEFAULT_TEMPO self.__event_callback = None self.__loop = False # status self.__is_playing = False # CPython self.__output = _pyg_output self.__output.set_instrument(26) # self.__output = mido.open_output() # self.__output.send(mido.Message('program_change', program=2)) self.__playing = None @property def is_playing(self): return self.__is_playing @property def volume(self): return self.__volume @property def note_shift(self): return self.__note_shift def _timer_callback(self, _=None): # schedule(self.play_next_note, True) self.play_next_note(True) def note_on(self, note, volume): if self.__playing: self.__output.note_off(self.__playing, 0) note = note + self.__note_shift + 7 note = 0 if note < 0 else note note = 128 - 1 if note >= 128 else note self.__output.note_on(note, volume*127//9) self.__playing = note # if self.__playing: # last = self.__playing # msg = mido.Message('note_off', channel=0, note=last.note, velocity=0) # self.__playing = None # self.__output.send(msg) # msg = mido.Message('note_on', channel=0, note=note, velocity=volume*128//10) # self.__playing = msg # self.__output.send(msg) def note_off(self): if self.__playing: self.__output.note_off(self.__playing, 0) self.__playing = None def play_next_note(self, play_next_note=False): try: try: time, frame_type, padding, frame_data = parse_bee_frame(self.__buzz_file.file.read(8)) except: return time = time * self.__tempo // self.__buzz_file.ticks_per_beat // 1000 # us -> ms # play next note self.__frame_pointer += 1 if self.__frame_pointer < self.__buzz_file.frame_count and play_next_note and time > 0: # set timer event as soon as possible self.__target_note_time = ticks_add(self.__target_note_time, time) target_period = ticks_diff(self.__target_note_time, ticks_ms()) self.__timer_id = self.__timer.init(mode=ONE_SHOT, period=target_period, callback=self._timer_callback) # deal with frame if frame_type == TYPE_SET_TEMPO: self.__tempo = int.from_bytes(frame_data, 'big') elif frame_type == TYPE_NOTE_OFF: self.note_off() elif frame_type == TYPE_NOTE_ON: self.note_on(frame_data[0], self.__volume) elif frame_type == TYPE_EMIT_EVENT and self.__event_callback != None: self.__event_callback(frame_data, padding) # control next note if self.__frame_pointer < self.__buzz_file.frame_count and play_next_note and time <= 0: self.play_next_note(True) return time if self.__frame_pointer >= self.__buzz_file.frame_count: if self.__loop: self.start(True) else: self.stop() return time except Exception as e: import usys usys.print_exception(e) def init(self): self.__pwm.init(freq=_FREQ_QUITE, duty=_VOLUME_DUTY[0]) def deinit(self): self.stop() self.unload() self.__pwm.deinit() def start(self, loop=False): self.__is_playing = True self.__loop = loop self.__frame_pointer = 0 self.__buzz_file.file.seek(10) self.__target_note_time = ticks_ms() self.__timer_id = self.__timer.init(mode=ONE_SHOT, period=1, callback=self._timer_callback) def stop(self): self.note_off() self.__timer.deinit(self.__timer_id) self.__pwm.freq(_FREQ_QUITE) self.__pwm.duty(_VOLUME_DUTY[0]) self.__is_playing = False def load(self, buzz_sound_file): self.__buzz_file = buzz_sound_file def unload(self): self.stop() self.__tempo = _DEFAULT_TEMPO self.__buzz_file = None def set_volume(self, volume): ''' set volume 0~9 ''' volume = 0 if volume < 0 else volume volume = len(_VOLUME_DUTY) - 1 if volume >= len(_VOLUME_DUTY) else volume self.__volume = volume def set_note_shift(self, note_shift): ''' set volume 0~9 ''' self.__note_shift = note_shift def set_event_callback(self, callback): ''' set event callback, (event_data, padding) -> None ''' self.__event_callback = callback
class BUZZER: def __init__(self, PIN, fq=4000, duty=512, sleept=150, ntimes=2, ntspace=50): self.duty = duty self.fq = fq self.buff = bytearray(3) self.tim = Timer(-1) self.tim2 = Timer(2) self.irq_busy = False self.hour = 0 self.minute = 0 self.second = 0 self.alarm = False self.buzz = PWM(Pin(PIN), freq=self.fq, duty=self.duty) self.buzz.deinit() self.buzz_button = Pin(12, Pin.OUT) self.buzz_detect = Pin(32, Pin.IN) self.buzz_button.on() self.irq_busy_buzz = False self.sleeptime = sleept self.ntimes = ntimes self.ntspace = ntspace self.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, G7, FS7, F7, DS7, 0, E7, 0, GS6, A6, C7, 0, 0, A6, C7, D7, G7, FS7, F7, DS7, 0, E7, 0, 0, C8, 0, C8, C8, 0, 0, 0, G7, FS7, F7, DS7, 0, E7, 0, GS6, A6, C7, 0, 0, A6, C7, D7, 0, 0, DS7, 0, D7, 0, 0, C7, 0, 0, 0, C7, C7, 0, C7, 0, C7, D7, 0, E7, C7, 0, A6, G6, 0, 0, C7, C7, 0, C7, 0, C7, D7, E7, 0, 0, C7, C7, 0, C7, 0, C7, D7, 0, E7, C7, 0, A6, G6, 0, E7, E7, E7, 0, C7, E7, 0, G7, 0, 0, 0, 0, G6, E7, C7, 0, G6, 0, GS6, 0, 0, A6, 0, F7, 0, F7, A6, 0, B6, A7, 0, A7, 0, A7, 0, G7, 0, F7, 0, E7, C7, 0, A6, G6, 0, 0, E7, C7, 0, G6, 0, GS6, 0, 0, A6, F7, 0, F7, A6, 0, 0, B6, 0, F7, 0, F7, 0, F7, 0, E7, 0, D7, 0, C7, 0, 0, 0, C7, 0, G6, 0, 0, E6, 0, 0, A6, 0, B6, 0, A6, 0, 0, GS6, 0, AS6, 0, GS6, 0, 0, E6, D6, E6 ] def time_print(self): return ('{}:{}:{}'.format(time.localtime()[3], time.localtime()[4], time.localtime()[5])) def buzz_beep(self, sleeptime, ntimes, ntimespaced, fq): self.buzz.freq(fq) for i in range(ntimes): self.buzz.init() time.sleep_ms(sleeptime) self.buzz.deinit() time.sleep_ms(ntimespaced) def set_alarm_at(self, h, m, s): self.alarm = True self.hour = h self.minute = m self.second = s self.start_alarm() def check_alarm(self): self.buff[0], self.buff[1], self.buff[2] = time.localtime( )[3], time.localtime()[4], time.localtime()[5] if (self.buff[0] == self.hour) and (self.buff[1] == self.minute) and ( self.buff[2] == self.second): return True def beep_alarm(self, x): if self.irq_busy: return try: self.irq_busy = True # print(self.time_print()) if self.alarm is True: if self.check_alarm(): for i in range(3): self.buzz_beep(150, 3, 100, self.fq) time.sleep_ms(500) self.tim.deinit() self.alarm = False self.irq_busy = False except Exception as e: self.irq_busy = False def start_alarm(self, timeout=1000): self.irq_busy = False self.tim.init(period=timeout, mode=Timer.PERIODIC, callback=self.beep_alarm) def stop(self): self.tim.deinit() self.irq_busy = False def buzzer_callback(self, x): if self.irq_busy_buzz: return else: if self.buzz_detect.value() == 1: # reverse op == 0 self.buzz_beep(150, 3, 100, self.fq) self.buzz_detect.init(Pin.OUT) time.sleep_ms(1000) self.buzz_detect.value(0) # reverse op == 1 self.buzz_detect.init(Pin.IN) # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy_buzz = False def active_button(self, PIN1, PIN2): self.buzz_button = Pin(PIN1, Pin.OUT) self.buzz_detect = Pin(PIN2, Pin.IN) self.buzz_button.on() self.buzz_detect.irq(trigger=Pin.IRQ_RISING, handler=self.buzzer_callback) def buzzer_callback_rev(self, x): if self.irq_busy_buzz: return else: if self.buzz_detect.value() == 0: # reverse op == 0 self.buzz_beep(150, 3, 100, self.fq) self.buzz_detect.init(Pin.OUT) time.sleep_ms(1000) self.buzz_detect.value(1) # reverse op == 1 self.buzz_detect.init(Pin.IN) # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy_buzz = False def active_button_rev(self, PIN1, PIN2): self.buzz_button = Pin(PIN1, Pin.OUT) self.buzz_detect = Pin(PIN2, Pin.IN) self.buzz_button.on() self.buzz_detect.irq(trigger=Pin.IRQ_FALLING, handler=self.buzzer_callback_rev) def buzz_beep_callback(self, x): if self.irq_busy: return try: self.irq_busy = True self.buzz_beep(self.sleeptime, self.ntimes, self.ntspace, self.fq) self.irq_busy = False except Exception as e: self.irq_busy = False def beep_interrupt(self): self.irq_busy = False self.tim2.init(period=1, mode=Timer.ONE_SHOT, callback=self.buzz_beep_callback) def sound_effect_up_down(self, fi, ff, fst, ts): fq_range = [i for i in range(fi, ff, fst)] self.buzz.init() for f in fq_range: self.buzz.freq(f) time.sleep_ms(ts) fq_range.reverse() for f in fq_range: self.buzz.freq(f) time.sleep_ms(ts) self.buzz.deinit() def sound_effect_random(self, fi, ff, fst, ts): fq_range = [urandom.randint(fi, ff) for i in range(fi, ff, fst)] self.buzz.init() for f in fq_range: self.buzz.freq(f) time.sleep_ms(ts) fq_range.reverse() for f in fq_range: self.buzz.freq(f) time.sleep_ms(ts) self.buzz.deinit() def sec_alarm(self, ntimes=10): for i in range(ntimes): self.sound_effect_up_down(1250, 6250, 200, 5) def play_tone(self, ts, scale=0, tone=None): if tone is None: tone = self.mario self.buzz.init() for f in tone: if f != 0: self.buzz.freq(f + scale) else: self.buzz.freq(f) time.sleep_ms(ts) self.buzz.deinit()
# # Copyright (c) 2006-2019, RT-Thread Development Team # # SPDX-License-Identifier: MIT License # # Change Logs: # Date Author Notes # 2019-06-13 SummerGift first version # from machine import PWM # Import PWM class from machine pwm = PWM( 3, 3, 1000, 100 ) # Create PWM object. Currently, 3 channels of PWM device numbered 3 are used. # The initialization frequency is 1000Hz and the duty ratio value is 100 (duty ratio is 100/255 = 39.22%). pwm.freq(2000) # Set the frequency of PWM object pwm.freq() # Get the frequency of PWM object print(pwm) # Show PWM object information pwm.duty(200) # Sets the duty ratio value of PWM object pwm.duty() # Get the duty ratio value of PWM object print(pwm) # Show PWM object information pwm.deinit() # Close PWM object pwm.init(3, 1000, 100) # Open and reconfigure the PWM object print(pwm) # Show PWM object information
from machine import Pin,PWM import network import os import time import socket import gc SSID="YOURSSID" #set the wifi ID PASSWORD="******" #set the wifi password wlan=None s=None led=None def connectWifi(ssid,passwd): global wlan wlan=network.WLAN(network.STA_IF) #create a wlan object wlan.active(True) #Activate the network interface wlan.disconnect() #Disconnect the last connected WiFi wlan.connect(ssid,passwd) #connect wifi while(wlan.ifconfig()[0]=='0.0.0.0'): time.sleep(1) return True def ajaxWebserv(): # minimal Ajax in Control Webserver global s,led s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create stream socket s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #Set the value of the given socket option s.bind((wlan.ifconfig()[0], 80)) #bind ip and port s.listen(1) #listen message while True: conn, addr = s.accept() #Accept a connection,conn is a new socket object #print("Got a connection from %s" % str(addr))
class U_IRQ_MG: def __init__(self, signal_pin, irq_pin, buzz_pin=None, led_pin=None, timeout=1000, driver_pin=None, n_vars=3, p_format='f'): self.sig_pin = signal_pin self.irq_pin = irq_pin self.driver_pin = driver_pin self.sig_button = None self.irq_detect = None self.fq = 4000 self.duty = 512 self.irq_busy = False if buzz_pin is not None: self.buzz = PWM(Pin(buzz_pin), freq=self.fq, duty=self.duty) self.buzz.deinit() if led_pin is not None: self.led = Pin(led_pin, Pin.OUT) self.irq_count = 0 self.irq_message = "INTERRUPT DETECTED" self.irq_detflag = False self.irq_timeout = timeout # ms self.sensor_vals = array(p_format, (0 for _ in range(n_vars))) self.cli_soc = None def reset_flag(self): self.irq_detflag = False def reset_flag_counter(self): self.irq_count = 0 def set_irq_msg(self, msg): self.irq_message = msg def irq_state(self): state = {'IRQ_DETECTED': self.irq_detflag, 'IRQ_COUNT': self.irq_count, 'SENSOR_DATA': list(self.sensor_vals)} self.reset_flag() return(state) def wait_irq(self, reset=True): if reset: self.reset_flag() while not self.irq_detflag: pass time.sleep_ms(10) return self.irq_state() def wait_async_irq(self, reset=True): if reset: self.reset_flag() while not self.irq_detflag: pass time.sleep_ms(10) return self.irq_state() def check_irq(self): return self.irq_state() def connect_SOC(self, host, port): self.irq_busy = True self.cli_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.cli_soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) soc_addr = socket.getaddrinfo(host, port)[0][-1] self.cli_soc.connect(soc_addr) self.irq_busy = False def disconnect_SOC(self): self.irq_busy = True self.cli_soc.close() self.irq_busy = False def buzz_beep(self, sleeptime, ntimes, ntimespaced, fq): self.buzz.freq(fq) for i in range(ntimes): self.buzz.init() time.sleep_ms(sleeptime) self.buzz.deinit() time.sleep_ms(ntimespaced) def sound_effect_up_down(self, fi, ff, fst, ts): fq_range = [i for i in range(fi, ff, fst)] self.buzz.init() for f in fq_range: self.buzz.freq(f) time.sleep_ms(ts) fq_range.reverse() for f in fq_range: self.buzz.freq(f) time.sleep_ms(ts) self.buzz.deinit() def sec_alarm(self, ntimes=10): for i in range(ntimes): self.sound_effect_up_down(1250, 6250, 200, 5) def led_blink(self, sleeptime, ntimes, ntimespaced): for i in range(ntimes): self.led.on() time.sleep_ms(sleeptime) self.led.off() time.sleep_ms(ntimespaced) def active_button(self, callback): self.sig_button = Pin(self.sig_pin, Pin.OUT) self.irq_detect = Pin(self.irq_pin, Pin.IN) self.sig_button.on() self.irq_detect.irq(trigger=Pin.IRQ_RISING, handler=callback) def active_button_rev(self, callback): self.sig_button = Pin(self.sig_pin, Pin.OUT) self.irq_detect = Pin(self.irq_pin, Pin.IN) self.sig_button.on() self.irq_detect.irq(trigger=Pin.IRQ_FALLING, handler=callback) def buzzer_callback(self, x): if self.irq_busy: return else: self.irq_busy = True if self.irq_detect.value() == 1: # reverse op == 0 self.buzz_beep(150, 3, 100, self.fq) self.irq_detect.init(Pin.OUT) time.sleep_ms(self.irq_timeout) self.irq_detect.value(0) # reverse op == 1 self.irq_detect.init(Pin.IN) self.irq_count += 1 self.irq_detflag = True # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy = False def buzzer_callback_rev(self, x): if self.irq_busy: return else: self.irq_busy = True if self.irq_detect.value() == 0: # reverse op == 0 self.buzz_beep(150, 3, 100, self.fq) self.irq_detect.init(Pin.OUT) time.sleep_ms(self.irq_timeout) self.irq_detect.value(1) # reverse op == 1 self.irq_detect.init(Pin.IN) self.irq_count += 1 self.irq_detflag = True # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy = False def buzzer_alarm_callback_rev(self, x): if self.irq_busy: return else: self.irq_busy = True if self.irq_detect.value() == 0: # reverse op == 0 self.sec_alarm(ntimes=10) self.irq_detect.init(Pin.OUT) time.sleep_ms(self.irq_timeout) self.irq_detect.value(1) # reverse op == 1 self.irq_detect.init(Pin.IN) self.irq_count += 1 self.irq_detflag = True # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy = False def led_callback(self, x): if self.irq_busy: return else: self.irq_busy = True if self.irq_detect.value() == 1: # reverse op == 0 self.led_blink(150, 3, 100) self.irq_detect.init(Pin.OUT) time.sleep_ms(self.irq_timeout) self.irq_detect.value(0) # reverse op == 1 self.irq_detect.init(Pin.IN) self.irq_count += 1 self.irq_detflag = True # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy = False def led_callback_rev(self, x): if self.irq_busy: return else: self.irq_busy = True if self.irq_detect.value() == 0: # reverse op == 0 self.led_blink(150, 3, 100) self.irq_detect.init(Pin.OUT) time.sleep_ms(self.irq_timeout) self.irq_detect.value(1) # reverse op == 1 self.irq_detect.init(Pin.IN) self.irq_count += 1 self.irq_detflag = True # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy = False def msg_callback(self, x): if self.irq_busy: return else: self.irq_busy = True if self.irq_detect.value() == 1: # reverse op == 0 print(self.irq_message) self.irq_detect.init(Pin.OUT) time.sleep_ms(self.irq_timeout) self.irq_detect.value(0) # reverse op == 1 self.irq_detect.init(Pin.IN) self.irq_count += 1 self.irq_detflag = True # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy = False def msg_callback_rev(self, x): if self.irq_busy: return else: self.irq_busy = True if self.irq_detect.value() == 0: # reverse op == 0 print(self.irq_message) self.irq_detect.init(Pin.OUT) time.sleep_ms(self.irq_timeout) self.irq_detect.value(1) # reverse op == 1 self.irq_detect.init(Pin.IN) self.irq_count += 1 self.irq_detflag = True # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy = False def sensor_callback(self, x): if self.irq_busy: return else: self.irq_busy = True if self.irq_detect.value() == 1: # reverse op == 0 print(self.irq_message) # returns array() self.sensor_vals[:] = self.read_data() self.irq_detect.init(Pin.OUT) time.sleep_ms(self.irq_timeout) self.irq_detect.value(0) # reverse op == 1 self.irq_detect.init(Pin.IN) self.irq_count += 1 self.irq_detflag = True # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy = False def sensor_soc_callback(self, x): if self.irq_busy: return else: self.irq_busy = True if self.irq_detect.value() == 1: # reverse op == 0 print(self.irq_message) self.cli_soc.sendall(self.read_data()) self.irq_detect.init(Pin.OUT) time.sleep_ms(self.irq_timeout) self.irq_detect.value(0) # reverse op == 1 self.irq_detect.init(Pin.IN) self.irq_count += 1 self.irq_detflag = True # butpress.init(Pin.IN, Pin.PULL_UP) self.irq_busy = False
pwm = PWM(0) pwm = PWM(0, freq=10000) pwm = PWM(0, duty=50) pwm = PWM(0, duty=50, freq=10000) print(pwm.duty() == 50) print(pwm.freq() == 10000) pwm.duty(35) print(pwm.duty() == 35) pwm.duty(200) print(pwm.duty() == 100) pwm.freq(1000) print(pwm.freq() == 1000) pwm.init(freq=5000) print(pwm.freq() == 5000) print(pwm.duty() == 100) pwm.init(duty=25) print(pwm.freq() == 5000) print(pwm.duty() == 25) pwm.init(duty=66, freq=8000) print(pwm.freq() == 8000) print(pwm.duty() == 66) pwm.duty(0)
ie = request.find( ' ', ib) #init address of the index with ib,then find ' ' Val = request[ib + 4:ie] #get the string of ib+4 to ie in the request print("Val =", Val) led.duty(int(Val) * 100) #set the duty of led conn.send(Val) #send data else: with open('Ajax_webCtrl.htm', 'r') as html: #open file 'webCtrl.htm' with readonly conn.sendall(html.read( )) #read data from 'webCtrl.htm',and send all of the data conn.sendall('\r\n') conn.close() #close file #print("Connection wth %s closed" % str(addr)) #Catch exceptions,stop program if interrupted accidentally in the 'try' try: led = PWM(Pin(2), freq=100) #create led object led.init() led.duty(0) connectWifi(SSID, PASSWORD) ajaxWebserv() except: if (s): s.close() led.deinit() wlan.disconnect() wlan.active(False)