rhetoric question: which code will be used by newcomers?
the code that comes close to their needs combined with easyness to understand how to apply it.
I have written a small tutorial with a demo-code how to use SafeString non-blocking serial input
and then derived from there a code that demonstrates LED switching on/off using serial commands that set states of a fsm
That is what I call a starting point
#include "SafeStringReader.h"
createSafeStringReader(myInputReader, 5, " ,\r\n");
const byte LED_pin = 13;
const byte fsm_idling = 1;
const byte fsm_switchLEDOn = 2;
const byte fsm_waitWithLEDOn = 3;
const byte fsm_SwitchLEDOFF = 4;
byte myStateVar;
unsigned long myWaitTimer;
const unsigned long LedOnTime = 10000;
// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - startOfPeriod >= TimePeriod ) {
// more time than TimePeriod has elapsed since last time if-condition was true
startOfPeriod = currentMillis; // a new period starts right here so set new starttime
return true;
}
else return false; // actual TimePeriod is NOT yet over
}
void ManageSerialCommands() {
if (myInputReader.read()) { // check if all characters of a command including delimiter are received
if (myInputReader == "ON") {
myStateVar = fsm_switchLEDOn;
}
if (myInputReader == "OFF") {
myStateVar = fsm_SwitchLEDOFF;
}
}
}
void setup() {
pinMode(LED_pin, OUTPUT); // no comment needed because of SELF-explaining name led
Serial.begin(115200);
Serial.println( F("Setup-Start") );
Serial.println( F("enter command ON or OFF to switch LED") );
SafeString::setOutput(Serial); // enable error messages and SafeString.debug() output to be sent to Serial
myInputReader.connect(Serial); // where SafeStringReader will read from in this demo the standard Serial
myInputReader.echoOn(); // echo back all input, by default echo is off
myStateVar = fsm_idling;
}
void FSM() {
switch (myStateVar) {
case fsm_idling:
// just do sit and wait for serial commands
break;
case fsm_switchLEDOn:
digitalWrite(LED_pin, HIGH);
myWaitTimer = millis(); // initialise Timer-variable with actual value of millis()
myStateVar = fsm_waitWithLEDOn;
break;
case fsm_waitWithLEDOn:
if ( TimePeriodIsOver(myWaitTimer, LedOnTime) ) { // check if waitingtime is over
// if number of milliseconds stored in LedOnTime have passed by
Serial.println( F("waiting time over chnage to switching LED off") );
myStateVar = fsm_SwitchLEDOFF;
}
break;
case fsm_SwitchLEDOFF:
digitalWrite(LED_pin, LOW);
Serial.println( F("LED switched off") );
Serial.println( F("enter command ON or OFF to switch LED") );
myStateVar = fsm_idling;
default:
myStateVar = fsm_idling;
break;
}
}
void loop() {
ManageSerialCommands();
FSM();
}
best regards Stefan