const byte ledPin [4] = { 3, 5, 9, 11 };
byte ledState [4] = { LOW, LOW, LOW, LOW };
unsigned long timeInterval [4] = { 5, 30, 2, 22 }; // timers reload with these values
unsigned long timeCounter [4] = { 0, 0, 0, 0 }; // these are the actual timers
boolean reloadable [4] = {true, true, true, true}; // this determines if the timer will restart upon reaching end
// put value in <timeCounter> for oneshot event
boolean tick [4] = {false, false, false, false}; // countdown timers flags
boolean mainTick = false;
unsigned long previousMillis = 0;
void setup() {
// Serial.begin(115200);
for (int i = 0; i < 4; i++) {
pinMode(ledPin[i], OUTPUT);
}
memcpy(timeCounter, timeInterval, 4 * sizeof(long)); // preload timers
}
void loop() {
unsigned long currentMillis = millis();
// -------------------------------------------------------------------
if (currentMillis - previousMillis >= 100) { // 100 ms tick
mainTick = true; // 100 ms tick
for (int i = 0; i < 4; i++) { // keep track of 4 time intervals
previousMillis = currentMillis;
timeCounter[i]-- ; // decrement counter
if (timeCounter[i] == 0) {
if (reloadable[i]) timeCounter[i] = timeInterval[i]; // reached zero, reload counter if it is reloadable
tick[i] = true; // emit a "tick"
}
}
}
// -------------------------------------------------------------------
if (mainTick) { // 100 ms tick
// run some code here every mainTick
}
// -------------------------------------------------------------------
if (tick[0]) { // 0.5 s tick
tick[0] = false; // clear flag so that code runs only once every tick
ledState[0] = ((ledState[0] == LOW) ? HIGH : LOW); // invert led state
// could do other logic here
}
// -------------------------------------------------------------------
if (tick[1]) { // 3.0 s tick
tick[1] = false; // clear flag so that code runs only once every tick
ledState[1] = ((ledState[1] == LOW) ? HIGH : LOW); // invert led state
}
// -------------------------------------------------------------------
if (tick[2]) { // 0.2 s tick
tick[2] = false; // clear flag so that code runs only once every tick
ledState[2] = ((ledState[2] == LOW) ? HIGH : LOW); // invert led state
}
// -------------------------------------------------------------------
if (tick[3]) { // 2.2 s tick
tick[3] = false; // clear flag so that code runs only once every tick
ledState[3] = ((ledState[3] == LOW) ? HIGH : LOW); // invert led state
}
// -------------------------------------------------------------------
if (mainTick) {
mainTick = false; // clear flag so that code runs only once every tick
// run some mode code here every mainTick
}
// -------------------------------------------------------------------
digitalWrite(ledPin[0], ledState[0]); // light LEDs according to states set earlier
digitalWrite(ledPin[1], ledState[1]);
digitalWrite(ledPin[2], ledState[2] & ledState[3]); // this one produces a compound sequence in the left LED
}