Skip to content

Instantly share code, notes, and snippets.

@RealOrangeOne
Created December 24, 2015 23:47
Show Gist options
  • Select an option

  • Save RealOrangeOne/ce2ced6f3ecd69e4722b to your computer and use it in GitHub Desktop.

Select an option

Save RealOrangeOne/ce2ced6f3ecd69e4722b to your computer and use it in GitHub Desktop.

Revisions

  1. RealOrangeOne created this gist Dec 24, 2015.
    42 changes: 42 additions & 0 deletions serial.ino
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    const char endChar = '\n';
    const char commandIdent = '$';

    String inputString;
    boolean hasInput = false;
    boolean isCommand = false;

    void setup() {
    Serial.begin(9600);
    }


    void loop() {
    if (hasInput) {
    if (isCommand) {
    Serial.println("Got command: " + inputString);
    } else {
    Serial.println("Got input: " + inputString);
    }
    inputString = "";
    isCommand = false;
    hasInput = false;
    }
    }


    void serialEvent() {
    while (Serial.available()) {
    char inChar = (char)Serial.read();

    if (inChar == endChar) { // It's the end of the input stream, let's work out what it is
    hasInput = true;

    if (inputString.startsWith(String(commandIdent))) {
    isCommand = true;
    inputString.remove(0, 1);
    }
    } else {
    inputString += inChar;
    }
    }
    }