Sorry to bump up this thread: I have used this and works pretty well.
I only send 1 piece of data from one Arduino to another. First Arduino gathers data and sends it to a second Arduino that received this piece of data. What I'd like to do is to set the received data to a variable. Then re-use it in my "Loop".
Code I am using in my receiving part is this, but doesn't work as expected:-
const char startOfNumberDelimiter = '<';
const char endOfNumberDelimiter = '>';
long _r = 0;
void setup ()
{
Serial.begin (115200);
Serial2.begin (115200);
Serial3.begin (115200);
pinMode(8, INPUT);
} // end of setup
void processNumber (const long n)
{
_r = n;
} // end of processNumber
void processInput ()
{
static long receivedNumber = 0;
static boolean negative = false;
byte c = Serial2.read ();
switch (c)
{
case endOfNumberDelimiter:
if (negative)
processNumber (- receivedNumber);
else
processNumber (receivedNumber);
// fall through to start a new number
case startOfNumberDelimiter:
receivedNumber = 0;
negative = false;
break;
case '0' ... '9':
receivedNumber *= 10;
receivedNumber += c - '0';
break;
case '-':
negative = true;
break;
} // end of switch
} // end of processInput
void loop ()
{
if (Serial2.available ())
{
processInput ();
}
Serial.println(_r);
}
Any help is appreciated.