Code 1 (here unsigned long currentmillis = millis() is in loop area):
const int LED = 2;
unsigned long previousmillis = 0 ;
const long delaytime = 1500;
int ledstate = HIGH;
void setup() {
pinMode(LED,OUTPUT);
}
void loop() {
unsigned long currentmillis = millis();
if (currentmillis - previousmillis >= delaytime) {
previousmillis = currentmillis;
if (ledstate == HIGH) {
ledstate = LOW;
} else{
ledstate = HIGH;
}
digitalWrite(LED,ledstate);
}
}
Code 2 (here unsigned long currentmillis = millis() is above void setup()):
const int LED = 2;
unsigned long previousmillis = 0 ;
unsigned long currentmillis = millis();
const long delaytime = 1500;
int ledstate = HIGH;
void setup() {
pinMode(LED,OUTPUT);
}
void loop() {
if (currentmillis - previousmillis >= delaytime) {
previousmillis = currentmillis;
if (ledstate == HIGH) {
ledstate = LOW;
} else {
ledstate = HIGH;
}
digitalWrite(LED,ledstate);
}
}
Code 1 is working and Code 2 is not working. What is the significance of the position of unsigned long currentmillis = millis() here and why?