Skip to content

Instantly share code, notes, and snippets.

@rahji
Created June 22, 2020 17:13
Show Gist options
  • Save rahji/9cfb68195878b0eb3214bfb7b407fd0a to your computer and use it in GitHub Desktop.
Save rahji/9cfb68195878b0eb3214bfb7b407fd0a to your computer and use it in GitHub Desktop.
Simple Arduino example that uses Serial comms as its interface
/* A simple arduino sketch that accepts one of three character-commands
* via the serial port: 0 to turn the LED off, 1 to turn it on, 2 to blink it
*/
// keep track of the "state": 0, 1, or 2
char currentState = '0';
char previousState = ' ';
// a separate flag to keep track of whether the LED
// should be blinking at the moment
boolean blinkState = false;
// variables used to blink the led
// see the Arduino example "BlinkWithoutDelay" for more info
int ledState = LOW;
unsigned long previousMillis = 0;
const long intervalMillis = 300;
void setup() {
// put your setup code here, to run once:
pinMode(LED_BUILTIN,OUTPUT);
Serial.begin(9600);
while (!Serial) {
;
}
Serial.println("Ready!");
}
void loop() {
// put your main code here, to run repeatedly:
// only do something if the state has CHANGED since
// the last time we checked
if (previousState != currentState) {
switch (currentState) {
case '0':
Serial.println("LED OFF");
digitalWrite(LED_BUILTIN,LOW);
blinkState = false;
break;
case '1':
Serial.println("LED ON");
digitalWrite(LED_BUILTIN,HIGH);
blinkState = false;
break;
case '2':
Serial.println("LED BLINK");
blinkState = true;
}
previousState = currentState;
}
if (blinkState == true) blinkLED();
}
// this function is fired off whenever some data comes
// in from the serial port. See Arduino example: "SerialEvent"
void serialEvent() {
while (Serial.available()) {
currentState = (char)Serial.read();
}
}
// a function to blink the LED
// again, see the Arduino example "BlinkWithoutDelay" for more info
void blinkLED() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= intervalMillis) {
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LED_BUILTIN,ledState);
previousMillis = currentMillis;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment