#!/usr/bin/env python3 """ Serial loopback test – single file, runs on Pico and ESP32. Wire TX to RX (Pico: GP0–GP1, ESP32: 17–18), then: mpremote run pico/test/test_serial.py For ESP32→Pico: run test_serial_send.py on ESP32, test_serial_receive.py on Pico; wire ESP32 TX (17) to Pico RX (1). """ import time import sys from machine import UART, Pin if "esp32" in sys.platform: UART_ID, TX_PIN, RX_PIN, BAUD = 1, 17, 18, 115200 else: UART_ID, TX_PIN, RX_PIN, BAUD = 0, 0, 1, 115200 READ_TIMEOUT_MS = 100 LINE_TERM = b"\n" print("UART loopback: %s UART%d TX=%s RX=%s %d baud" % (sys.platform, UART_ID, TX_PIN, RX_PIN, BAUD)) uart = UART(UART_ID, baudrate=BAUD, tx=Pin(TX_PIN, Pin.OUT), rx=Pin(RX_PIN, Pin.IN)) uart.read() to_send = [b"hello", b"123", b"{\"v\":\"1\"}"] errors = [] for msg in to_send: uart.write(msg + LINE_TERM) time.sleep_ms(20) buf = bytearray() deadline = time.ticks_add(time.ticks_ms(), READ_TIMEOUT_MS) while time.ticks_diff(deadline, time.ticks_ms()) > 0: n = uart.any() if n: buf.extend(uart.read(n)) if LINE_TERM in buf: break time.sleep_ms(2) got = bytes(buf).strip() if got != msg: errors.append((msg, got)) uart.deinit() if errors: print("FAIL loopback:", errors) else: print("PASS loopback: sent and received", to_send)