I have two ESP32 boards connected back to back through a serial cable, using pin 16 for Rx and 17 for Tx. They exchange simple hello world messages through the serial2 hardware port on the ESP32. The received messages are echoed on the regular serial port 0, so that I can monitor them on the PC through an USB cable.
There are no other connections to the boards except the Rx and Tx pins, and the USB cable connecting to the PC.
This test is in preparation for a larger project, where one board will send command messages through the serial2 port and the other will execute them.
This is an outline of my test program:
String str;
void setup() {
Serial.begin(115200);
Serial2.begin(115200);
}
void loop(){
while(Serial2.available()) {
str = Serial2.readStringUntil('\n');
Serial.println(str);
Serial2.println("OK);
}
}
The sending side is even simpler:
void loop(){
Serial2.println("Hello world");
delay(4000);
}
The program works fine, and messages are sent and received accurately. But unfortunately, when one board is yet to initialize,
the Serial port on the other board spits out lot of random characters like K⸮}⸮⸮⸮KK⸮-mo⸮⸮m⸮⸮[K⸮⸮⸮⸮⸮
Once the sender is initialized and starts sending out regular messages, the garbage vanishes and regular messages are displayed.
I tried reducing the baud rate to 9600, connecting the ground pins of the two boards through a wire, etc. But so far the junk print out has not vanished. This will be dangerous in my main program, since random messages can operate unintentional relays and trigger other unwanted actions. Please suggest some ways to isolate the issue.
Edit: I placed a delay before initializing the serial port at the sending end:
delay(10000);
Serial2.begin(115200);
The receiver is dumping garbage characters, non-stop, during these 10 seconds!
NOTE: I am surprised at the negative vote; I am not asking for a workaround for my problem; I have already solved it by using simple error correction techniques. But I am raising it here as a warning to all future serial port users, so that we can collectively try to understand the problem.
I am only trying to understand why the ESP32 behaves in this unexpected way. I have also raised it as a bug in the ESP32 Git repository.
The developers have replied that the serial pin will be in an undefined state before it is initialized. So I have put a work around in software: I just ignore all characters before a known marker is received. This works well for me, for now. But this is only sweeping the problem under the carpet.
Probability theory says that if sufficient number of monkeys type randomly for sufficient number of years, then you can expect to see a quote from Shakespeare in their output!