class limit_switch(): def __init__(self, pin_number, pin_on_low_func, pin_on_high_func, pull='UP'): if pull == 'UP': self.switch_pin = Pin(pin_number, Pin.IN, Pin.PULL_UP) elif pull == 'DOWN': self.switch_pin = Pin(pin_number, Pin.IN, Pin.PULL_DOWN) elif pull == 'NONE': self.switch_pin = Pin(pin_number, Pin.IN) else: raise ValueError( "Not valid pull pin. Valid options are UP, DOWN and NONE") self.pin_on_low_func = pin_on_low_func self.pin_on_high_func = pin_on_high_func # Force pin to execute on init. This will detect if switch was engaged before program start self.change_pin_state(self.switch_pin) self.switch_pin.irq(self.change_pin_state, trigger=(Pin.IRQ_FALLING | Pin.IRQ_RISING)) def change_pin_state(self, pin): if pin() == 0: self.pin_on_low_func() elif pin() == 1: self.pin_on_high_func()
class hc_sr04_multi(object): def __init__(self, cs=Pin.cpu.A4, trigger=Pin.cpu.C0, echo=Pin.cpu.C1, timer=Timer(2), avg_window=1): self.__io = MCP23S08(cs=cs) self.__trigger = Pin(trigger, Pin.OUT_PP) self.__echo = Pin(echo, Pin.IN, pull=Pin.PULL_DOWN) self.__timer = timer self.__counter = 0 self.__window_len = avg_window self.__window = [] self.__trigger.high() self.__io.set_direction(0, 0) self.__io.set_direction(1, 0) self.__io.set_direction(2, 0) self.__io.set_direction(3, 0) self.__io.set_gpio(0, 0) self.__io.set_gpio(1, 0) self.__io.set_gpio(2, 0) self.__io.set_gpio(3, 0) self.select_sensor(3) def __echo_rising(self, p): self.__timer.counter(0) self.__echo.irq(handler=self.__echo_falling, trigger=Pin.IRQ_FALLING) #print(self.__distance((self.__counter * 20) / 65537)) #exit() def __echo_falling(self, p): #print("echo {}".format(self.__timer.counter())) self.__counter = self.__timer.counter() self.__echo.irq(trigger=0) def __timeout(self, t): t.deinit() #print("timeout") self.__counter = 16800000 def select_sensor(self, sensor): self.__io.set_gpio(0, 0) self.__io.set_gpio(1, 0) self.__io.set_gpio(2, 0) self.__io.set_gpio(3, 0) self.__io.set_gpio(sensor, 1) def duration(self, sensor): self.select_sensor(sensor) #time.sleep(20E-6) #print("Trigger: {}, Echo: {}".format(self.__trigger.value(), self.__echo.value())) #while(True): # pass self.__counter = 16800000 while (self.__counter == 16800000): self.__counter = 0 self.__trigger.low() time.sleep(3E-6) self.__trigger.high() time.sleep(20E-6) self.__trigger.low() self.__echo.irq(handler=self.__echo_rising, trigger=Pin.IRQ_RISING) time.sleep(450E-6) self.__timer.init(prescaler=0, period=16800000, callback=self.__timeout) self.__timer.counter(0) #self.__timer.init(freq=) while (self.__counter == 0): pass self.__timer.deinit() #self.__echo.irq(trigger=0) return (self.__counter * 0.2) / 16800 # ms def __distance(self, duration, temp_deg=20): return (duration * (331.5 + (0.6 * temp_deg))) / 2 # mm def distance(self, sensor, temp_deg=20): distance = self.__distance(self.duration(sensor), temp_deg) self.__window.insert(0, distance) self.__window = self.__window[0:self.__window_len] return (sum(self.__window) / len(self.__window))
led3.off() def allLightsOff_x8_Callback(pin): if not pinDebounce(pin): passRelay50_x1.value(startValue) passRelay80_x3.value(startValue) cylinderRetract50_x2.value(startValue) cylinderRetract80_x4.value(startValue) led1.off() led2.off() led3.off() # the lines bellow triggers the interupts (?) lightCurtain_x5.irq(trigger=Pin.IRQ_FALLING, handler=lightCurtain_x5_Callback) dutFinished_x6.irq(trigger=Pin.IRQ_FALLING, handler=dutFinished_x6_Callback) closeLid_x7.irq(trigger=Pin.IRQ_FALLING, handler=closeLid_x7_Callback) allLightsOff_x8.irq(trigger=Pin.IRQ_FALLING, handler=allLightsOff_x8_Callback) #switch.irq(trigger = Pin.IRQ_FALLING, handler = switch_Callback) # General functions used throughout the program # Returns the lids position. Returns: fullyClosed, closedNotLocked, fullyOpen, moving #def lidState(): # fullyClosed = 0 # closedNotLocked = 0 # fullyOpen = 0 # moving = 0 # for _ in range(10): # if lidStateSimple() == "fullyClosed":
if desired_moisture_level < MIN_MOISTURE: desired_moisture_level = MIN_MOISTURE write_moisture_level(desired_moisture_level) def left_button_pushed(p): button_pushed(LEFT) print("Left button pushed") def right_button_pushed(p): button_pushed(RIGHT) print("Right button pushed") water_monitor.irq(trigger=Pin.IRQ_RISING, handler=water_incrementer) left_button.irq(trigger=Pin.IRQ_FALLING, handler=left_button_pushed) right_button.irq(trigger=Pin.IRQ_FALLING, handler=right_button_pushed) def calculate_moisture_level(input_level): numerator = input_level - SOAKING_DIRT denominator = DRY_DIRT - SOAKING_DIRT level = 1.0 - (numerator * 1.0) / denominator return level def write_moisture_level(level): f = open(FILE_NAME, 'w')
class Lora(): def __init__(self, AUXPin='Y3', MD0Pin='Y4', baudrate=9600): #M0输入,M1输出 self.m = Pin('Y3', Pin.IN) self.M1 = Pin(MD0Pin, Pin.OUT_PP) self.m.irq(handler=self.__saved_data, trigger=Pin.IRQ_FALLING) #设置中断函数 #根据模块手册,接收或发送数据时aux呈现高电平,发送接收完成时电平拉低 #设置引脚中断,当电平变低时__save_data函数被调用,__save_data被调用时数据接收完毕 self.count = 0 #中断回掉函数调用计数 self.M1.low() self.u4 = UART(6, baudrate) self.u4.init(baudrate, bits=8, parity=None, stop=1) def __saved_data(self, b): self.count = 1 + self.count def md0low(self): self.M1.low() def md0high(self): self.M1.high() def enterConfig(self): #进入设置模式,md0拉高,波特率设为115200 self.M1.high() self.u4 = UART(6, 115200) self.u4.init(115200, bits=8, parity=None, stop=1) def exitConfig(self, baudrate=9600): #退出设置模式,md0拉低,更改波特率 self.M1.low() self.u4 = UART(6, baudrate) self.u4.init(baudrate, bits=8, parity=None, stop=1) def send(self, data): return self.u4.write(data) def recv(self, cycle=100): self.count = 0 save_data = b'' #收到的数据 while True: if self.count == 1: #__save_data每调用一次,count+1 if self.u4.any() > 0: save_data = save_data + self.u4.read() return save_data.decode('utf-8') if self.u4.any() > 12: save_data = save_data + self.u4.read() pyb.delay(cycle) #循环间隔100ms def getb(self): #获取二进制数据 len = self.u4.any() if len > 0: recv = self.u4.read() return recv else: return -1 def get(self): len = self.u4.any() if len > 0: recv = self.u4.read().decode('utf-8') return recv else: return -1 # 串口对应GPIO # UART(4) is on XA: (TX, RX) = (X1, X2) = (PA0, PA1) # UART(1) is on XB: (TX, RX) = (X9, X10) = (PB6, PB7) # UART(6) is on YA: (TX, RX) = (Y1, Y2) = (PC6, PC7) # UART(3) is on YB: (TX, RX) = (Y9, Y10) = (PB10, PB11) # UART(2) is on: (TX, RX) = (X3, X4) = (PA2, PA3)
from pyb import Pin #Set pin to alterate function #a3 = Pin(Pin.board.GPA3, Pin.ALT, alt = Pin.AF_PA3_KPI0_SI0) #print(a3) #For GPIO output #a3 = Pin(Pin.board.GPA3, Pin.OUT) #print(a3) #a3.value(1) count = 0 def pa3_callback(pin): count = count + 1 #For GPIO input a3 = Pin(Pin.board.GPA3, Pin.IN) a3.irq(handler=pa3_callback, trigger=Pin.IRQ_RISING) while True: print(count) pyb.delay(2000)
led3.off() def allLightsOff_x8_Callback(pin): if not pinDebounce(pin): passRelay50_x1.value(startValue) passRelay80_x3.value(startValue) cylinderRetract50_x2.value(startValue) cylinderRetract80_x4.value(startValue) led1.off() led2.off() led3.off() # the lines bellow triggers the interupts (?) lightCurtain_x5.irq(trigger = Pin.IRQ_FALLING, handler = lightCurtain_x5_Callback) #dutFinished_x6.irq(trigger = Pin.IRQ_FALLING, handler = dutFinished_x6_Callback) #closeLid_x7.irq(trigger = Pin.IRQ_FALLING, handler = closeLid_x7_Callback) #allLightsOff_x8.irq(trigger = Pin.IRQ_FALLING, handler = allLightsOff_x8_Callback) #switch.irq(trigger = Pin.IRQ_FALLING, handler = switch_Callback) # General functions used throughout the program # Returns the lids position. Returns: fullyClosed, closedNotLocked, fullyOpen, moving
class Stepper(object): ''' Counts signals received on a pin and counts them. Also rises an event on a concrete step. ''' def __init__(self, pin, pullMode=None, stepLevel=1): ''' Constructor @param pin: Pin where the signal is received @param pullMode: (default: None) specifies if the pin has a (weak) pull resistor attached. @param stepLevel: value on the pin indicating a step (values: 0, 1) @see http://docs.micropython.org/en/latest/library/machine.Pin.html?highlight=pin#machine.Pin ''' self._pin = Pin(pin, Pin.IN, pullMode) self._state = 0 self._counter = 0 self._stepTrigger = 0 assert stepLevel in (0, 1) self._stepLevel = stepLevel self._callback = None self._callbackArgs = None def setCallback(self, callback, args=None): ''' Set the callback when the trigger step is reached @param callback: Callback method with at least one parameter: this object itself @param args: (optional) additional object passed to the callback @return: self ''' self._callback = callback self._callbackArgs = args return self def setStepTrigger(self, stepTrigger): ''' Set the step trigger @param stepTrigger: Positive integer. On this step the callback will be called @return: self ''' self._stepTrigger = stepTrigger return self def resetCount(self): ''' Set the step counter to zero @return: self ''' self._counter = 0 return self def startCounting(self): ''' Starts to count steps @return: self ''' self._state = self._pin.value() self._pin.irq( self._onStep, Pin.IRQ_RISING if self._stepLevel == 1 else Pin.IRQ_FALLING) return self def stopCounting(self): ''' Stops to count steps ''' self._pin.irq(None) def steps(self): ''' @return: Number of steps after starting or reset ''' return self._counter def _execCallback(self): ''' Executes the callback ''' if self._callback: if self._callbackArgs: self._callback(self, self._callbackArgs) else: self._callback(self) def _onStep(self, pin): ''' Counts steps. It's used on the pin's IRQ @param pin: The pin which received the signal ''' if pin.value() != self._state: self._state = pin.value() if self._state == self._stepLevel: self._counter += 1 if self._counter == self._stepTrigger: schedule(Stepper._execCallback, self)
class IRRC(object): class Channel(object): CHANNEL_1 = const(0xFC) CHANNEL_2 = const(0x3C) CHANNEL_3 = const(0xCC) CHANNEL_4 = const(0x0C) CHANNEL_5 = const(0xF0) CHANNEL_6 = const(0x30) CHANNEL_7 = const(0xC0) CHANNEL_8 = const(0x00) class Key(object): UP = const(0x1FC3) DOWN = const(0x1F) LEFT = const(0x07) RIGHT = const(0x73) UP_AND_LEFT_KEY = const(0x7C3) UP_AND_RIGHT_KEY = const(0x7F) DOWN_AND_LEFT_KEY = const(0x70F) DOWN_AND_RIGHT_KEY = const(0x1CF) F1 = const(0x7CF) F2 = const(0x1C3F) F3 = const(0x7F3) F4 = const(0x1CCF) F5 = const(0x1F0F) F6 = const(0x703) OFF = const(0x733) _TIMEOUT = const(500) _SHIFT = const(8) def __init__(self, pin: Pin, channel: int): self._CHANNELS = (self.Channel.CHANNEL_1, self.Channel.CHANNEL_2, self.Channel.CHANNEL_3, self.Channel.CHANNEL_4, self.Channel.CHANNEL_5, self.Channel.CHANNEL_6, self.Channel.CHANNEL_7, self.Channel.CHANNEL_8) self._KEYS = (self.Key.UP, self.Key.DOWN, self.Key.LEFT, self.Key.RIGHT, self.Key.UP_AND_LEFT_KEY, self.Key.UP_AND_RIGHT_KEY, self.Key.DOWN_AND_LEFT_KEY, self.Key.DOWN_AND_RIGHT_KEY, self.Key.F1, self.Key.F2, self.Key.F3, self.Key.F4, self.Key.F5, self.Key.F6, self.Key.OFF) self._pin = Pin(pin, mode=Pin.IN, pull=Pin.PULL_UP) self.channel = channel self._button_id = 0 self._impulse = True self._res = 0 self._state = 0 self._timeout_mark = 0 self._buf = 0 self._time = micros() self._pin.irq(lambda p: self._update()) @property def channel(self) -> int: return self._channel @channel.setter def channel(self, channel: int): if channel in self._CHANNELS: self._channel = channel else: raise ValueError("`channel` must be the one of IRRC.Channel") @property def _res(self): return self._res @_res.setter def _res(self, _res): self._res = _res & (uctypes.UINT32 - 1) @property def _buf(self): return self._buf @_buf.setter def _buf(self, _buf): self._buf = _buf & (uctypes.UINT8 - 1) @property def _button_id(self): return self._button_id @_button_id.setter def _button_id(self, _button_id): self._button_id = _button_id & (uctypes.UINT32 - 1) @property def _state(self): return self._state @_state.setter def _state(self, _state): self._state = _state & 0x7F def _update(self): diff_time = elapsed_micros(self._time) self._time += diff_time self._buf = diff_time del diff_time if self._buf % 200 > 101: self._buf = (self._buf // 200) + 1 else: self._buf //= 200 if self._buf == 0: self._buf = 1 if self._state == 0: if not self._impulse: self._state += 1 self._res = 0 << self._buf else: if self._impulse: self._res <<= self._buf for i in range(self._buf): self._res |= 1 << i else: self._res <<= self._buf if (self._res & 0x7F) == 0x38: self._buf = 1 for i in range(1, self._SHIFT): self._buf = (self._buf << 1) + 1 channel_buf = ((self._res >> 6) & self._buf) & 0x7F # channel_buf is byte if channel_buf == self._channel: self._button_id = self._res >> (6 + self._SHIFT) while not (self._button_id & 1): self._button_id >>= 1 self._timeout_mark = millis() self._state = 0 self._res = 0 self._impulse = not self._impulse def pressed(self, key: int) -> bool: if key in self._KEYS: pass else: raise ValueError("`key` must be the one of IRRC.KEY") if (millis() - self._timeout_mark >= self._TIMEOUT): self._button_id = self.Key.OFF if (key == self._button_id): return True return False
class Button(object): ''' This button can handle short and long press ''' def __init__(self, pin, timerId=6, thresholdTime=1000, lowOnPress=False): ''' Constructor @param pin: Pin object where the button is @param timerId: (default=6) Timer to determine the long press @param thresholdTime: Waiting time to determine a long press as milliseconds @param lowOnPress: Indicates whether the value is 0 when the button is pressed (pull-down) The user (blue) button on the NUCLEO-L476RG board must have this parameter as True, but for the case of the NUCLEO-F767ZI board, this parameter must be False ''' self._pin = Pin(pin) self._pin.init(mode=Pin.IN) self._pin.irq(handler=self._onPinIrq) self._lowOnPress = lowOnPress self._thresholdTime = thresholdTime self._pressTime = 0 self._timer = Timer(timerId) self._shortPressHandler = None self._longPressHandler = None self._isTimeout = False def _onPinIrq(self, _): self._pin.irq(handler=None) self._timer.callback(None) self._timer.deinit() #debounce signal sleep_ms(50) if self._pin.value() == (1 if self._lowOnPress else 0): if not self._isTimeout: schedule(self._shortPressHandler, self) else: self._isTimeout = False self._timer.init(freq=1000 / self._thresholdTime, callback=self._onTimeout) self._pin.irq(handler=self._onPinIrq) def _onTimeout(self, t): t.deinit() self._isTimeout = True schedule(self._longPressHandler, self) def setShortPressHandler(self, handler): ''' Sets the handler for short press ''' self._shortPressHandler = handler return self def setLongPressHandler(self, handler): ''' Sets the handler for long press ''' self._longPressHandler = handler return self def cleanup(self): ''' Releases resources Deinits the timer and removes handler for the pin's IRQ ''' self._timer.deinit() self._pin.irq(handler=None)