/*
Forum: https://forum.arduino.cc/t/replace-delay-with-milllis/1421640
Wokwi: https://wokwi.com/projects/451485436765501441
2025/12/28
ec2021
SerialCommand library used for this example:
https://www.arduinolibraries.info/libraries/serial-command-advanced
*/
#include <SerialCommand.h>
SerialCommand SerialCommandHandler;
class LedData {
private:
byte pin;
byte state = LOW;
unsigned long interval;
unsigned long lastChange;
public:
LedData(byte p, unsigned long intervl) : pin(p), interval(intervl) {};
void init() {
pinMode(pin, OUTPUT);
}
boolean isDone() {
if (state == LOW) {
digitalWrite(pin, HIGH);
lastChange = millis();
state = HIGH;
};
if (millis() - lastChange >= interval) {
off();
return true;
}
return false;
}
void off() {
digitalWrite(pin, LOW);
state = LOW;
}
};
LedData led[] = {
{2, 4000},
{3, 1000},
{4, 3000}
};
constexpr int noOfItems = sizeof(led) / sizeof(led[0]);
boolean startCmdReceived = false;
boolean stopCmdReceived = false;
void setup()
{
Serial.begin(115200);
Serial.println("Begin");
SerialCommandHandler.addCommand("Start", Cmd_Start);
SerialCommandHandler.addCommand("Stop", Cmd_Stop);
SerialCommandHandler.setDefaultHandler(unrecognized);
for (int i = 0; i < noOfItems; i++) {
led[i].init();
}
}
void loop()
{
SerialCommandHandler.readSerial();
handleLeds();
blinkWithoutDelay(500);
}
void handleLeds() {
static byte itemNo = 0;
if (stopCmdReceived) {
for (int i = 0; i < noOfItems; i++) {
led[i].off();
}
itemNo = 0;
stopCmdReceived = false;
startCmdReceived = false;
}
if (startCmdReceived) {
if (led[itemNo].isDone()) {
itemNo++;
}
if (itemNo >= noOfItems) {
itemNo = 0;
startCmdReceived = false;
}
}
}
// Commands Start and Stop
// set boolean variables to true
// that enable the required functionality
void Cmd_Start()
{
Serial.println(F("The Start command is handled"));
startCmdReceived = true;
}
void Cmd_Stop()
{
Serial.println(F("The Stop command is handled"));
stopCmdReceived = true;
}
// Invalid commands leave a message
void unrecognized(const char *command) {
Serial.println("Invalid command ..");
}
void blinkWithoutDelay(unsigned long interval) {
constexpr byte bluePin {5};
static unsigned long lastChange = 0;
if (lastChange == 0) pinMode(bluePin, OUTPUT);
if (millis() - lastChange > interval) {
lastChange = millis();
byte state = digitalRead(bluePin);
digitalWrite(bluePin, !state);
}
}