Hi everyone,
I was watching Tutorial 2 from Jeremy's Arduino series, and I'm trying to make sense of the sketch he uses for debouncing a switch. Here is the sketch:
int switchPin = 8;
int ledPin = 13;
boolean lastButton = LOW;
boolean ledOn = false;
boolean currentButton = LOW;
void setup() {
// put your setup code here, to run once:
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
}
boolean debounce(boolean last)
{
boolean current = digitalRead(switchPin);
if (last != current)
{
delay(10);
current = digitalRead(switchPin);
}
return current;
}
void loop() {
currentButton = debounce(lastButton);
// put your main code here, to run repeatedly:
if (lastButton == LOW && currentButton == HIGH)
{
ledOn = !ledOn;
}
lastButton = currentButton;
digitalWrite(ledPin, ledOn);
}
My question is the following: The global boolean variable 'lastButton' is initialised to low, so I can see how the conditions of the very first if loop would be satisfied. But then 'lastButton' is set to currentButton, and that marks the end of the loop. So how can 'lastButton' ever return back to LOW?
My understanding is that programs are run from the very beginning (with the initialisation of global variables in this particular sketch), then the setup function, and then continue repeating the loop (without starting from the very top of the sketch). And so after the first loop function is performed the arduino wouldn't start reading from the very top of the program again, thus precluding the possibility of 'lastButton' being reset to low. Is this understanding valid?
If so, how would the conditions of the if statement within the loop ever be satisfied after the first iteration?
Thank you!