MicroPython/RP2350ZERO/utils/switch.py

74 lines
2.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import utime
from machine import Pin
class MTS102:
"""MTS102三脚二档钮子开关"""
def __init__(self, pin, pull_down=False):
"""
:param pin: 引脚编号
:param pull_down: 引脚下拉电阻断开为低电平接通为高电平默认为False。若使用下拉电阻因钮子接通后断开可能存留电荷/漏电故需在引脚和GND并联1K10K欧电阻
"""
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)
"""