ping pong with two Arduinos over serial I have two Arduino boards and want to make them communicate with each other over serial. The code I have used for the two boards is almost identical.

Every one second the &quot;A&quot; board sends a &quot;ping&quot; message over serial.
The &quot;B&quot; board receives the &quot;ping&quot; message and responds with a &quot;pong&quot; one.
The &quot;A&quot; board receives the &quot;pong&quot; message and prints it on screen.

Board A - ping code
String inputString = &quot;&quot;;         
boolean stringComplete = false;  

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
}

void loop() {

  Serial.print(&quot;ping&quot;);

  if (stringComplete) {
    Serial.println(inputString);
    inputString = &quot;&quot;;
    stringComplete = false;
  }
  delay(1000);
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == 'g') {
      stringComplete = true;
    }
  }
}

Board B - pong code
String inputString = &quot;&quot;;         
boolean stringComplete = false;  

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
}

void loop() {

  if (stringComplete) {
    Serial.println(&quot;pong&quot;);
    inputString = &quot;&quot;;
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == 'g') {
      stringComplete = true;
  }
 }
} 

The code seems to work, but not exactly as expected. I initiate the serial monitor of the board &quot;A&quot; and expect to see every one second:

pingpong

Instead I see this:

pingpong
pong
pong
....

which means that the pong message is repeated more than one time per second. But I want the &quot;B&quot; board to transmit the &quot;pong&quot; message only when it receives the &quot;ping&quot; one.
Why is this happening? Is there an error in the code? Is there a detail about the serial protocol which escapes me?
Any thoughts would be appreciated.
The problem is with your protocol and also with how you are using the serial.

You are using the same serial channel both for your communication protocol and for the reporting of the results.  What you see the B end sees.

So A sends ping, and when it sees the letter g it responds with pong.  You then print that pong to the serial, so end B sees pong. It gets the character g and thinks "That was a ping, I'll respond with a pong", so it does - it sends pong, which you then receive and duly print - starting the sequence over yet again.

You either need to separate out the communication and the reporting, or make your protocol look for the whole string "ping" so it never inadvertently responds to a "pong" when it shouldn't.

Here's a good resource about reading serial strings on the Arduino: http://hacking.majenko.co.uk/reading-serial-on-the-arduino