1. import _thread
    2. import utime
    3. from machine import UART
    4. from queue import Queue
    5. class Example_uart(object):
    6. def __init__(self, no=UART.UART2, bate=115200, data_bits=8, parity=0, stop_bits=1, flow_control=0):
    7. self.uart = UART(no, bate, data_bits, parity, stop_bits, flow_control)
    8. self._queue = Queue(5)
    9. _thread.start_new_thread(self.handler_thread, ())
    10. self.uart.set_callback(self.callback)
    11. def callback(self, para):
    12. print("call para:{}".format(para))
    13. if(0 == para[0]):
    14. self._queue.put(para[2])
    15. def uartWrite(self, msg):
    16. print("write msg:{}".format(msg))
    17. self.uart.write(msg)
    18. def uartRead(self, len):
    19. msg = self.uart.read(len)
    20. utf8_msg = msg.decode()
    21. print("UartRead msg: {}".format(utf8_msg))
    22. return utf8_msg
    23. def uartWrite_test(self):
    24. for i in range(10):
    25. write_msg = "Hello count={}".format(i)
    26. self.uartWrite(write_msg)
    27. utime.sleep(1)
    28. def handler_thread(self):
    29. while True:
    30. recv_len = self._queue.get()
    31. self.uartRead(recv_len)
    32. if __name__ == "__main__":
    33. uart_test = Example_uart()
    34. uart_test.uartWrite_test()