Add button handler
This commit is contained in:
45
esp32-wifi/button_handler.py
Normal file
45
esp32-wifi/button_handler.py
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import _thread
|
||||||
|
from typing import Callable
|
||||||
|
from machine import Pin
|
||||||
|
import time
|
||||||
|
|
||||||
|
class ButtonHandler:
|
||||||
|
def __init__(self, pin : int, action : Callable[[], None]):
|
||||||
|
self.button = Pin(pin, Pin.IN, Pin.PULL_UP)
|
||||||
|
self.action = action
|
||||||
|
self._pressed = False
|
||||||
|
_thread.start_new_thread(self._listen, ())
|
||||||
|
|
||||||
|
def _listen(self):
|
||||||
|
while True:
|
||||||
|
if not self.button.value():
|
||||||
|
if not self._pressed:
|
||||||
|
self._pressed = True
|
||||||
|
self.action()
|
||||||
|
else:
|
||||||
|
self._pressed = False
|
||||||
|
time.sleep(0.1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
def on_press():
|
||||||
|
print("Button action triggered")
|
||||||
|
|
||||||
|
btn = ButtonHandler(14, on_press)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
|
"""# Track button state
|
||||||
|
button_pressed = False
|
||||||
|
|
||||||
|
while True:
|
||||||
|
if not button.value(): # Button pressed (active low)
|
||||||
|
if not button_pressed:
|
||||||
|
button_pressed = True
|
||||||
|
print("Button pressed! Action triggered.") # Replace with your action
|
||||||
|
else:
|
||||||
|
button_pressed = False # Reset when button released
|
||||||
|
|
||||||
|
time.sleep(0.01) # Small debounce delay"""
|
||||||
Reference in New Issue
Block a user