2 second delay when communicating with 2 arduinos

Hey,

I'm using this code for both arduinos.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); //RX, TX

void setup() {
  Serial.begin(38400);
  mySerial.begin(38400);
}

void loop() {
  
  
  if(Serial.available() > 0){
    String input = Serial.readString();
    mySerial.println(input);    
  }
 
  if(mySerial.available() > 1){
    String input = mySerial.readString();
    Serial.println(input);    
  }
  delay(20);
}

D2 is connected directly to D3 on the other arduino, the same goes for pin D3.

I can communicate with them while using Serial monitor for one of them and putty for the other. The problem is, why is there such a long delay - 2 seconds between sending-receiving? I believe something is wrong, as it does not depend on the string length. I deliberately put such a high baud rate to see if there was any difference between 9600 and 38400 but there wasn't any.

Thank you for any suggestions/solutions.

Serial.readString() is a blocking function - what is its timeout set at?

Rather than use blocking code have a look at the examples in Serial Input Basics - simple reliable ways to receive data. The system in the third example will be the most reliable.

You should not have delay(20); (or any other value) in the receiving program. It needs to be listening all the time. If you use my example start with delay(500); in the transmitting program and when that works you can experiment with smaller values.

...R

Try......

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); //RX, TX

void setup() {
  Serial.begin(38400);
  mySerial.begin(38400);
}

void loop() {
  
  
  if(Serial.available() > 0){
    mySerial.write(Serial.read());
  }
 
  if(mySerial.available() > 0){
    Serial.write(mySerial.read());
  }
}

@Robin2 I found that quite complex when using the markers, which was not my intention

@indev2 That worked perfectly, thank you. How can I easily separate the incoming text, that is, to have one message per line?

mawej1:
@indev2 That worked perfectly, thank you. How can I easily separate the incoming text, that is, to have one message per line?

Your messages just need appending with newline, which is a feature of most serial terminal apps, including the Arduino serial monitor. The newline byte (\n) will be passed through just the same as the text content :slight_smile: