arduino Serial Communication Command Handling over Serial


Example

byte incoming;
String inBuffer;

void setup() {
    Serial.begin(9600); // or whatever baud rate you would like
}

void loop(){
    // setup as non-blocking code
    if(Serial.available() > 0) {
        incoming = Serial.read();
        
        if(incoming == '\n') {  // newline, carriage return, both, or custom character
        
            // handle the incoming command
            handle_command();

            // Clear the string for the next command
            inBuffer = "";
        } else{
            // add the character to the buffer
            inBuffer += incoming;
        }
    }

    // since code is non-blocking, execute something else . . . .
}

void handle_command() {
    // expect something like 'pin 3 high'
    String command = inBuffer.substring(0, inBuffer.indexOf(' '));
    String parameters = inBuffer.substring(inBuffer.indexOf(' ') + 1);
    
    if(command.equalsIgnoreCase('pin')){
        // parse the rest of the information
        int pin = parameters.substring("0, parameters.indexOf(' ')).toInt();
        String state = parameters.substring(parameters.indexOf(' ') + 1);

        if(state.equalsIgnoreCase('high')){
            digitalWrite(pin, HIGH);
        }else if(state.equalsIgnoreCase('low)){
            digitalWrite(pin, LOW);
        }else{
            Serial.println("did not compute");
        }
    } // add code for more commands 
}