Arduino - Code Structure
Hardware Required
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Basic Structure
Arduino code (also called Arduino sketch) includes two main parts: setup code and loop code.
Setup Code
- Is code in setup() function.
- Executed right after power-up or reset
- Executed only one time.
- Used to initialize variables, pin modes, start using libraries,
Loop Code
- Is code in loop() function.
- Executed right after setup code.
- Executed repeatedly (infinitely).
- Used to do the main task of application
Example
Quick Steps
- Copy the above code and open with Arduino IDE
- Click Upload button on Arduino IDE to upload code to Arduino
- Open Serial Monitor
- See the output on Serial Monitor
As you can see, “This is the setup code” is printed once, but “This is loop code” is printed many times. It means the setup code is executed once, loop code is executed repeatedly. The setup code is executed first.
※ NOTE THAT:
setup() and loop() functions MUST be in Arduino code. If not, an error is generated.
Optional Parts
Apart from setup and loop code, an Arduino sketch can include some of the following parts:
- Block comment: usually used to write some information about the author, the wiring instruction, the license ... Arduino will ignore this part.
- Libraries inclusion: is used to include libraries into the sketch.
- Constant definition: used to define constant
- Global variables declaration
Quick Steps
- Copy the above code and open with Arduino IDE
- Click Upload button on Arduino IDE to upload code to Arduino
- Open Serial Monitor
- See the output on Serial Monitor
We do NOT need to understand code line by line now. We just need to know about code structure. The line-by-line code will be explained in the next tutorials.