I have searched for an answer and I can only imagine it has to be on this forum somewhere already, but I couldn't find it so apologies in advance because it seems like something that has probably been asked a million times.
Since the setup function is only called once when the arduino is powered on, what is the point of having it? In my mind, functions are only useful when you want to recall a set of instructions more than once or perhaps to group together a set of instructions that provide some return value. Why couldn't whatever code you plan to put inside the setup function just sit on the root level of the sketch file. We already put global variables here so it's not as if code outside of a function won't be parsed, right? Is it the case that the Setup function also does some behind-the-scenes configuring of the arduino, or is it a carry over from more general coding best practices where things should always be inside a function or something like that?
ryancousins:
Since the setup function is only called once when the arduino is powered on, what is the point of having it?
The setup() function was designed into the Arduino system to make things easier for newbie programmers.
Many projects require certain items to be prepared at the start of a program before the repeating part of the program (in the Arduino case the loop() function) takes over.
ryancousins:
That clears up why things like pinMode() have to be done inside setup. Any idea why it's structured this way in the first place?
Power_Broker:
Because C++
It's just how the language works
That's indeed the primary reason, but also because then it would run before the initialization of the Arduino platform. (This happens in main.)
Some Arduino functions rely on the hardware being initialized correctly, so running them before main would result in unexpected behavior.
For example, the following code bricks my Leonardo, because the USB Serial port is never initialized, and it gets stuck in the while loop: