Doubt in BlinkWithoutDelay program...

Firstly, I’m new to arduino and I’m noob, so excuse me for stupid questions.

I have a doubt in the default BlinkWithoutDelay program which comes in examples of compiler:-

Why the line “unsigned long currentMillis = millis();” is declared in void loop() ?
If it is in loop then every time the loop gets executed, won’t the currentMillis will reset to 0?

According to my understanding as of now, it should be declared in void setup(), but when i placed it there (cut and paste, no other change in program), it gave error as shown in attachment:-

Yes, it will be reset (to something undefined actually). But that line also assigns the value of the millis() function to the variable. If you use Serial.print() to print currentMillis; you will see that it is incrementing all the time (you have to wait about 49 days before it falls over).

Yes, I can see that the default program totally runs fine practically. But it is the only thing I have seen till now which is present in loop but works as if it is not present. Its kind of odd.

when you moved the declaration of the variable into setup() you changed its scope, rendering it unavailable in loop().

currentMillis() needs to be available in loop() and it only needs to survive for the comparison (very short time).

Zero97M:
Why the line "unsigned long currentMillis = millis();" is declared in void loop() ?
If it is in loop then every time the loop gets executed, won't the currentMillis will reset to 0?

That will set currentMillis to the current value returned by the function millis(). It will not be set to 0.

The purpose of using the variable currentMillis is so that all the tests in that iteration of loop can use the same time value.

The demo Several Things at a Time is an ectended example of BWoD and might make the usage of currentMillis clearer. Note that the demo creates currentMillis as a global variable.

...R