3.1 Structure of an Arduino Program

Introduction
Arduino programming fundamentals are the basic concepts and techniques used to write programs, called sketches, for Arduino boards. Arduino programs are mainly written in a simplified version of C/C++ and are used to control electronic components such as LEDs, sensors, motors, displays, buzzers, and communication modules.
Understanding programming fundamentals enables a learner to create programs that can read input, process information, make decisions, repeat operations, and control output devices. This unit introduces the major elements required to develop Arduino applications.
3.1 Structure of an Arduino Program
An Arduino program is called a sketch. A basic Arduino sketch contains two important functions:
- setup()
- loop()
3.1.1 The setup() Function
The setup() function runs once when the Arduino is powered on, reset, or restarted. It is normally used to configure pins, start serial communication, initialize sensors, and prepare other components.
Example:
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
}
In this example:
- pinMode(13, OUTPUT) configures pin 13 as an output.
- Serial.begin(9600) starts serial communication at 9600 bits per second.
3.1.2 The loop() Function
The loop() function runs repeatedly as long as the Arduino is powered.
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
The program turns an LED on for one second and off for one second continuously.
3.1.3 Comments
Comments are notes written in a program to explain what the code does. They are ignored by the Arduino compiler.
Single-line comment:
// Turn the LED on
Multi-line comment:
/*
This program controls
an LED.
*/
3.1.4 Statements and Semicolons
Most Arduino programming statements end with a semicolon ;.
int ledPin = 13;
digitalWrite(ledPin, HIGH);
The semicolon tells the compiler that a statement has ended.


