# mPy - Esp32 serial communication
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-02-05  initial release

import	time
from	machine	import	UART

# =========================== Serial ================================

class Serial:

    # Open serial port through UART.
    def __init__(self, id=1, baud=115200, rx=27, tx=26):
        self.uart = UART(id, baudrate=baud, rx=rx, tx=tx, stop=2)
        self.b_rx = None
        self.uart.irq(self.onRx, trigger=UART.IRQ_RXIDLE)


    # close the serial port
    def close(self):
        if self.uart:
            self.uart.deinit()
            self.uart = None


    # Write bytes or bytearray
    def write(self, obj):
        self.uart.write(obj)


    # Irq on data receive gap, using timer 0
    def onRx(self, sender):
        self.b_rx = self.uart.read()	# return b'\x00 on no data

# =========================== test ===============================

if __name__ == '__main__':
    
    def test():
        serial = Serial()
        try:
            while True:
                for _ in range(10):
                    if serial.b_rx:				# @ 100 mSec
                        print(serial.b_rx)
                        serial.b_rx = None
                    time.sleep_ms(100)
                serial.write(b'hello')			# @ 1 Sec
        finally: serial.close()
        
        
    test()
    
# =========================== end ================================
