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 "A" board sends a "ping" message over serial.
- The "B" board receives the "ping" message and responds with a "pong" one.
- The "A" board receives the "pong" message and prints it on screen.
Board A - ping code
String inputString = ""; boolean stringComplete = false; void setup() { Serial.begin(9600); inputString.reserve(200); } void loop() { Serial.print("ping"); if (stringComplete) { Serial.println(inputString); inputString = ""; 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 = ""; boolean stringComplete = false; void setup() { Serial.begin(9600); inputString.reserve(200); } void loop() { if (stringComplete) { Serial.println("pong"); inputString = ""; 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 "A" 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 "B" board to transmit the "pong" message only when it receives the "ping" 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.