I am currently writing an application that enables an Arduino Nano to talk to a Mega. Currently the Nano uses the Serial.write() function to send a single integer value between 0 and 300. The Mega then uses the Serial.read() function to retrieve the data sent by the Nano. To increase the functionality of this application, I need to send a second integer value to the Mega. My first though was to concatenate the two values and send both of them out in a single Serial.write() and then parse the combined string once it is received by the Mega. But since neither of them are strings, I am unable to use the strcat() function to combine the two of them. I tried to then convert the integer values to characters but the function sprintf() was has been giving me the error - error: invalid conversion from 'char' to 'char*'.
My question then is what is the best way to send to values (the first ranging from 0-300 and the second ranging from 0-500) over a serial line and not have them get mixed up upon receiving by the Mega.
The best way is as strings, with a known start-of-packet marker and a known end-of-packet marker, with a known separator between the values:
<175,280>
With a start-of-packet marker and end-of-packet markers, partially transmitted packets can be detected and ignored. With a separator between values, you know where a value starts and ends.
For additional integrity, you could send 3 values - the two of interest and some sort of checksum.
You can, after receiving the string, use strtok to parse the tokens, and atoi to convert the tokens to integers.
That's what I was thinking of doing but the problem lies in converting the integers into strings. The function strcat() would be able to build this example - <175,280> - but it does not accept any arguments that are not strings. How do I build the string <175,280> when 175 & 280 are integers?
Well I got it to transmit in the form <123,456> and now I am trying to receive this string from the Mega and parse it so I can use the values contained in the string.
I read up some and found the Serial.read() only reads one byte at a time so I need to find out how to read all 9 bytes from the string and store them appropriately. Any ideas???
Groove, where the heck is that page you were going to put together on serial read issues?
To read multiple bytes:
char inData[24]; // or some reasonable size
int index = 0;
void loop()
{
// See if there is any serial data to read
if(Serial.available() > 0)
{
char aChar = Serial.read();
if(aChar == '<') // Start of a new packet
{
index = 0;
inData[index] = '\0'; // NULL the array
}
else if(aChar == '>')
{
// End of packet. Parse inData and do something
}
else // Somewhere in the packet
{
inData[index] = aChar; // Store the character
index++; // Advance the pointer
inData[index] = '\0'; // Keep the array NULL terminated
}
}
}