2. Arduino Basics
The Arduino programming language uses C-like syntax and is designed to make programming easier for beginners to learn and understand. Similar to C, Arduino syntax is structured and includes common programming constructs such as if statements, for loops, functions, and variables.
Compared with C, Arduino syntax is simpler and easier to understand, and it pays more attention to human-computer interaction. For example, Arduino often uses natural-language terms such as "pin" and "serial" as keywords. In addition, Arduino provides many built-in functions in the programming environment, making programming easier.
Arduino's syntax is designed so users can get started quickly without extensive professional programming knowledge. With only a few basic syntax rules and commonly used functions, you can begin writing code easily. Its easy-to-understand syntax and logic structure also make Arduino very suitable for building simple IoT devices, robots, and other engineering projects. The following sections describe the main parts and basic syntax of Arduino programming.
2.1 Structure
An Arduino program, called a "sketch", usually includes two main functions:
setup(): This function runs once when the program starts. It is usually used to initialize pin modes, start libraries, and so on.loop(): This function runs repeatedly aftersetup()has executed. It is used for the main program logic. A new project is usually created from a template containingsetup()andloop().
2.2 Variables and Data Types
Arduino supports standard C/C++ data types such as int, float, char, and boolean. Variables must be declared before use and can be assigned a value when declared.
| Type | Storage Size | Value Range | Precision |
|---|---|---|---|
| char | 1 byte | -128 to 127 or 0 to 255 | |
| unsigned char | 1 byte | 0 to 255 | |
| signed char | 1 byte | -128 to 127 | |
| int | 2 or 4 bytes | -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 | |
| unsigned int | 2 or 4 bytes | 0 to 65,535 or 0 to 4,294,967,295 | |
| short | 2 bytes | -32,768 to 32,767 | |
| unsigned short | 2 bytes | 0 to 65,535 | |
| long | 4 bytes | -2,147,483,648 to 2,147,483,647 | |
| unsigned long | 4 bytes | 0 to 4,294,967,295 | |
| float | 4 bytes | 1.2E-38 to 3.4E+38 | 6 digits |
| double | 8 bytes | 2.3E-308 to 1.7E+308 | 15 digits |
| long double | 16 bytes | 3.4E-4932 to 1.1E+4932 | 19 digits |
Example:
int ledPin = 13; // Declare an integer variable named 'ledPin' and set it to 13
float sensorValue = 0.0; // Declare a float variable named 'sensorValue' with an initial value of 0.0
bool isButtonPressed = false; // Declare a Boolean variable named 'isButtonPressed' with an initial value of false
char receivedChar = 'A'; // Declare a character variable named 'receivedChar' and set it to 'A'2
3
4
Users often forget the value range when using the
chartype, which can cause an infinite loop. See the code below:cchar number = 0; for(number = 0; number < 1000; number++ ) { ... }1
2
3
4
5
The code above requires number to increment to 1000 before the for loop ends, but the char range is 0 to 255, so the loop cannot end.
2.3 Functions
A function is a reusable block of code that encapsulates a specific operation and can be called in a program. The Arduino programming language provides many built-in functions for common hardware operations and data processing. Common built-in functions will be explained in later chapters. Arduino also supports custom functions. A function includes a return type, function name, and parameter list. The following example implements a simple digital counter to demonstrate function calls in Arduino.
First, define a global variable counter to store the current counter value:
int counter = 0;Then define two functions, inc() and subtract(), to increment the counter and perform subtraction:
// Function definition: no return value and no parameters
void inc()
{
counter=counter+1;
}
// Function definition: with return value and input parameters
int subtract(int a, int b)
{
int sum = a - b;
return sum;
}2
3
4
5
6
7
8
9
10
11
12
Note that inc() has no return value and no parameters because it directly operates on the global variable counter. Now that the two functions have been defined, they can be called elsewhere in the program to increment or decrement the counter.
For example, in setup(), you can call inc() to initialize the counter to 1:
// Run only once
void setup()
{
// Initialize the serial port
Serial.begin(115200);
// Increment counter by 1. Because setup runs only once, the counter is initialized to 1.
inc();
}2
3
4
5
6
7
8
In loop(), you can check the button state and call inc() or subtract() to increment or decrement the counter:
// Loop continuously
void loop()
{
// Check whether the button is pressed
if(digitalRead(BUTTON_PIN) == HIGH)
{
inc(); // Button pressed, counter plus 1
}
else
{
subtract(counter, 1); // Button not pressed, counter minus 1
}
// Display the counter value on the serial port
Serial.println(counter);
// Delay for 100 ms
delay(100);
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In this example, inc() and subtract() are called to increment and decrement the counter, and Serial.println() outputs the counter value to the serial port.
2.4 Control Structures
Arduino supports standard C/C++ control structures such as if, else, switch, for, while, and do-while. These structures are used for conditional decisions and loops.
- Conditional statement (
if-else): This structure executes different code branches according to a given condition.
if (condition) {
// Code block 1
} else {
// Code block 2
}2
3
4
5
When the condition is true, code block 1 runs. When the condition is false, code block 2 runs. Example:
int value = 0;
if( value == 0 )
{
value = 10;
}
else
{
value = 20;
}2
3
4
5
6
7
8
9
10
After this code runs, the value of value is 10.
- Loop statements (
for,while, anddo-while): These structures repeatedly execute a section of code until a specific condition is met.
for (initialization; loop condition; update expression) {
// Code block
}
while (condition) {
// Code block
}
do {
// Code block
} while (condition);2
3
4
5
6
7
8
9
10
11
Example:
int value = 0;
//----------------------------------
for (value = 2; value > 0; value--)
{
// This will run twice
}
//----------------------------------
while (value < 5)
{
value++;// This will run five times
}
//----------------------------------
do
{
value--;// This will run five times
} while (value > 0);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- Switch statement (
switch-case): Used to execute different code blocks for different cases.
switch (variable) {
case value1:
// Code block 1
break;
case value2:
// Code block 2
break;
// ...
default:
// Default code block
break;
}2
3
4
5
6
7
8
9
10
11
12
2.5 Libraries
Arduino provides many ready-to-use libraries for implementing specific functions or interacting with specific hardware. A library can be included in a program with the #include directive, after which the functions in the library can be used.
Arduino is an open-source electronics platform that provides an easy-to-use hardware and software environment for building interactive projects and prototypes. Arduino libraries are collections of software components that help developers write code more conveniently. These libraries provide various functions and modules that users can use directly in Arduino projects without writing low-level code from scratch. The following are some commonly used Arduino libraries:
| No. | Name | Purpose |
|---|---|---|
| 1 | Wire library | Used for I2C two-wire serial bus communication |
| 2 | SPI library | Used for SPI serial peripheral interface communication |
| 3 | Serial library | Used for serial communication, such as communication with a computer or other devices |
| 4 | WiFi library | Used to connect to a network over Wi-Fi |
| 5 | Servo library | Used to control servo motors |
| 6 | SD library | Used to read and write SD card storage |
| 7 | Stepper library | Used to control stepper motors |
| 8 | DHT library | Used to communicate with DHT series temperature and humidity sensors |
These are only a small portion of Arduino libraries. In addition to official libraries, many third-party libraries developed by the Arduino community are available. When using an Arduino library, you usually include the library header file at the top of the code with the #include directive, then use the functions provided by the library.
2.6 Simple Application Verification
The following is a simple Arduino program example. It repeatedly blinks an LED connected to output pin GPIO13:
// Define a constant named ledPin of type int and initialize it to 13
const int ledPin = 13;
// Run only once
void setup() {
// Call pinMode to set the ledPin pin to OUTPUT mode
pinMode(ledPin, OUTPUT);
}
// Loop continuously
void loop() {
// Call the built-in digitalWrite function to output HIGH on ledPin
digitalWrite(ledPin, HIGH);
// Call the built-in delay function and delay for 100 ms
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17