Question: Where do I put code if I want it to execute only once per Arduino startup?
Background: I tend to use my Arduino to perform tasks that should be executed once per power cycle. (For example, my robot should only drive forward once every time I turn it on--more than that, and it might fall off the table.)
The standard Arduino IDE "template" consists of a loop()
and a setup()
function. The setup
code is run once per power cycle, and the loop
is re-started every time it finishes.
I see two approaches to code "1 time tasks:"
Method 1: "Loop once"
void setup() {
//do setup stuff
}
void loop() {
//do task
while(1) ; //Repeat forever, preventing function from re-starting
}
Method 2: "Setup only"
void setup() {
//do setup stuff
//do task
}
void loop() {
//do nothing
}
More detailed form of question: Is one of these methods "better" from a hardware/software sense? (e.g. is there anything "special" about the setup
function, like it can only run for so much time?)
And, if they are the same from a hardware/software perspective, is there a "best practice" or standard way of writing code for these situations in the Arduino community?
exit
command is discussed in arduino.stackexchange.com/questions/188/…