This was a head scratcher for me….
I’ve seen in many code examples while(1) used as a way of halting code execution. Ok, I uderstand it only looks like that, in fact it’s whizzing round and round re-evaluating the truth of 1, finding it to be true and will do forever more. Great.
In a few sketches I’ve written (and seen in other people’s), this code:
while (digitalRead(buttonPin) != 0)
(with the way I’ve wired the button) just keeps looping until the button is no longer pressed. All fine and dandy.
So I wanted the code to give an opportunity for a button to be pressed and, if not, processing was to continue after a 15 second delay:
long dispStart;
:
:
dispStart = millis();
while ((digitalRead(buttonPin) == 0) && ((millis() - dispStart) < 15000)) // auto continue after 15s
But no! It doesn’t auto continue after 15 seconds. I scratched my head, drank a cup of tea, scratched my head some more, and then I tried what I thought was daft, adding a null statement: {} like this:
long dispStart;
:
:
dispStart = millis();
while ((digitalRead(buttonPin) == 0) && ((millis() - dispStart) < 15000)){} // auto continue after 15s
and it worked! Wait, what??
Would someone care to explain the whys and wherefores, please?
Hopefully this post will prevent others going through the same brain-pain that I went through ;)