Add mute and input switching button controls

This commit is contained in:
Correl Roush 2023-05-28 13:04:43 -04:00
parent 181363a52d
commit 554d702279
2 changed files with 98 additions and 2 deletions

84
button.py Normal file
View File

@ -0,0 +1,84 @@
import utime
from machine import Pin
class Button:
DEBOUNCE_MS = 50
DOUBLECLICK_MS = 400
HOLD_MS = 1000
def __init__(self, pin: Pin) -> None:
self._pin = pin
self._pressed = False
self._clicked = False
self._doubleclicked = False
self._held = False
self._debounce = 0
self._hold = 0
self._doubleclick = 0
if self._pin():
self._debounce = utime.ticks_ms()
def update(self) -> None:
now = utime.ticks_ms()
if self._pin():
if self._debounce and now - self._debounce >= self.DEBOUNCE_MS:
self._debounce = 0
self._pressed = True
self._hold = now
elif not self._pressed and not self._debounce:
self._debounce = now
elif self._hold and now - self._hold >= self.HOLD_MS:
self._hold = 0
self._held = True
else:
if self._pressed:
self._pressed = False
if self._doubleclick:
if now - self._doubleclick <= self.DOUBLECLICK_MS:
self._doubleclicked = True
self._doubleclick = 0
self._hold = 0
self._held = False
else:
self._doubleclick = now
if self._doubleclick and now - self._doubleclick > self.DOUBLECLICK_MS:
if not self._held:
self._clicked = True
self._doubleclick = 0
self._hold = 0
self._held = False
def pressed(self) -> bool:
return self._pressed
def was_clicked(self) -> bool:
if self._clicked:
self._clicked = False
return True
return False
def was_double_clicked(self) -> bool:
if self._doubleclicked:
self._doubleclicked = False
return True
return False
def held(self) -> bool:
return self._held
if __name__ == "__main__":
button = Button(Pin(36, Pin.IN))
while True:
button.update()
if button.was_clicked():
print("CLICKED")
if button.was_double_clicked():
print("DOUBLE-CLICKED")
if button.held():
print("HELD")
utime.sleep_ms(10)

16
main.py
View File

@ -4,6 +4,7 @@ import json
import machine
import network
import ubinascii
import uasyncio
import utime
from umqtt.simple import MQTTClient
@ -11,6 +12,7 @@ from umqtt.simple import MQTTClient
import cd4052
import ssd1306
import mcp4
from button import Button
from rotary_irq_esp import RotaryIRQ
from statetree import StateTree
@ -42,6 +44,7 @@ rotary = RotaryIRQ(
pull_up=True,
)
rotary_value = rotary.value()
rotary_button = Button(Pin(36, Pin.IN))
try:
i2c = SoftI2C(sda=Pin(21), scl=Pin(22))
@ -91,7 +94,16 @@ def on_message(topic, msg):
def loop():
global mqtt, state, last_update, rotary, rotary_value
global mqtt, state, last_update, rotary, rotary_button, rotary_value
rotary_button.update()
if rotary_button.was_clicked():
switch.toggle_mute()
if rotary_button.was_double_clicked():
if switch.channel() >= 3:
switch.select(0)
else:
switch.select(switch.channel() + 1)
state["volume"]["left"] = pot.read(0)
state["volume"]["right"] = pot.read(1)
@ -275,4 +287,4 @@ def loop():
while True:
loop()
utime.sleep(0.1)
utime.sleep_ms(10)