3. Basics of Arduino Programming
3.1 Introduction to Arduino Programming Language
The Arduino programming language is based on C/C++, which is a general-purpose, structured programming language. This means that Arduino inherits the syntax and structure of C and C++. It utilizes specific functions and libraries that encapsulate the low-level details of hardware interaction, allowing developers to implement basic functionalities without needing a deep understanding of the underlying hardware. This makes it easy to control various hardware features of Arduino. A key feature of the Arduino programming language is its simplicity, enabling beginners to quickly get started. For example, in other controllers, lighting an LED requires configuring the clock, pins, modes, outputs, and other operations. In Arduino, however, you can accomplish this with just two lines of code.
3.2 Common Arduino Libraries and Functions
❓What are a library and a function?
Libraries and functions are common concepts in programming, and they are used in various programming languages, including the C/C++ language used by Arduino.
- Library: A library is a collection of functions that can be called as a whole after being encapsulated. Libraries usually contain some common functions to implement specific programs. For example, Arduino contains some standard libraries that provide common functions for interacting with hardware, allowing developers to easily control LED lights, read sensors, etc. Thanks to the development of the Arduino open source community, many makers have independently submitted their own libraries, which we can directly download and apply.If you want to control a small car, you would need to configure the pins and set up how the car moves forward, backward, and turns. This requires a lot of code. However, if someone in the maker community has provided a library, you can quickly complete the setup by following the library's documentation.The pin initialization might only require one line of code, and the commands for moving the car forward, backward, and turning could also be achieved with just one line each.
- Function: A function is a fundamental unit in programming; it is a block of code that can be repeatedly called to perform a specific task. Functions have a name, which allows them to be invoked within a program. They can accept input parameters and return a result. In Arduino, many predefined functions are provided in the form of libraries, enabling developers to call these functions directly without writing low-level code.
To sum up, libraries and functions exist to improve the reusability and simplicity of code. By using libraries and functions, developers can write programs more efficiently while reducing errors and code redundancy. In Arduino development, rational use of libraries and functions can greatly simplify the interaction with hardware and improve development efficiency.
The Arduino IDE comes with many built-in libraries that provide a variety of commonly used functions, making it easy for developers to utilize various hardware features. For example, the pinMode()
function is used to set the mode of a digital pin (input or output), the digitalWrite()
function is used to write a value (HIGH or LOW) to a digital pin, the digitalRead()
function is used to read the voltage level from a digital pin.
There are also third-party libraries that provide more complex functionalities. For example, the Servo
library is used to control servos, and the IRremote
library is used to control infrared remote devices.
3.3 Data Types and Variables in Arduino
In Arduino programming, data types and variables are fundamental concepts that determine how data is stored and processed. The Arduino programming language supports all the basic data types from C/C++, such as int, float, and char. Additionally, Arduino defines some special data types, such as byte
(an 8-bit unsigned integer) and word
(a 16-bit unsigned integer).
📌Data Types
Data types are used to declare variables, function parameters, and function return values. In Arduino programming, the following data types are primarily used:
- byte: An 8-bit unsigned integer, ranging from 0 to 255. Commonly used for reading the state of digital pins or representing color values.
- int: A 32-bit integer, which may vary depending on the platform and compiler, typically ranging from -2147483648 to 2147483647.
- float: A 32-bit floating-point number, used in situations requiring decimal values.
- double: A 64-bit floating-point number, providing higher precision and range than float.
- char: An 8-bit character, used to store ASCII values.
- String: Used for storing and manipulating text data.
📌Variables:
Variables are used to store data. In Arduino programming, you can declare a variable to store data of a specific type. Here are some key points about Arduino variables:
- Declaring Variables: To declare a variable, you need to specify its data type and a name. For example, to declare an integer variable named
myVariable
, you can useint myVariable
. - Initializing Variables: You can specify an initial value when declaring a variable. For instance,
int myVariable = 10
declares an integer variable namedmyVariable
and initializes it to 10. - Scope: The scope of a variable determines where it is accessible. In Arduino, variable scope can be local (within a function) or global (throughout the entire program).
- Constants: Variables declared with the
const
keyword are constants, meaning their values cannot be modified. For example,const int myConstant = 20;
declares a constant integer. - Variable Lifetime: The lifetime of a variable depends on its scope. Variables declared within a function exist only during their lifetime, while global variables persist for the duration of the program.
- Implicit Type Conversion: In some cases, Arduino performs implicit type conversion. For example, when a byte type value is involved in arithmetic with an int type value, Arduino automatically converts the byte to int.
Variables are used to store data. In Arduino, you can declare a variable to hold a value. For example, you can declare an int
type variable to store an integer. Here’s an example: we all know what a light is; when we mention a light, we have a clear image of it, and its physical form is its carrier. But what about in a computer or program? How do we tell the computer that this thing is a light? In programming, we can define a variable to encapsulate the concept of a light. For instance, if I define a variable called LED
, we can use it for any operations related to the light. To turn the light on, we would use LED.on()
, and to turn it off, we would use LED.off()
.
The concepts of data types and variables will be further explained in the upcoming examples and validations.
3.4 Control Structures and Flow Control
Arduino programming language supports various control structures and flow control statements, such as if-else statements, switch statements, for loops, and while loops. In programming, control structures and flow control are essential for implementing specific logic and algorithms; they dictate the order of code execution and conditions. These control structures and flow control statements enable you to write more complex programs.
Here are some commonly used control structures and flow control mechanisms in Arduino programming: Control Structures:
Control structures determine the execution path of the code. In Arduino programming, the main control structures include:
- if statement: The if statement is used to execute a block of code based on a condition. If the condition condition is true, the code inside the block will be executed; if it is false, the code will be skipped. The syntax is as follows:
if(condition)
{
// Code to execute when the condition is true
}
2
3
4
✔In programming and code, "true" and "false" typically refer to the two basic states in boolean logic, corresponding to the binary system's 1 and 0. Any non-zero value is considered true, while only a value of zero is considered false.
In programming:
- true: Indicates that a condition is met, an expression is valid, or the result of an operation is as expected. For example, when comparing two values, if they are equal, the comparison results in
true
. - false: Indicates that a condition is not met, an expression is invalid, or the result of an operation does not meet expectations. If the two values being compared are not equal, the comparison results in
false
.
These boolean values are very useful for controlling program flow, such as in if
statements, while
loops, and conditional operators.
✔For example, you have a button and a light. You're required o use Arduino to make the light turn on when the button is pressed. How would you implement this? You can use an if statement like this:
if ( buttonPressed )
{
lightOn
}
2
3
4
This is how if statement is implemented.
- if-else statement: The if-else statement allows you to execute two different blocks of code based on a condition. The syntax is as follows:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
2
3
4
5
6
7
8
✔Now, continuing with the previous example, you're required to implement a setup where pressing the button turns the light on, and releasing the button turns the light off. You can use an if-else statement like this:
if ( buttonPressed )
{
Turn the light on
}
else
{
Turn the light off
}
2
3
4
5
6
7
8
The "else" in this context executes when the condition in the if statement is not met, which is similar to saying "otherwise" in English.
- switch statement: The switch statement is used to execute different code blocks based on various conditions. It is typically used when there are multiple options. The syntax is as follows:
switch ( variable )
{
case value1:
// Code executed if variable equals value1
break;
case value2:
// Code executed if variable equals value2
break;
case n:
...
default:
// Code executed when none of the cases match
}
2
3
4
5
6
7
8
9
10
11
12
13
✔For example, you're required to determine the state of a light based on the voltage level: the light should blink slowly at 5V, blink quickly at 3V, and stay on at 0V. You can implement this functionality using a switch statement ike this:
switch ( voltageValue )
{
case 5:
Light blinks slowly
break;
case 3:
Light blinks quickly
break;
case 0:
Light stays on
default:
Light is off
}
2
3
4
5
6
7
8
9
10
11
12
13
- for loop: The for loop is used to repeat a section of code a specific number of times, until a certain condition is no longer met. The syntax is as follows:
for (initialization; condition; update)
{
// Code to be executed in the loop
}
2
3
4
initialization:
- This is a block of code that runs only once before the loop starts. It's typically used to set initial values or states needed for the loop.
- For example,
int i = 0;
initializesi
to 0 in a counting loop.
condition:
- This is a boolean expression that gets evaluated at each iteration of the loop.
- If the condition is true, the loop body continues to execute. If the condition is false, the loop will stop.
- For example, in a counting loop, the condition might be
i < 10
, meaning the loop continues as long asi
is less than 10; it will stop when i is less than 10; it will stop when i is 10 or greater.
update:
- This is the code block executed at the end of each iteration of the loop. It's typically used to update the value of the loop control variable.
- For example, in a counting loop, the update might be
i++
, meaning that after each iteration, the value ofi
increases by 1.
✔For example, if you want to output debugging data continuously for 10 times, you can implement this simply and quickly like this:
for (int i = 0; i < 10; i++)
{
//Output debugging data
}
2
3
4
int i = 0;
is the initialization, setting the variablei
to 0.i < 10
is the condition; the loop will continue as long asi
is less than 10.i++
is the update part, which increments the value ofi
after each iteration.
- while loop: The while loop is used to repeatedly execute a block of code as long as the condition is true. The syntax is as follows:
while (condition)
{
// Code to be executed in the loop
}
2
3
4
Continuing with the previous example, you could write it like this:
int i = 10;
while( i )
{
//Output debug data
i = i - 1;
}
2
3
4
5
6
- do-while loop: The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once before checking the condition. The key difference from the while loop is that the execution happens first, and then the condition is evaluated. The syntax is as follows:
do {
// Code to be executed in the loop
} while (condition);
2
3