The information in this chapter is optional. Unless you are really interested in how things work, skip to the next chapter.
Every C++ source program for a microcontroller has the following basic form:
int main(void)
{
// Your code goes here
}
Assembly language startup code like this
calls main() after the microcontroller hardware has been
initialized just enough to run C++ code.
The Arduino development environment hides main() from you. The
hidden Arduino C++ main program has a form similar to the following:
int main(void)
{
// Hidden initialization code goes here
setup(); // Call Arduino sketch setup() function
for (;;) loop(); // Call Arduino sketch loop() function
}
When you create a new program using the Arduino IDE (using File →
New Sketch) you get the following code, which is called an Arduino Sketch:
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
By convention, and enforced by the Arduino IDE, sketch files are saved with
a .ino file extension.
The hidden Arduino main program described above calls setup()
in your sketch one time whenever you upload it to the microconroller
code memory and then also whenever the microcontroller powers up or resets.
After setup() has been called, the Arduino main program starts
calling loop() repeatedly from an infinite loop.
You will need to put data definitions before setup(),
initialization code in setup, and application code
in loop(), like the following:
int counter; // Define a counter variable
void setup(void)
{
counter = 0; // Initialize the counter variable
}
void loop(void)
{
counter = counter + 1; // Increment the counter variable
}
Notice that the Arduino IDE sketch skeleton uses the One True Brace
Style for the opening brace character while I will always use the
more readable Allman Style
with two space indentation.