Search code examples
uartesp32micropython

Write data to ESP32 over USB connection with MicroPython


I have an ESP32 connected to a computer via USB port. I can use the ESP32 to send data over the serial connection using the print statement, I need to periodically write commands into the ESP32. How do I read what is coming over the COM port on the ESP32 in MicroPython? I unsuccessfully tried many variations of the following:

from machine import UART

uart = UART(115200)
while 1:
    if uart.any():
        msg = uart.read()
        print(msg)

Solution

  • Print is for printing in REPL only. If you want to communicate with MCU via serial port you have to write to it.

    The simplest example would be:

    # your imports and initialization
    
    msg = uart.read()
    uart.write(msg)
    

    And on your computer you have to run some serial console e.g. picocom or if you're Windows user then Putty. After connection just type something in terminal and hit enter. This is basically all you need to start echoing messages. You can use Python serial library on your machine but I suggest to stick with simplest tools until you connect successfully for the first time.

    Two more things though:

    1. Your init is incomplete imho. It should contain port and timeout options.
    2. You can't use the same USB port for programming and communication (like in Arduino). REPL is going to blow your connection up. You need USB to serial adapter for $2 from China and connect to other UART pins (there are 3 UART interfaces on ESP32).