Hello.
I have a bit of a complicated affair going on with comms between a Python routine, a Mega2560 and an Uno.
My Mega is sending data on Serial3 as stated below: (code is huge, so just lifted this bit)
SendtoUNO is called whenever the data changes (that works fine).
//--Send data from the Mega to the UNO so it can be passed on to the Python routine later
char Assembled_data[20]; // Data to send to the Uno
char Number[5]; // To assist with data conversion to send to the Uno
void SendtoUNO(){
strcpy(Assembled_data, ""); // Clear the data
strcat(Assembled_data, "<"); // Assemble the data
sprintf(Number, "%d", int(Ammo)); strcat(Assembled_data, Number);
strcat(Assembled_data, ",");
sprintf(Number, "%d", Detection_mode); strcat(Assembled_data, Number);
strcat(Assembled_data, ",");
sprintf(Number, "%d", Firing); strcat(Assembled_data, Number);
strcat(Assembled_data, ">");
Serial3.println(Assembled_data);
}
This is then received on the UNO as:
const byte buffSize2560 = 40;
char inputBuffer2560[buffSize2560];
byte bytesRecvd2560 = 0;
boolean readInProgress2560 = false;
boolean newDataFrom2560 = false;
const char startMarker = '<';
const char endMarker = '>';
void loop() {
if(LinkSerial.available() > 0) {
char z = LinkSerial.read(); // read char from serial
if (z == endMarker) { // look for end marker
readInProgress2560 = false; // if found, set read in progress true (will stop adding new byte to buffer)
inputBuffer2560[bytesRecvd2560] = 0; // clear input buffer
processData2560(); // process data in buffer
}
if (readInProgress2560) {
inputBuffer2560[bytesRecvd2560] = z; // populate input buffer with bytes
bytesRecvd2560 ++; // increment index
if (bytesRecvd2560 == buffSize2560) { // when buffer is full
bytesRecvd2560 = buffSize2560 - 1; // keep space for end marker
}
}
if (z == startMarker) { // look for start maker
bytesRecvd2560 = 0; // if found, set byte received to 0
readInProgress2560 = true; // set read in progress true
}
}
}
//--------------------------------------------------------
void processData2560() // Convert data from 2560p to useable variables
{
char * strtokIndx2560; // this is used by strtok() as an index
strtokIndx2560 = strtok(inputBuffer2560,","); // get the first part
Ammo = atoi(strtokIndx2560); // convert this part to an integer
strtokIndx2560 = strtok(NULL,","); // get the second part(this continues where the previous call left off)
Detection_mode_gun = atoi(strtokIndx2560); // convert this part to an integer
strtokIndx2560 = strtok(NULL, ","); // get the third part
Firing = atoi(strtokIndx2560); // convert this part to an integer (string to int)
}
The data is arriving fine sometimes, but corrupted probably 1 in 5 reads.
Have not been able to find the reason.
Can somebody confirm whether my method is sound?