The void loop() in Arduinodom is something that executes over and over forever, of course. I tried putting a "break" in the middle of it, so that under certain conditions it would quit circling. The compiler yelled at me, saying that the "break;" statement was not inside a loop or other such repeating structure.
Hmm, coulda sworn it said "void loop()".
But the error message referred to it as a function. Is it sort of a combination of both?
loop() is a function that is called by a loop behind the scenes (by the init() function - it ends in a while loop that repeatedly calls loop() forever).
LilAbner:
Hmm, so every Arduino sketch MUST have a "void loop()" section, no exceptions?
Not necessarily - if your sketch has a 'main()' function, it will be used instead of the default 'main()'
For instance, this will compile in the IDE:-
#include <Arduino.h> // Not absolutely necessary for compilation, but
// included for the standard Arduino functions.
int main(void)
{
// More code here
return 0;
}
(But you don't want it to ever get to the 'return' statement. )
And putting a "break;" statement inside it is a no-no, unless it's in its own loop that's placed inside "void loop()"?
OK, now I'm curious. What happens if it reaches the return? What if you want the Arduino to "do it's thing" one time when it powers up, and then when done, just quit. (go to sleep, whatever)
DrWizard:
OK, now I'm curious. What happens if it reaches the return?
I thought that would be obvious - the Arduino will burst into flames.
Actually, nothing happens, of course. Usually, though, we want our programs to continue execution. That's all that I meant.
And to use the standard Arduino stuff, I forgot that you also need to call 'init()'
ie
This works as expected:-
#include <Arduino.h> // Not absolutely necessary for compilation, but
// included for the standard Arduino functions.
int main(void)
{
init();
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
delay(2000);
digitalWrite(13, LOW);
return 0;
}
But in this version, the LED lights but doesn't turn back off:-
#include <Arduino.h> // Not absolutely necessary for compilation, but
// included for the standard Arduino functions.
int main(void)
{
// init();
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
delay(2000);
digitalWrite(13, LOW);
return 0;
}
What if you want the Arduino to "do it's thing" one time when it powers up, and then when done, just quit. (go to sleep, whatever)
The usual way to do this is to put all of the code in 'setup()', then leave the 'loop()' empty.
DrAzzy:
You could also put it to sleep in setup() with no way to wake other than reset, if you want it to only run once, and then essentially turn off.
That's a better option in terms of power consumption. An empty 'loop()' still goes flat-out.
And I don't know what really happens internally with a user-defined 'main()' that returns when the code has executed. Where does it return to, I wonder?