如何在 PlatformIO 中将 ESP32 用作 USB 转 UART 转换器
ESP32 可以轻松用作 USB 转 UART 转换器。注意 ESP32 本身不带有 USB 接口,带有板载 USB 连接器的 ESP32 板只是使用 USB 转 UART 转换器(这是板上的单独芯片)。因此,从 ESP32 的角度来看,它
你可以将 UART TX 和 RX 映射到 ESP32 上的任何 GPIO 引脚。虽然使用一组预定义引脚有非常非常轻微的性能优势,但这在实践中并不重要。在此示例中,我们将使用引脚 GPIO2 作为 UART RX,引脚 GPIO4 作为 UART TX。
基本上,代码只是在 Serial2 和Serial(连接到 USB)之间复制字节:
usb_to_uart_loop.cpp
// 复制通过 PC 串口传入的字节
while (Serial.available() > 0) {
Serial2.write(Serial.read());
}
// 复制通过 UART 串口传入的字节
while (Serial2.available() > 0) {
Serial.write(Serial2.read());
}完整示例
usb_to_uart_full_example.cpp
#include <Arduino.h>
#define UART_RX_PIN 2 // GPIO2
#define UART_TX_PIN 4 // GPIO4
void setup() {
// Serial 连接到计算机
Serial.begin(115200);
// Serial2 是连接到外部电路的硬件 UART 端口
Serial2.begin(115200, SERIAL_8N1,
UART_RX_PIN,
UART_TX_PIN);
}
void loop() {
// 复制通过 PC 串口传入的字节
while (Serial.available() > 0) {
Serial2.write(Serial.read());
}
// 复制通过 UART 串口传入的字节
while (Serial2.available() > 0) {
Serial.write(Serial2.read());
}
}关于 platformio.ini,我们只需要设置 monitor_speed 以匹配 Serial.begin(115200); 中的值:
platformio.ini
[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200Check out similar posts by category:
C/C++, Electronics, ESP8266/ESP32, PlatformIO
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow