I have a use case where I would need to communicate via the USB & UART whenever required, and the code should be able to check and act accordingly wherever the data is available (whether over Serial or Serial0). I have tried to do this with the below platformio.ini and a small cpp code snippet. Individually, the communication works with Serial (when connected to USB) & Serial0 (when connected via UART). I would appreciate it if someone could give me a few insights on how I might achieve my goal of making both communications work simultaneously.
Umm no, not really a bridge between Serial and Serial0. Rather, 2 bridges in parallel, both ready to work whenever required. For example, if I send data using Serial, the code should send the response back through Serial. If I send data through Serial0, the response should be received back through Serial0.
Ah, my apologies for this confusion. Let me try harder.
Let’s say the ESP32 is connected through both USB (Serial) and UART (Serial0). I have an application code that expects some kind of request. Let’s say, esp32 is waiting for a command through Serial or Serial0 (both should be listening). For the response, I have to print “Command received”. So, I should know whether the request came through Serial or Serial0 so that I could accordingly do Serial.print("Command received"); or Serial0.print("Command received");
That’s why I was trying something like this:
Serial.begin(115200);
Serial0.begin(115200);
Stream *stream;
// Check which Serial interface has available data
if (Serial.available()) {
stream = &Serial;
} else if(Serial0.available()) {
stream = &Serial0;
}
...
...
...
if (Serial0.available() || Serial.available()) {
stream->println("Command received");
Is it better now?
Thanks a lot for your patience. I really appreciate it.
The issue with your code might be that after reading from the Stream object (Serial / Serial0) another call to available() will always return 0 (if all data has been read from that stream).
Maybe this is what you’re looking for:
void processStream(Stream* stream) {
int available = stream->available();
if (!available) return; // nothing to process? -> return
char buf[available];
stream->readBytes(buf, available); // after this line stream->available() returns 0!
// process content of buf
// ...
// send response
stream->println("Command received");
}
void loop() {
processStream(&Serial);
processStream(&Serial0);
}