//#define INTERVAL1 1000
//#define INTERVAL2 100
//#define LED_BUILTIN 5
#define LED1 5
#define LED2 2
int period1=100, period2=200;
// ---- for command interpreter ----
String rcvdstring; // string received from serial
String cmdstring; // command part of received string
String parmstring; // parameter part of received string
float parmvalfloat;
int parmvalint;
bool newcmd = 0; // flag when new command received
int sepIndex; // index of seperator
int noparm=0;
// -----------------------------------
long previousMillis1 = 0, previousMillis2 = 0;
void setup() {
pinMode(LED2, OUTPUT); // red
pinMode(LED1, OUTPUT); // green
Serial.begin(115200);
}
void loop() {
long currentMillis = millis();
if(currentMillis - previousMillis1 > period1) {
previousMillis1 = currentMillis;
digitalWrite(LED1, !digitalRead(LED1));
}
if(currentMillis - previousMillis2 > period2) {
previousMillis2 = currentMillis;
digitalWrite(LED2, !digitalRead(LED2));
}
if (Serial.available() > 0) { // detect new input
rcvdstring = Serial.readString();
newcmd = 1;
}
if (newcmd) { // execute this part only when new command received
cmdInt(); // invoke the interpreter
newcmd = 0;
}
}
void cmdInt(void)
{
rcvdstring.trim(); // remove leading&trailing whitespace, if any
// find index of separator (blank character)
sepIndex = rcvdstring.indexOf('=');
if (sepIndex==-1) {
cmdstring = rcvdstring;
noparm = 1;
}
else {
// extract command and parameter
cmdstring = rcvdstring.substring(0, sepIndex);
cmdstring.trim();
parmstring = rcvdstring.substring(sepIndex+1);
parmstring.trim();
noparm = 0;
}
// check if received command string is a valid command
if (cmdstring.equalsIgnoreCase("period1")) {
// task for command 1
parmvalint = parmstring.toInt();
if (parmvalint<50 | parmvalint>2000) {
Serial.println("Period1 out of range!");
}
else {
period1 = parmvalint;
Serial.print("Period1 changed to ");
Serial.println(period1);
}
}
else if (cmdstring.equalsIgnoreCase("period2")) {
// task for command 1
parmvalint = parmstring.toInt();
if (parmvalint<50 | parmvalint>2000) {
Serial.println("Period2 out of range!");
}
else {
period2 = parmvalint;
Serial.print("Period2 changed to ");
Serial.println(period2);
}
}
}