Source

arduino-comm-example / comm_example / comm_example.pde

Full commit
unsigned long nextStateChange;
int ledState = LOW;

void setup() {
  pinMode(13,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  long int currentTime;
  int inbyte;
  
  // Perform work to be done
  currentTime = millis();
  if(currentTime>=nextStateChange) {
    changeLEDState();
    nextStateChange = currentTime+1000l;
  }
  
  // Accept and parse input
  checkInput();
}
  
void changeLEDState() {
  if(ledState==LOW) {
    ledState = HIGH;
    digitalWrite(13,HIGH);
  }
  else {
    ledState = LOW;
    digitalWrite(13,LOW);
  }
}

void checkInput() {
  int inbyte;
  static char incomingBuffer[128];
  static char bufPosition=0;
  
  if(Serial.available()>0) {
    // Read only one character per call
    inbyte = Serial.read();
    if(inbyte==10) {
      // Newline detected
      incomingBuffer[bufPosition]='\0'; // NULL terminate the string
      bufPosition=0; // Prepare for next command
      
      // Supply a separate routine for parsing the command. This will
      // vary depending on the task.
      parseAndExecuteCommand(String(incomingBuffer));
    }
    else {
      incomingBuffer[bufPosition]=(char)inbyte;
      bufPosition++;
      if(bufPosition==128) {
        Serial.println("ERROR Command Overflow");
        bufPosition=0;
      }
    }
  }
}

// This routine is specific to the commands you will be interpreting.
void parseAndExecuteCommand(String command) {
  if(command.equals(String("CHECK"))) {
    // Check connection, respond with CONNECT
    Serial.println("CONNECT");
  }
  else if(command.equals(String("QUERY"))) {
    // Query state of the LED
    if(ledState==LOW) {
      Serial.println("LOW");
    }
    else {
      Serial.println("HIGH");
    }
  }
  else {
    // Unrecognized command
    Serial.println("ERROR Unrecognized Command");
  }
}