Contents
1. Introduction: Master the Language for Communicating with hardware
In Arduino programming, understanding the basic syntax structure is the foundation of writing effective code.
The Arduino language is essentially a simplified version based on C/C++, and its goal was very clear from the beginning of its design: to allow non-programmers to quickly get started with controlling hardware.
2. Variables and Constants
2.1 What is a Variable
A variable, literally, is a value that can change. A variable can store a value, and we can retrieve or modify data through the variable in a program.
For example:
int ledPin = 13; // Declare a variable to store the pin numberWhat this line means is: "I've declared a variable named ledPin with a value of 13." After that, you can use ledPin to refer to the number 13 and control the corresponding pin, instead of writing the number every single time.
Wherein:
intis the data type of a variableledPinis a variable name13is its initial value
2.1.1 Common Data Types
In Arduino, variables must first have their data type declared to inform the compiler what kind of data the variable is intended to store.
Just now int is a data type, which refers to the integer type and is used to store ordinary integers.
Besides, there are several other commonly used data types:
int ledPin = 13; // Suitable for storing integers
float temperature = 36.5; // Suitable for handling data with decimal points, such as temperature and voltage.
bool isPressed = false; // Used to represent true/false / on/off state
char letter = 'A'; // Stores a single character
String name = "ESP32"; // Used to store a string of characters, such as names, prompt messages, etc.We can select appropriate data types as needed to provide each variable with the most suitable "container".
Mini Exercise:
1. Declare an integer variable speed with a value of 100
int speed = 100;
2. Declare a boolean variable isOn with a value of true
bool isOn = true;
2.1.2 Variable Names
Before using a variable, we need to give it a name — this is the variable name, through which we can access or modify the data stored in the variable.
Just as we used earlier:
int ledPin = 13;Here, the ledPin is the variable name. Later, we can use ledPin to represent the number 13 instead of writing the number 13 every time.
So, can variable names be chosen arbitrarily? Obviously not. Variable names must follow their own naming rules so that they can be correctly recognized and processed by the compiler.
The basic naming rules are as follows:
- Can only consist of letters, digits, and underscores
_- For example, both my_variable and var123 are valid, whereas my-variable and var#123 are invalid.
- Cannot start with a number
- For example, variable1 is valid, but
1variableis invalid.
- For example, variable1 is valid, but
- Reserved words or keywords are not allowed, such as
int,if,for,whileand other terms already in use by the system - case-sensitive,
LEDandledare two distinct variables- For example, Total and total are two distinct variables.
- To improve the readability of code, variable names should be able to describe the content or purpose of the data they store.
- For example:
✅speedstands for speed
✅positionXstands for the X-axis coordinate of a position
✅accelerationstands for acceleration
❌a,b,c—— ambiguous meaning, hard to read later
- For example:
2.1.3 Variable Declaration and Assignment
Next, let's formally learn how to declare a variable and assign a value to it.
In Arduino, variable declaration typically consists of three components: data type, variable name, and initial value. This step tells the compiler: I want to create a "container" for storing a specific type of data, specify what its name is, and set the initial value it holds.
For example, the declaration method we used earlier:
int speed = 100;You can also declare a variable first and then assign a value to it:
int speed;
speed = 100;These two writing styles produce the same effect, and which one is more suitable depends on the code structure and personal habits.
2.2 Constants
A "constant" refers to a fixed value; literally, a "constant" is a quantity whose value does not change. The core difference between it and a variable is that: once a value is assigned, it cannot be modified during the execution of the program.
Constants can make programs more stable and easier to understand, and also prevent accidental unintended modifications.
In Arduino, you can use the const keyword to declare a constant:
// const data_type variable_name = variable_value;
const int ledPin = 13;This line of code means: I have declared an integer constant named ledPin with a value of 13, which cannot be modified later. If you try to write:
ledPin = 12;The compiler will throw an error, since constants cannot be reassigned.
3. Operators
Among the variables and constants we discussed earlier, the focus is mostly on "storing data". For a program to actually "come alive", it needs to manipulate these data, such as performing arithmetic operations like addition, subtraction, multiplication and division, comparing values, judging true or false, concatenating strings, and so on.
These operations require the use of —— operators.
An operator is a symbol used to perform operations, such as +, -, *, /, which are arithmetic operators we have long encountered in mathematics. In Arduino programming, there are many other commonly used types of operators, such as relational operators, logical operators, and so on. Each type of operator has its own function and applicable scenarios, and we will give examples to illustrate them one by one later.
3.1 Arithmetic Operators
+(Addition): Add two numbers together.
-(Subtraction): Subtract the second number from the first number.
*(Multiplication): Multiply two numbers.
/(division): Divide the first number by the second number.
%(Modulo): Returns the remainder after dividing two numbers. 15%25 = 0.. ... .15
3.2 Relational Operators
==(Equal): Checks whether two numbers are equal.
!=(Not Equal): Checks whether two numbers are not equal.
>(greater than): Checks whether the number on the left is greater than the number on the right.
<(less than): Checks whether the number on the left is less than the number on the right.
>=(greater than or equal to): Checks whether the number on the left is greater than or equal to the number on the right.
<=(less than or equal to): Checks whether the number on the left is less than or equal to the number on the right.
3.3 Logical Operators
&&(Logical AND): If both conditions are true, the result is true.
||(Logical OR): If at least one of the conditions is true, the result is true.
!(Logical NOT): Performs negation. If the condition is true, the result is false, and vice versa.
3.4 Assignment Operators
=(Assignment): Assign the value on the right-hand side to the variable on the left-hand side.
++(increment operator): Increments the value of a variable by 1
--(decrement): Decrements the value of a variable by 1
+=(Addition Assignment): Adds the value on the right to the variable.
-=(subtraction assignment): Subtract the value on the right from the variable and assign the result to the variable.
4. Expressions
An expression is a piece of code composed of constants, variables and operators, which will produce a result.
We previously categorized operators into arithmetic operators, comparison operators, logical operators, and assignment operators, and each category of operators can form expressions of the corresponding type:
Operator Type | Example Expression | Description | |
|---|---|---|---|
Arithmetic Expression | +, -, *, /, % | a + b | Perform mathematical operations such as addition, subtraction, multiplication and division |
relational expression | ==, !=, >, <, >=, <= | x > 10 | Compare the values, and the result will be true/false |
logical expression | &&, ||, ! | x > 0 && y < 5 !(x == y) | Multi-condition judgment |
assignment expression | =, +=, -=, *=, /=, %= | speed = 100 x *= y | Assign the result to a variable |
So it can be said that: an expression is the actual application scenario of operators.
// Arithmetic expression
int a = 10;
int b = 5;
int result = a + b; // Expression: a + b, the result is 15
// Relational expression: check whether temperature is greater than 30
int temperature = 28;
bool isHot = temperature > 30; // Expression: temperature > 30, the result is false
// Logical expression
int light = 40;
int sound = 20;
bool isQuietAndDark = light < 50 && sound < 30; // Logical AND: true only if both are satisfied
bool isQuietOrDark = light < 50 || sound < 30; // Logical OR: only one needs to be satisfied
bool isNotQuiet = !(sound < 30); // Logical NOT: true becomes false
// Assignment expression
int speed;
speed = 80; // Expression: speed = 80, assigns 80 to speed
speed += 10; // Equivalent to speed = speed + 10Mini Exercise:
1. Determine whether the temperature is between 20 and 30, and use isComfortable to represent it.
bool isComfortable = temperature >= 20 && temperature <= 30;
2. Concatenate two string variables String name = "ESP32" and " is powerful", and save the result to the variable msg.
String name = " ESP32 "
String msg = name + " is powerful";
5. Array
When you need to store a set of data of the same type, arrays come in handy. Unlike a variable that can only hold a single value, an array is a collection of multiple pieces of data of the same type, and each piece of data can be accessed via an index.
5.1 Basic Syntax
data_type array_name[number_of_elements] = {value1, value2, value3, ...};Example:
int ledPins[3] = {2, 4, 7};The meaning of this example is as follows:
- An array named
ledPinsis created; - The array has 3 elements;
- They are the integers 2,4 and 7 respectively;
- We can access them via index, for example:
ledPins[0]indicates that the first pin is 2.
5.2 Accessing Array Elements
Array indices start at 0.
int x = ledPins[1]; // The value of x is 4 (the 2nd element)You can also modify the elements in the array:
ledPins[2] = 13; // Change the third element to 135.3 A Practical Example: Iterating Through Array Elements in Turn
//Define an array
int scores[5] = {85, 90, 78, 92, 88};
void setup() {
Serial.begin(115200);
for (int i = 0; i < 5; i++)
{
int currentScore = scores[i]; // Take one element from the array and assign it to a variable
Serial.println(currentScore); // Output using the variable
}
}
void loop() {
}"Fetch a value from an array → store it in a variable → then use it"
In this example, we define an int type array scores to store 5 scores. In the for loop, we use scores[i]to retrieve each score and assign it to the variable currentScore. The advantage of this approach is that we can perform more flexible operations on each score, such as subsequent judgment, comparison or accumulation processing.