Tuesday, March 18, 2014

Arduino detect string command from serial port

This example receive char and detect command terminal '\n', and compare with predefined command ("LEDON" and "LEDOFF") with strcmp() function, to turn on/off Esplora's on-board LED accordingly.



serialReadCmd.ino
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>

int MAX_CMD_LENGTH = 10;
char cmd[10];
int cmdIndex;
char incomingByte;

void setup() {
  
    EsploraTFT.begin();  
    EsploraTFT.background(0,0,0);
    EsploraTFT.stroke(255,255,255);  //preset stroke color
     
    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
    
    //indicate start
    Esplora.writeRGB(255, 255, 255);
    delay(250);
    Esplora.writeRGB(0, 0, 0);
    
    cmdIndex = 0;
    
}
 
void loop() {
    
    if (incomingByte=Serial.available()>0) {
      
      char byteIn = Serial.read();
      cmd[cmdIndex] = byteIn;
      
      if(byteIn=='\n'){
        //command finished
        cmd[cmdIndex] = '\0';
        Serial.println(cmd);
        cmdIndex = 0;
        
        if(strcmp(cmd, "LEDON")  == 0){
          Serial.println("Command received: LEDON");
          Esplora.writeRGB(255, 255, 255);
        }else if (strcmp(cmd, "LEDOFF")  == 0) {
          Serial.println("Command received: LEDOFF");
          Esplora.writeRGB(0, 0, 0);
        }else{
          Serial.println("Command received: unknown!");
        }
        
      }else{
        if(cmdIndex++ >= MAX_CMD_LENGTH){
          cmdIndex = 0;
        }
      }
    }
    
}


5 comments:

  1. Great example! I was trying to *way* over complicate something that was really quite simple. Thanks!

    ReplyDelete
  2. It went from complicated to simple once I landed here.

    Thank you.

    ReplyDelete
  3. Sir, I can't make it work


    int MAX_CMD_LENGTH = 10;
    char cmd[10];
    int cmdIndex;
    char incomingByte;
    int relay1 = 13;

    void setup() {

    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
    pinMode(relay1, OUTPUT);
    digitalWrite(relay1, LOW);

    Serial1.begin(9600);
    delay(20000); // give time to log on to network.
    Serial1.print("AT+CMGF=1\r"); // set SMS mode to text
    delay(100);
    Serial1.print("AT+CNMI=2,2,0,0,0\r");
    // blurt out contents of new SMS upon receipt to the GSM shield's serial out
    delay(100);
    Serial.println("Ready...");
    cmdIndex = 0;

    }

    void loop() {

    if (incomingByte=Serial.available()>0) {

    char byteIn = Serial.read();
    cmd[cmdIndex] = byteIn;

    if(byteIn=='\n'){
    //command finished
    cmd[cmdIndex] = '\0';
    Serial.println(cmd);
    cmdIndex = 0;

    if(strcmp(cmd, "LEDON") == 0){
    Serial.println("Command received: LEDON");
    digitalWrite(relay1,HIGH);
    }if (strcmp(cmd, "LEDOFF") == 0) {
    Serial.println("Command received: LEDOFF");
    }

    }else{
    if(cmdIndex++ >= MAX_CMD_LENGTH){
    cmdIndex = 0;
    }
    }
    }

    }

    ReplyDelete