Arduino Nano - Code Structure
Hardware Preparation
1 | × | Arduino Nano | |
1 | × | USB A to Mini-B USB cable | |
1 | × | (Recommended) Screw Terminal Expansion Board for Arduino Nano | |
1 | × | (Recommended) Breakout Expansion Board for Arduino Nano |
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Additionally, some of these links are for products from our own brand, DIYables.
Basic Structure
The Arduino Nano code consists of two sections: the setup code and the loop code. The setup code is executed once when the program starts. The loop code is executed continuously until the program ends.
Setup Code
- Code in the setup() function is executed right after power-up or reset. It is only executed one time and is used for initializing variables, pin modes, and starting to use libraries, etc.
Loop Code
- The loop() function is code that is executed immediately following the setup code. It is repeated indefinitely and is used for the primary purpose of the application.
Example
Detailed Instructions
- Copy the code and open it in the Arduino IDE.
- Click the Upload button to transfer it to the Arduino Nano.
- Open the Serial Monitor.
- Check the output on the Serial Monitor.
You can observe that “This is the setup code” is printed only once, however “This is loop code” is printed multiple times. This implies that the setup code is executed only once, while the loop code is executed repeatedly. The setup code is executed first.
※ NOTE THAT:
The setup() and loop() functions MUST be included in Arduino Nano code. Failing to do so will result in an error.
Optional Parts
In addition to the setup and loop code, an Arduino Nano sketch may include:
- A block comment, which is typically used to provide information about the author, wiring instructions, license, etc. Arduino Nano will ignore this part.
- Including libraries in the sketch.
- Declaring global variables.
Detailed Instructions
- Copy the code and open it with the Arduino IDE.
- Click the Upload button on the Arduino IDE to compile and upload the code to the Arduino Nano.
- Open the Serial Monitor.
- Check out the output on the Serial Monitor.
We do not have to comprehend code line-by-line at present. We just need to be aware of the code structure. The line-by-line code will be elucidated in the upcoming tutorials.