Data in serial comm going more than expected

I have been trying to get serial communication to work with using USB to Raspberyy Pi with Arduino Nano. I have got down most of the things correct; I want the Nano to respond only when I send a request from Pi. The problem I am facing now is that the Nano is sending to Rpi one more time than I am expecting. I can of course ignore this, but I want to know if its a problem with my understanding of how the serial comm works.

Attaching the snippets of the relevant code,

Arduino code;

void loop() {
  readSerialPort();
  if (msg == "data") 
  {
      Serial.print(Int1);
      Serial.print("x");
      Serial.print(Int2);
      Serial.print("x");
      Serial.print(Int3);
  }
  delay(1);  
}

void readSerialPort() {
  msg = "";
  if (Serial.available()) {
    delay(10);
    while (Serial.available() > 0) {
      msg += (char)Serial.read();
    }
    Serial.flush();
  }
}

Python code at the Raspberry Pi end;

while True:
            cmd="data"
            arduino.write(cmd.encode())
            if  arduino.inWaiting()>0: 
                answer=str(arduino.readline(),'utf-8')
                print("---> {}".format(answer))

This is how I am getting the integers in python,
Py_arduino

There is a serial input bascis tutorial, which you should study.

On a Nano don’t use Strings and on any single thread system don’t use delay.

[Mod edit]
See new topic for discussion on the merits of char arrays Vs Strings

1 Like

23 posts were split to a new topic: Use of char arrays (C strings) Vs Strings (discussion)

The discussion past this point was not really an answer to the OP’s question, but was worth continuing so I have moved it to a new topic.