The Arduino Projects Book states that loop() runs continuously after setup() has completed.( I intepret this as finishing all the code writtin within the curly braces, and then starting again from the top).
However, in project #8, Digital Hourglass, the book uses the millis() function to keep track of the amount of time that has passed.
Code Extract
void loop() {
unsigned long currentTime = millis();
//more code....
}
In the code shouldnt above, shouldn't the currentTime be placed outside the loop() function as a global variable instead of being declared inside the loop() function? I say this because in the example aboce, wouldn't the variable currentTime be reset everytime the loop() has finished one iteration(i.e it reaches the last line and starts over again.)
However, the code works perfectly with currentTime() inside the loop() function, doesn't work if i declare currentTime as a global variable outside loop() and setup(), and will not work if declared in setup() as i will get an error saying that currentTime was not declared in this scope and i can't seem to figure out why..?
Any clarifications would be greatly appreciated.
EDIT:(Full Code)
const int switchPin = 8;
unsigned long previousTime = 0;
int switchState = 0;
int prevSwitchState = 0;
int led = 2;
long interval = 60000;
void setup(){
for(int x = 2;x<8;x++)
{
pinMode(x,OUTPUT);
}
pinMode(switchPin,INPUT);
}
void loop(){
unsigned long currentTime = millis();
if(currentTime - previousTime >interval){
previousTime = currentTime;
digitalWrite(led,HIGH);
led++;
}
if(led == 7){
//What happens when all the leds light up
}
switchState=digitalRead(switchPin);
if(switchState != prevSwitchState){
for(int x = 2;x<8;x++){
digitalWrite(x,LOW);
}
led=2;
previousTime = currentTime;
}
prevSwitchState = switchState;
}