def __init__(self, pin, press_cmd=None, hold_cmd=None, release_cmd=None, threshold=400, hold_time=2, hold_repeat_time=None, freq=10): if isinstance(pin, int): pin = Pin(pin) else: pin.init() self.tp = TouchPadBase(pin) self.press_cmd = press_cmd self.hold_cmd = hold_cmd self.release_cmd = release_cmd self.hold_time = int(hold_time * 1000) if hold_repeat_time is not None: self.hold_repeat_time_diff = int((hold_repeat_time * 1000) - self.hold_time) else: self.hold_repeat_time_diff = None self.threshold = threshold self.freq = freq self.is_active = self.tp.read() < self.threshold if self.is_active: self.pressed_timestamp = time.ticks_ms() else: self.pressed_timestamp = None loop = asyncio.get_event_loop() loop.create_task(self._handle_touch())
def led_on_even_minute(): print("led_on_even_minute(), time: {}".format(utime.localtime())) led_pin = Pin(BUILD_IN_LED_PIN, Pin.OUT) # disable pin hold to allow to change it led_pin.init(Pin.OUT, pull=None) if utime.localtime()[4] % 2 == 0: led_pin.on() else: led_pin.off() # enable pin hold to keep the output state during deep sleep led_pin.init(Pin.OUT, pull=Pin.PULL_HOLD) # Set and increment 'value' to limit how many times this function is executed. # 'value' is stored in the array sl.rtc_memory_bytes what is saved/restored # by sleepscheduler before/after deep sleep. if len(sl.rtc_memory_bytes) == 0: print("led_on_even_minute(): rtc_memory_bytes empty") value = 1 sl.rtc_memory_bytes.extend(value.to_bytes(2, 'big')) else: value = int.from_bytes(sl.rtc_memory_bytes[0:2], 'big') value = value + 1 sl.rtc_memory_bytes[0:2] = value.to_bytes(2, 'big') # stop executing led_on_even_minute() when 'value' reaches 3 if value >= 3: print("finish led_on_even_minute()") sl.remove_all(__name__, led_on_even_minute)
def __init__(self, name, pin, *args, report_high="on", report_low="off", pullup=True, threshold=0, on_change=None, report_change=True, filter=None): if len(args) > 0: report_high = args[0] if len(args) > 1: report_low = args[1] Device.__init__(self, name, pin, value_map={ True: report_high, False: report_low }, on_change=on_change, report_change=report_change, filter=filter) if pullup: pin.init(Pin.IN, Pin.PULL_UP) else: pin.init(Pin.IN) try: Pin.init(Pin.OPEN_DRAIN) except: pass self.threshold = threshold + 1 self.debouncer = self.port() * self.threshold
class Button: """ A button that does something when pushed. Usage: def callback(pin): print("Pushed: %s" % pin) button = Button(pin=27, on_push=callback) When pushed: "Pushed: Pin(27) mode=IN, PULL_UP, irq=IRQ_FALLING, debounce=0, actTime=0" """ def __init__(self, pin, handler=None, trigger=Pin.IRQ_FALLING, *args, **kwargs): self.callback = handler self.pin = Pin( pin, Pin.IN, Pin.PULL_UP, handler=self.push_handler, trigger=trigger, *args, **kwargs ) def push_handler(self, pin): if not self.callback: return self.callback(pin) def disable(self): self.pin.init(handler=None, trigger=Pin.IRQ_DISABLE) def update(self, *args, **kwargs): self.pin.init(**kwargs)
class IRrec(): #count = 0 def __init__(self, pnum): self.ir = Pin(pnum, Pin.IN) self.pnum = pnum self.ntime = 0 self.otime = 0 self.diff = 0 self.ledge = 0 self.signal = ['L Time'] self.tu = ticks_us self.td = ticks_diff self.start() def start(self): self.otime = self.tu() self.ir.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self.timeseq_isr) def stop(self): self.ir.init(mode=Pin.OUT, value=1) def print(self): print('\n'.join(self.signal)) def timeseq_isr(self, p): #IRrec.count += 1 #irq = disable_irq() self.ntime = self.tu() self.diff = self.td(self.ntime, self.otime) self.ledge = self.ir.value() self.signal.append('{0} {1}'.format(str(self.ledge), str(self.diff))) self.otime = self.ntime
class Button(): """Wrap a button to make it easier to use :param pin: The pin the button is attached to :param invert: Is the pin inverted """ def __init__(self, pin, invert=False): self._pin = Pin(pin) self._pin.init(Pin.IN) self._invert = invert @property def down(self): """Is the pin down :return: Pin is down """ return self._pin.value() == 0 if self._invert else self._pin == 1 @property def up(self): """Is the pin up :return: Pin is up """ return self._pin.value() == 1 if self._invert else self._pin == 0
class D_Pin(Pin): def __init__(self, pin): self.pin = pin self.pwm = None self.io = Pin(pin) def write_digital(self, v): if self.pwm is not None: self.pwm.deinit() self.pwm = None self.io.init(Pin.OUT) # set pin as output self.io.value(v) def read_digital(self): if self.pwm is not None: self.pwm.deinit() self.pwm = None self.io.init(Pin.IN) # set pin as input return self.io.value() def write_analog(self, value): if self.pwm is None: self.pwm = PWM(self.io, freq=1000) #self.pwm.freq(10000) self.pwm.duty(value) def time_pules_in(level, timeout): if self.io is None: self.io = super()
class Switch: def __init__(self, pin_no, name): self._state = 0 self.value = 0 self.pin = Pin(pin_no) self.name = name self._pressed = False def setup(self): self.pin.init(mode=Pin.IN, pull=Pin.PULL_UP) def output(self): return self.name if self.value else '.' def update_internal_state(self): bit = self.pin.value() self._state = ((self._state << 1) | bit) & 0xfff if self._state == 0x000: self.value = True self._pressed = True elif self._state == 0xfff: self.value = False def pressed(self): return True if self.value else False def released(self): if self._pressed and not self.value: self._pressed = False return True return False
def init(): global source, sensor, init_done source = Pin(22) sensor = Pin(4) sensor.init(sensor.IN) source.init(source.OUT) source.value(100) # why this magic number? init_done = True
def temp_method(*args, **kwargs): print("Pin: {}".format(pin_nr)) print("Args:{}".format(args)) print("Kwargs: {}".format(kwargs)) p = Pin(pin_nr) if len(args) > 0: p.init(args[0]) return p
class PIR(): # モーションセンサークラス def __init__(self, handler=None): self.pin = Pin(units.PORTB[1], Pin.IN, handler=handler, trigger=(Pin.IRQ_RISING | Pin.IRQ_FALLING), debounce=100) def read(self): return self.pin.value() def deinit(self): self.pin.init(handler=None, trigger=Pin.IRQ_DISABLE)
class DHT: # pylint: disable=C1001,R0903 """ DHT DHT sensor (dht11, dht21,dht22) reader class for Pycom """ __dhttype = 0 def __init__(self, pin, sensor=0): self.__pin = Pin(pin, mode=Pin.OPEN_DRAIN, pull=Pin.PULL_UP) self.__dhttype = sensor self.__pin(1) utime.sleep(1.0) def read(self): """ read Reads data from DHT sensor """ # pull down to low self.__send_and_sleep(0, 0.019) data = pycom.pulses_get(self.__pin, 100) # pylint: disable=E1101 self.__pin.init(Pin.OPEN_DRAIN) self.__pin(1) bits = [] for a, b in data: if a == 1 and 18 <= b <= 28: bits.append(0) if a == 1 and 65 <= b <= 75: bits.append(1) if len(bits) != 40: return DHTResult(DHTResult.ERR_MISSING_DATA, 0, 0) # we have the bits, calculate bytes the_bytes = bits_to_bytes(bits) # calculate checksum and check checksum = calculate_checksum(the_bytes) if the_bytes[4] != checksum: return DHTResult(DHTResult.ERR_CRC, 0, 0) # ok, we have valid data, return it [int_rh, dec_rh, int_t, dec_t, csum] = the_bytes # pylint: disable=E0632,W0612 if self.__dhttype == 0: #dht11 rh = int_rh #dht11 20% ~ 90% t = int_t #dht11 0..50 deg C else: #dht21,dht22 rh = ((int_rh * 256) + dec_rh)/10 t = (((int_t & 0x7F) * 256) + dec_t)/10 if (int_t & 0x80) != 0: t = -t return DHTResult(DHTResult.ERR_NO_ERROR, t, rh) def __send_and_sleep(self, output, mysleep): self.__pin(output) utime.sleep(mysleep)
def switch_led(led_on): led_pin = Pin(BUILD_IN_LED_PIN, Pin.OUT) # disable pin hold to allow to change it led_pin.init(Pin.OUT, pull=None) if led_on: led_pin.on() else: led_pin.off() # enable pin hold to keep the output state during deep sleep led_pin.init(Pin.OUT, pull=Pin.PULL_HOLD)
def test(): init() # set up button from machine import Pin button = Pin(0) button.init(Pin.IN, Pin.PULL_UP) butstate = button.value() while True: if button.value() != butstate: butstate = button.value() if butstate == 0: netscan()
def set_pins(values): try: for i in range(1, len(values), 2): # i = 1, 3, 5... upto n pin, val = values[i - 1], values[i] print("set_pin", pin, val) gpioPin = Pin(pin) gpioPin.init(Pin.OUT) gpioPin.value(val) return b"@K" except Exception as oops: print("Error in set_pins", oops) return b"@E"
class device: def __init__(self, pin): self.temperature = None self.humidity = None self.status = "NoConversionStartedError" self.pin = Pin(pin, mode=Pin.OPEN_DRAIN) def trigger(self): self.pin.init(Pin.OUT) self.pin(1) time.sleep(2) # enforce two second read interval self.pin(0) # send start signal (1ms low). time.sleep_ms(20) pulses = pycom.pulses_get(self.pin, 100) # capture communication time.sleep(2) self.pin.init(Pin.OPEN_DRAIN) if len(pulses) != 82: # 40 data bit plus one acknowledge expected self.status = "ReadError - received {} only pulses".format(len(pulses)) return False bits = [] for level, duration in pulses[1:]: if level == 1: bits.append(0 if duration < 50 else 1) # convert to 0 or 1 data = [] for n in range(5): byte = 0 for i in range(8): # shift 8 bits into a byte byte <<= 1 byte += bits[n * 8 + i] data.append(byte) int_rh, dec_rh, int_t, dec_t, csum = data print(data) if ((int_rh + dec_rh + int_t + dec_t) & 0xFF) != csum: self.status = "Checksum Error" return False self.humidity = (int_rh +(dec_rh*0.1)) self.temperature = (int_t + dec_t*0.1) if (int_t & 0x80) > 0: self.temperature *= -1 self.status = "OK" return True
def led_on_even_minute(): print("led_on_even_minute(), time: {}".format(utime.localtime())) led_pin = Pin(BUILD_IN_LED_PIN, Pin.OUT) # disable pin hold to allow to change it led_pin.init(Pin.OUT, pull=None) if utime.localtime()[4] % 2 == 0: led_pin.on() else: led_pin.off() # enable pin hold to keep the output state during deep sleep led_pin.init(Pin.OUT, pull=Pin.PULL_HOLD)
def _signal(self): """ flashes the LED on an ESP8266 module. """ self._current_state['params']['signal'] = self._shadow_state['state'][ 'desired']['signal'] from utime import sleep_ms from machine import Pin led = Pin(2, Pin.OUT, value=0) for _ in range(self._current_state['params']['signal']): led.init(Pin.OUT) sleep_ms(300) led.init(Pin.IN) sleep_ms(300) return "done: signaled {} times".format( self._current_state['params']['signal'])
def __init__(self): self.spi = SPI(1, baudrate=20000000, bits=8, polarity=0, phase=0, sck=Pin(18), mosi=Pin(23), miso=Pin(5)) self.spi.init() cs = Pin(25) dc = Pin(27) rst = Pin(0) busy = Pin(13) cs.init(cs.OUT, value=1) dc.init(dc.OUT, value=0) rst.init(rst.OUT, value=0) busy.init(busy.IN) self.buffer = bytearray(EPD_WIDTH // 8 * EPD_HEIGHT) self.display = display.Display(self.buffer, self.spi, 128, 296, rst=rst, dc=dc, cs=cs, busy=busy, rotation=self.default_rotation, partial=True, invert=self.default_inverted, font=self.default_font, ) self.display.init()
class PIR(): # 1 OUT def __init__(self, port=PORTB): self.pin = Pin(PORTB[1], Pin.IN) self.cb = None def callback(self, cb): self.cb = cb self.pin.init(handler=self._irq_cb, trigger=(Pin.IRQ_RISING | Pin.IRQ_FALLING)) def _irq_cb(self, pin): self.cb(pin.value()) def read(self): return self.pin.value()
def __init__(self, reed_pin: machine.Pin, tyre_circumference: float): """ Initialise the reed switch speed sensor. :param reed_pin: The pin that the reed switch is attached to. :param tyre_circumference: Circumference of the tyre the reed switch measures. """ self.tyre_circumference = tyre_circumference self.last_trigger_time = time.ticks_us() self.current_speed = 0 self.distance_travelled = 0 # Configure reed_pin as an input pulled up internally, and set up reed_callback # to be called whenever pin is driven low. reed_pin.init(mode=machine.Pin.IN, pull=machine.Pin.PULL_UP) reed_pin.irq(trigger=machine.Pin.IRQ_FALLING, handler=self.reed_callback)
class GroveUltrasonic(object): def __init__(self, pin): self.dio = Pin(pin) def value(self): dt=-1 while dt<0: self.dio.init(Pin.OUT) self.dio.value(0) utime.sleep_us(2) self.dio.value(1) utime.sleep_us(10) self.dio.value(0) self.dio.init(Pin.IN) dt = time_pulse_us(self.dio, 1, 100000) return (dt / 29 / 2) # cm
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)
class Buzz(object): def __init__(self, pin = 16): self.pin = pin self.io = Pin(self.pin) self.io.value(1) self.isOn = False def on(self, freq = 500): if self.isOn == False: self.pwm = PWM(self.io, freq, 512) self.isOn = True def off(self): if self.isOn == True: self.pwm.deinit() self.io.init(self.pin, Pin.OUT) self.io.value(1) self.isOn = False
class Ir: portMethod = unit.PORT0 | unit.PORT1 def __init__(self, port): self.tx = PWM(port[0], freq=38000, duty=0, timer=1) self.rx = Pin(port[1], Pin.IN) self.rx.init(Pin.IN) self.rx.irq(handler=self._irq_cb, trigger=Pin.IRQ_FALLING) self.rx_value = 0 self.times = 0 self.status = 0 self.tx_en = 0 self.duty = 0 self.time_num = peripheral.get_timer() if self.time_num == None: raise unit.Unit('ir application time fail') self.timer = Timer(self.time_num) self.timer.init(period=50, mode=self.timer.PERIODIC, callback=self._update) def _irq_cb(self, pin): self.times = 0 def _update(self, arg): if self.tx_en: self.duty = 0 if self.duty else 10 else: self.duty = 0 self.tx.duty(self.duty) self.times += 1 def rxStatus(self): return 1 if self.times < 5 else 0 def txOn(self): self.tx_en = 1 def txOff(self): self.tx_en = 0 def deinit(self): self.timer.deinit() if self.time_num is not None: peripheral.free_timer(self.time_num) self.rx.deinit()
class IRrec(): def __init__(self, pin): self.pin = pin self.ir = Pin(self.pin, Pin.IN) self.us = ticks_us self.diff = ticks_diff # self.ltime=0 self.times = [] self.values = [] self.start() def start(self): # self.ltime=self.us() # self.ir.irq(trigger=Pin.IRQ_RISING, handler=self.timeseq_rising) # self.ir.irq(trigger=Pin.IRQ_FALLING, handler=self.timeseq_falling) self.ir.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self.timeseq_irq) def stop(self): self.ir.init(self.pin, Pin.OUT) def timeseq_irq(self, p): self.values.append(1 - p.value()) self.times.append(self.us()) # def timeseq_rising(self, p): # self.value.append(1) # self.times.append(self.us()) # def timeseq_falling(self, p): # self.value.append(0) # self.times.append(self.us()) def process(self): for i in range(len(self.values) - 1): self.times[i] = self.diff(self.times[i + 1], self.times[i]) self.times[len(self.values) - 1] = 0 def print(self): print('n Signal Duration') print('\n'.join([ str(i) + ' ' + str(self.values[i]) + ' ' + str(self.times[i]) for i in range(len(self.times)) ]))
class RotaryIRQ(Rotary): """Start""" def __init__( self, pin_num_clk, pin_num_dt, min_val=0, max_val=10, reverse=False, range_mode=Rotary.RANGE_UNBOUNDED, pull_up=False ): super().__init__(min_val, max_val, reverse, range_mode) if pull_up: self._pin_clk = Pin(pin_num_clk, Pin.IN, Pin.PULL_UP) self._pin_dt = Pin(pin_num_dt, Pin.IN, Pin.PULL_UP) else: self._pin_clk = Pin(pin_num_clk, Pin.IN) self._pin_dt = Pin(pin_num_dt, Pin.IN) self._enable_clk_irq(self._process_rotary_pins) self._enable_dt_irq(self._process_rotary_pins) def _enable_clk_irq(self, callback=None): # self._pin_clk.init(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=callback) self._pin_clk.init(trigger=Pin.IRQ_ANYEDGE, handler=callback) def _enable_dt_irq(self, callback=None): # self._pin_dt.init(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=callback) self._pin_dt.init(trigger=Pin.IRQ_ANYEDGE, handler=callback) def _disable_clk_irq(self): self._pin_clk.init(handler=None) def _disable_dt_irq(self): self._pin_dt.init(handler=None) def _hal_get_clk_value(self): return self._pin_clk.value() def _hal_get_dt_value(self): return self._pin_dt.value() def _hal_enable_irq(self): self._enable_clk_irq(self._process_rotary_pins) self._enable_dt_irq(self._process_rotary_pins) def _hal_disable_irq(self): self._disable_clk_irq() self._disable_dt_irq() def _hal_close(self): self._hal_disable_irq()
class Ultrasonic: """HC-SR04 ultrasonic ranging module class.""" _dist = 0 def __init__(self, trig_Pin, echo_Pin): """Initialize Input(echo) and Output(trig) Pins.""" ''' PePO: adopted from jpedrodias: https://forum.micropython.org/viewtopic.php?t=2436&start=20 self._trig = trig_Pin self._echo = echo_Pin #''' self._trig = Pin(trig_Pin) self._echo = Pin(echo_Pin) self._trig.init(Pin.OUT) self._echo.init(Pin.IN) self._sound_speed = 340 # m/s self._dist = 0 def _pulse(self): """Trigger ultrasonic module with 10us pulse.""" self._trig.value(1) sleep_us(10) self._trig.value(0) def distance(self): """Measure pulse length and return calculated distance [m].""" self._pulse() #PePo: pulse_width_s = time_pulse_us(self._echo, Pin.high) / 1000000 pulse_width_s = time_pulse_us(self._echo, 1) / 1000000 self._dist = (pulse_width_s / 2) * self._sound_speed return self._dist def calibration(self, known_dist_m): """Calibrate speed of sound.""" self._sound_speed = known_dist_m / self.distance() * self._sound_speed print("Speed of sound was successfully calibrated! \n" + "Current value: " + str(self._sound_speed) + " m/s") # 2017-1014 PePo added as helper def distance_in_cm(self): """return calculated distance [cm].""" # 2017-1022 do not measure distance again #dist_m = self.distance() return self._dist * 100
class WioLTE: """The WioLTE class to control Wio LTE on-board functions.""" def __init__(self): self.__comm = None self.__pin_grove_power = Pin('GRO_POWR') def initialize(self): """Initialize Wio LTE board.""" self.__pin_grove_power.init(Pin.OUT) self.__pin_grove_power.off() def get_comm(self): """Gets communication module object.""" if self.__comm is None: self.__comm = LTEModule() return self.__comm def set_grove_power(self, turn_on): """Turn on or off the power supply of Grove connectors.""" self.__pin_grove_power.value(turn_on)
def test(listen_ip, dest_ip): import socket # we can open the server on all network interfaces or only one defined by a non-zero IP listen_addr = socket.getaddrinfo(listen_ip, 473)[0][-1] init(listen_addr) # set up button from machine import Pin button = Pin(0) button.init(Pin.IN, Pin.PULL_UP) butstate = button.value() while True: if button.value() != butstate: butstate = button.value() if butstate == 0: # technically we can pick a different destination IP address each time dest_addr = socket.getaddrinfo(dest_ip, 473)[0][-1] msg_send(dest_addr, 'pressed') msg, frm = msg_check() if len(msg) > 0: print('received: ', msg)
from machine import Pin import pyb import onewire import onewireslave import time import os import ubinascii successled = pyb.LED(4) warnled = pyb.LED(3) shortpin = Pin('X12', mode=Pin.OUT) shortpin.value(1) toggleread = Pin('Y6', mode=Pin.OUT) toggleread.value(0) toggleread.init(Pin.IN) if 1: print("Write mode") ows = onewireslave.OneWireSlave(Pin('Y5'), [0x01, 0x19, 0x76, 0x60, 0x09, 0x00, 0x00, 0x8e]) ows.waitForRequest(False) else: print("Read mode") # create a OneWire bus on GPIO12 ow = onewire.OneWire(Pin('Y5')) while True: roms = '' while not roms: try: roms = ow.scan()
pin = Pin(pin_map[0], mode=Pin.OPEN_DRAIN, pull=Pin.PULL_UP) pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_DOWN) pin = Pin(pin_map[0], mode=Pin.OUT, pull=None) pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP) pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.MED_POWER) pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) pin = Pin(pin_map[0], mode=Pin.OUT, drive=pin.LOW_POWER) pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_DOWN) pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP) pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP) test_pin_af() # try the entire af range on all pins # test pin init and printing pin = Pin(pin_map[0]) pin.init(mode=Pin.IN) print(pin) pin.init(Pin.IN, Pin.PULL_DOWN) print(pin) pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) print(pin) pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) print(pin) # test value in OUT mode pin = Pin(pin_map[0], mode=Pin.OUT) pin.value(0) pin.toggle() # test toggle print(pin()) pin.toggle() # test toggle again print(pin())
def lo_power(): from machine import Pin, deepsleep for pin in dir(Pin.board): p = Pin(pin) p.init(Pin.IN, pull=Pin.PULL_DOWN, alt=-1) deepsleep()