As soon as you create a new sketch in the Arduino IDE and the window opens, you’ll always see the following basic structure:
But what does this mean? As you might already know, in the Arduino IDE you use the C++ programming language. In this language – just like in all other programming languages – you can define so-called functions.
These actually belong to more advanced programming. However, due to the structure of an Arduino sketch, you can’t avoid understanding functions at least in their basic principles.
With functions, you can structure your code by assigning separate tasks to them. You first define the function according to a fixed pattern. In C++, this looks like the following:
Type Name() {
Code;
}
The Type indicates what “kind” of function it is. In our case, this is the type void
. This means that this function does nothing more than execute the code between the curly braces { }
.
The Name is – that’s right, the name of the function. 😉 In our case, that’s setup
and loop
. Inside the two curly braces comes everything you want these functions to execute.
Here’s a tip right away: Always make sure that every opening brace {
also has a closing counterpart }
. Otherwise, your sketch won’t run. But don’t worry, if you forget a brace, the Arduino IDE will alert you before uploading the sketch.
But what are these two functions good for?
The Setup Function
In this function, you determine what your Arduino should execute once after starting. Here you can define, for example:
- whether a pin sends or receives signals.
- whether an LED should be turned on or off at the beginning of the program.
- that the Serial Monitor should run at a certain speed.
Your Arduino only needs to know all of this once at the beginning of the sketch – so it’s, as the name of the function suggests, the setup.
In the next lesson, you’ll fill the setup function with code. But first, let’s take a look at the loop.
The Loop Function
Unlike the setup, all the code within the loop is constantly repeated. Your Arduino executes it line by line until it reaches the end – and then starts over again from the beginning.
You’ll take advantage of this in the next lesson by using the loop function to make the internal LED of your Arduino blink.