I have spent the whole day trying to deal with this problem connecting Arduinos together using UART (Serial). But the problem is that it always behaves weirdly. For now the problem is that if previous number (I am sending numbers over serial) stays in the serial port.
Let me describe the problem. I want to send the following sequence of numbers 16 4 100. Numbers are sent with a terminator char after each number, but on the receiver side I get the following result 16 46 100.
As you can see if the previous number is longer (length, has more digits) than the current one, like 16 and 4, 132 and 34, the difference (number of digits) remains in the next result: for 16 and 4 it will be 16 and 46, for 132 and 34 it will be 132 and 342.
I have tried different ways to solve this problem, but unfortunately I cannot find the solution.
Here are my functions used for communication:
void sendCommandToSerial(int command) {
Serial3.print(command);
Serial3.print(TERMINATOR_CHAR);
Serial3.flush();
}
void setup() {
Serial3.begin(9600);
Serial.begin(9600);
}
int readRawBytes(char *inputBuffer,const int bufferSize) {
return Serial3.readBytesUntil(TERMINATOR_CHAR, inputBuffer, bufferSize);
}
int readIntFromSerial() {
if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
return atoi(inputBuffer);
}
return -1;
}
int readFloatFromSerial() {
if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
return atof(inputBuffer);
}
return -1;
}
I have tried both software and hardware serials, still the same. Please help to find and solve the problem.