/*
============================
Selfmade For-Loop III
============================
This is an example of a "selfmade" for-loop
which is usually required where a a non-blocking
loop is required e.g. to blink an LED
This is an example of a non-blocking millis() function replacing delay()
to blink a LED and counting a variable in given time intervals
First Edition 2023-04-02
ec2021
Simulation: https://wokwi.com/projects/360905127753897985
Discussion: https://forum.arduino.cc/t/millis-instead-of-delay-and-loop-instead-of-for-loop/1110044
Changed 2023-07-26
*/
constexpr byte LEDPin = 13;
void setup() {
Serial.begin(115200);
pinMode(LEDPin, OUTPUT);
}
unsigned long lastChange = 0; // Variable to store the time in ms when ledState was changed
unsigned long delayTime = 300; // Delay in [ms] when then next change shall take place
unsigned long lastCount = 0;
unsigned long delayCount = 500;
boolean firstBlink = true; // Added firstBlink and firstCount to make sure
boolean firstCount = true; // that the millis()-if-clauses are already entered
// in the first loop()
int i = 0;
int iMax = 9;
void loop() {
if (millis()-lastChange >= delayTime || firstBlink){
lastChange = millis();
boolean ledState = digitalRead(LEDPin);
digitalWrite(LEDPin, !ledState);
firstBlink = false;
}
if (millis()-lastCount >= delayCount || firstCount){
lastCount = millis();
firstCount = false;
if (i <= iMax) {
Serial.print(i);
Serial.print("\t"); // prints tabs
i++;
} else {
Serial.println();
i = 0;
}
}
}