Hi,
I'm reading from the serial output of a device.
The output format is in ASCII sent about once per second with 9600bps in the following pattern:
[Variable length decimal][CR][LF]
When I run the loop as a single program, the output is fine. (At least during the 30min I've tested it)
When I run the exactly same as a part of my program, randomly (first afer ~20-30 seconds, then every 16s) an extra number appears in the pattern
[Variable length decimal][Variable lenght decimal][CR][LF] (example on the bottom, CR LF visible when using readBytes instead of readBytesUntil)
I don't know where the second number comes from, because I only read until CR, and every number is sent followed by a CR.
I'm using the following code (with debug output -48 to show decimal value of ASCII character digit)
I don't use any variable outside of this (except cpm)
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9); //RX, TX
unsigned int cpm;
void setup() {
Serial.begin(115200);
mySerial.begin(9600);
mySerial.setTimeout(1500);
}
void loop() {
char cpm_array[6]= {0,0,0,0,0,0}; // Make sure the array is 0 before starting
if(mySerial.find(0x0A)){ // Start reading after 0x0A (LF)
mySerial.readBytesUntil(0x0D,cpm_array,5); // Until 0x0D (CR)
char buffer[6];
buffer[0] = cpm_array[0],
buffer[1] = cpm_array[1],
buffer[2] = cpm_array[2],
buffer[3] = cpm_array[3],
buffer[4] = cpm_array[4],
buffer[5] = '\0';
Serial.print("cpm_array: ");
for(int i= 0; i<6; i++) {
Serial.print(cpm_array[i]-48);
Serial.print(" ");
}
Serial.println();
cpm = atoi(buffer);
}
Serial.print("cpm = ");
Serial.println(cpm);
}
An example of the output containing an unexpected number:
cpm_array: 3 6 -48 -48 -48 -48
cpm = 36
cpm_array: 3 7 -48 -48 -48 -48
cpm = 37
cpm_array: 3 7 3 8 -48 -48 //Why?!
cpm = 3738
cpm_array: 3 7 -48 -48 -48 -48
cpm = 37
cpm_array: 3 8 -48 -48 -48 -48
cpm = 38
How could anything outside of this code have an influence on cpm_array[]?
To me it looks like readBytes is omitting one CR,LF somehow, but I don't know why and how.