Go Down

Topic: Setup and Loop?? (Read 7476 times) previous topic - next topic

Charles

Do I have to use setup and loop?

Could I leave out the loop function and do this?

void setup() {
 Serial.begin(9600);
 Serial.println("Bla bla bla");
 int a = 0;

 while (1) {
   Serial.println(a);
   a++;
 }
}

If not, could I just insert an empty loop function after this?

floresta

#1
Jan 20, 2011, 03:49 am Last Edit: Jan 20, 2011, 03:51 am by floresta Reason: 1
Quote
Do I have to use setup and loop?
Yes

Quote
Could I leave out the loop function and do this?
No

Quote
If not, could I just insert an empty loop function after this?
Yes

I believe that loop() accomplishes essentially the same thing as:   while (1) { ... }

Don

Charles


Si

You do have to supply both functions. You could do everything in the setup and leave loop empty, and for some apps that would be all that is needed. For example if your app was just a timer that was to start when the reset button was pressed for example.

However, these functions are there as a reminder of how most embedded software is structured.

You set some things up once after reset, and then you have a 'tight' loop where you do things quickly like monitor for a key being pressed, or refresh an LCD display.

So the things in the main 'loop' will be run repeatedly as frequently as possible.

Si.
--
My New Arduino Book: http://www.arduinobook.com

robtillaart

#4
Jan 20, 2011, 06:01 pm Last Edit: Jan 20, 2011, 06:01 pm by robtillaart Reason: 1
In the file main.cpp the setup() and loop() are called this way:

Code: [Select]
#include <WProgram.h>

int main(void)
{
     init();

     setup();
   
     for (;;)
           loop();
       
     return 0;
}


main.cpp can be found at : ~arduino-0021\hardware\arduino\cores\arduino\main.cpp

there is interesting code in the dungeons :)
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Darth Maker

And actually, since the main() function is part of a library, you can overwrite in your code.  Just don't forget to call init() or delays and other built in functions wont work.

Go Up