Some code like this would read all of <red_led, HIGH>:
#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 it says "Process the packet" is where you would perform the parsing. The strtok() function would be useful. Of course, the Arduino will have no idea what to do with the name red_pin or the name HIGH, so you will have to write code to map them to something that the Arduino does understand.
[code]Do you absolutely need an ASCII protocol like that, or are you also in control of the app side? If so, your code will be incredibly more reliable, simple, and fast if you use bytes instead.
For example (and forgive coding mistakes, I'm replying via iPhone)
[code]
byte redLedPin = 2;
byte greenLedPin = 3;
if (Serial.available() > 1). //Only read packet if 2 bytes are available
{
byte ledNum = Serial.read();
byte ledVal = Serial.read();
switch (ledNum)
{
case 0:
digitalWrite(redLedPin, ledVal);
break;
case 1:
digitalWrite(greenLedPin, ledVal);
break;
}
}
Then on the app side you only send 2 bytes to turn an LED on/off. Send the first byte to tell it which LED to control and the second byte to tell Arduino whether you want the LED on or off. Just make sure the first byte has a corresponding "case" and the second byte is either 0 or 1.[/code][/code]
// zoomkat 8-6-10 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later
int ledPin = 13;
String readString;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
Serial.println("serial on/off test 0021"); // so I can keep track
}
void loop() {
while (Serial.available()) {
delay(2);
char c = Serial.read();
readString += c;
}
if (readString.length() >0) {
Serial.println(readString);
if (readString == "on")
{
digitalWrite(ledPin, HIGH);
}
if (readString == "off")
{
digitalWrite(ledPin, LOW);
}
readString="";
}
}