Sending one variable is quite easy, but how is it done with more then one?
Just like one.
How am i able to say, hey this is the value of variable a and this for variable b.(like marking them)
Are you sending in binary or ASCII? If ASCII, "A=xxx, B=yyy" would work. If binary, there is no need to label them. The bytes are sent in the order you specify.
The variables a and b are numbers between 0 and 180 that are constantly changing.
if i send them in a specified order, (a,b,a,b....)which could look like (121,9,109,40....)
and i read the serial monitor with arduino, how do i say: ok the first one is a, the second one is b, the third one is a etc. ...?
(on the arduino side)
Isnt there a safer method, because if there appears a mistake (like missing one number), perhaps a b becomes an a or is it unnecessary?
The variables a and b are numbers between 0 and 180 that are constantly changing.
Like so?
variable a = 22;
variable b = 29;
if i send them in a specified order, (a,b,a,b....)which could look like (121,9,109,40....)
No. Send them like "<121,9><109,40>..."
Then, you know where the data for one iteration starts and where it ends.
#define SOP '<'
#define EOP '>'
bool started = false;
bool ended = false;
char inData[80];
byte index;
void setup()
{
Serial.begin(57600);
// Other stuff...
}
void loop()
{
// Read all serial data available, as fast as possible
while(Serial.available() > 0)
{
char inChar = Serial.read();
if(inChar == SOP)
{
index = 0;
inData[index] = '\0';
started = true;
ended = false;
}
else if(inChar == EOP)
{
ended = true;
break;
}
else
{
if(index < 79)
{
inData[index] = inChar;
index++;
inData[index] = '\0';
}
}
}
// We are here either because all pending serial
// data has been read OR because an end of
// packet marker arrived. Which is it?
if(started && ended)
{
// The end of packet marker arrived. Process the packet
// Reset for the next packet
started = false;
ended = false;
index = 0;
inData[index] = '\0';
}
}
Where the comment "Process the packet" is, inData would contain "121,9" which you can parse using strtok(), and convert to values using atoi(). There is no risk, then, of getting the numbers out of order.
Isnt there a safer method, because if there appears a mistake (like missing one number), perhaps a b becomes an a or is it unnecessary?
Using start and end of packet markers makes this impossible. There is still the possibility of data loss, but lost start or end markers are handled. Lost characters in between are possible, and there are ways to deal with this possibility. How to do send depends on the severity of a lost/corrupted value.
Dear Paul,
thank you a lot.
I´m going to look at the code the whole day, till i´m completely into it.
When i got it and it is working im going to tell you.
If you need to guarantee that your data arrives in correct pairs, Paul's code is the sort of thing you need. It can be less complex, but only if you are prepared to forget about data integrity.