# mPy - slave for Qt master
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-04-02  initial release

# incoming USB strings are displayed on LCD (connect SDA-SDA and SCL-SCL)
# pressed buttons are sent as JSON {"btn": "red"}

# 1. test in Thonny
# 2. $ picocom -q -b 115200 /dev/ttyUSB0

import	time, json
from	machine		import	Pin
from	drivers		import	nbInput
from	driver_lcd	import	Lcd

# ======================== Button ==========================

# Button release edge detect class
class Button:
    
    def __init__(self, pin_nr):
        self.btn = Pin(pin_nr, Pin.IN, Pin.PULL_UP)
        self.sts = 0
      
      
    # call at 50 mS, return True on release edge
    def exe50(self):
        if self.btn(): 					# if released
            if self.sts:
                self.sts -= 1			# debounce
                if self.sts: return
                return True
        else: self.sts = 4				# if pressed
        
# ======================= Hardware =======================

buttons = [Button(pin_nr) for pin_nr in (14, 27, 26, 25)]

# ======================== Main ==========================

def main():
    lcd      = Lcd()
    colours  = ('red', 'yellow', 'green', 'blue')
    while True:
        if s := nbInput():							# s is incoming UTF-8 string or None
            lcd.print(s[:16])
        for btn, col in zip(buttons, colours):		# check for released button
            if btn.exe50(): print(json.dumps({'btn':col}))
        time.sleep_ms(50)


main()

# ======================== end ==========================
