import utime from machine import Pin class MTS102: """MTS102(三脚二档钮子开关)""" def __init__(self, pin, pull_down=False): """ :param pin: 引脚编号 :param pull_down: 引脚下拉电阻(断开为低电平,接通为高电平),默认为False。若使用下拉电阻,因钮子接通后断开可能存留电荷/漏电故需在引脚和GND并联1K~10K欧电阻 """ if not isinstance(pull_down, bool): raise TypeError("pull_down数据类型应为布尔") self.pull_down = pull_down # 尝试初始化引脚 try: self.pin = Pin( pin, Pin.IN, Pin.PULL_DOWN if self.pull_down else Pin.PULL_UP ) except Exception as exception: raise RuntimeError(f"初始化引脚发生异常,{str(exception)}") from exception # 初始化上一次检测时间 self._last_time = utime.ticks_ms() # 初始化上一次检测状态 self._last_state = self._get_state() def _get_state(self): """获取状态:0为断开,1为接通""" return self.pin.value() ^ (not self.pull_down) def _debounce(self): """去抖""" current_time = utime.ticks_ms() current_state = self._get_state() # 若当前与上一次检测间隔大于等于防抖时间则更新时间,又若状态不同则更新状态 if utime.ticks_diff(current_time, self._last_time) >= 20: if current_state != self._last_state: self._last_time = current_time self._last_state = current_state return self._last_state @property def switched(self): """是否接通""" return self._debounce() == 1 """ 使用示例 引脚0→LED→220R→GND 引脚1→MTS102→GND import utime from machine import Pin from utils.switch import MTS102 led = Pin(0, Pin.OUT) toggle = MTS102(pin=1) while True: if toggle.switched: led.on() else: led.off() utime.sleep_ms(200) """