#include <HardwareSerial.h>
// Define UART instances
HardwareSerial uart1(1); // UART1
HardwareSerial uart2(2); // UART2
String baseMessage = "Message";
int counter = 0;
void setup() {
Serial.begin(115200);
Serial.println("ESP32 Full-Duplex UART Echo Demo");
// UART1: TX=GPIO17, RX=GPIO5
uart1.begin(115200, SERIAL_8N1, 5, 17);
// UART2: TX=GPIO18, RX=GPIO16
uart2.begin(115200, SERIAL_8N1, 16, 18);
// Send initial message via UART1
uart1.print(baseMessage);
Serial.println("Sent initial message: " + baseMessage);
}
void loop() {
// Check if UART1 received anything
if (uart1.available()) {
String msg = uart1.readString();
Serial.print("UART1 <<-- ");
Serial.println(msg);
// Append counter and send back via UART2
String response = baseMessage + "_" + String(++counter);
uart2.print(response);
Serial.print("UART2 -->> ");
Serial.println(response);
}
// Check if UART2 received anything
if (uart2.available()) {
String msg = uart2.readString();
Serial.print("UART2 <<-- ");
Serial.println(msg);
// Append counter and send back via UART1
String response = baseMessage + "_" + String(++counter);
uart1.print(response);
Serial.print("UART1 -->> ");
Serial.println(response);
}
delay(2000); // Small delay to avoid flooding CPU
}
UART1: Tx = GPIO17, Rx = GPIO5
UART2: Tx = GPIO18, Rx = GPIO16