Commit e903d5ce authored by Evan Raskob's avatar Evan Raskob

fleshed out message handing

parent d2e86893
/*
* An example showing how to get some values from a string
* with numbers encoded into it.
*/
An example showing how to get some values from a string
with numbers encoded into it.
*/
// we declare variables for each parameter we want to read:
char c;
int x;
int y;
int z;
void setup() {
// we declare variables for each parameter we want to read:
int x;
int y;
int z;
// this is the string we're reading from. It's a few values separated by commas
const char buf[] = "90,80,180";
const char buf[] = "N 90,80,180";
// sscanf reads the values and stores them in variables we just declared. %d represents a number of digits to read
int n = sscanf(buf, "%d,%d,%d", &x, &y, &z);
int n = sscanf(buf, "%c %d,%d,%d", &c, &x, &y, &z);
// just print it out so we can show that it worked:
Serial.begin(38400);
while (!Serial);
Serial.println("TEST!");
Serial.print(c);
Serial.print(' ');
Serial.print(x);
Serial.print(',');
Serial.print(y);
Serial.print(',');
Serial.println(z);
Serial.println("END TEST!");
}
const unsigned int bufferSize = 256; // number of bytes we can read
char buffer[bufferSize];
int charsRead = 0; // amount of bytes we've read
void loop() {
// no need to do anything
// we need this while loop to fully empty the serial buffer
while (Serial.available())
{
char charRead = (char)Serial.read();
// be careful not to go over the buffer size (with room
// for string terminator character)!
// note that this doesn't stop the loop - we ignore
// extra bytes
if (charsRead < bufferSize )
{
if (charRead != '\n') {
buffer[charsRead] = charRead;
charsRead = charsRead + 1;
// for testing:
// Serial.print(charsRead);
}
else
{
Serial.println("process command[");
Serial.print(charsRead);
Serial.print("]\n");
buffer[charsRead] = '\0'; // terminate string
// process results
Serial.print(':');
Serial.print(buffer);
Serial.println(':');
// now handle bytes read
// NXXX means note
// sscanf reads the values and stores them in variables we just declared. %d represents a number of digits to read
int n = sscanf(buffer, "%c %d,%d,%d", &c, &x, &y, &z);
Serial.print(c);
Serial.print(' ');
Serial.print(x);
Serial.print(',');
Serial.print(y);
Serial.print(',');
Serial.println(z);
charsRead = 0; // go back to beginning of buffer for next command
}
}
// otherwise too many bytes!
else {
Serial.print("looped");
// loop back around, so we drain all serial data waiting
charsRead = 0;
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment