Indice
- 8.1 Arduino Variables and Data Types Explained
- 8.2 Arduino Operators and Conditions: Making Decisions with if / else
- 8.3 Arduino Loops: for, while and the loop() Function Explained
- 8.4 Arduino Functions: How to Create and Use Your Own Functions
- 8.5 Arduino Comments: How to Write Clear, Readable Code
- 8.6 Storing and Updating State in Arduino: Toggle an LED with a Button
- 8.7 Arduino millis() vs delay(): How to Manage Time in Your Programs
- 8.8 How to Debug an Arduino Program: Finding and Fixing Errors
- Coming up in the next chapter...
8.1 Arduino Variables and Data Types Explained
In the previous chapters we’ve written several programs (or sketches, as they’re often called in the Arduino world) to control LEDs, read sensors and display information on the LCD screen. Along the way we’ve already been using variables, even if we haven’t yet looked closely at how they really work.
A variable is a space in memory where the program can store a value and use it while it runs. Think of it as a small container with a name on it, so that we can retrieve the value inside and change it whenever we need to.
For example, in the light sensor program we used this statement:
int lightValue = analogRead(A0);
With this statement, Arduino reads the analog value present on pin A0 and stores it in the variable lightValue. That way we can use the result in other statements, for example to show it on the display or to compare it with a threshold.
Declaring a variable
To create a variable, we need to give two key pieces of information: the data type it will hold and the name we want to give it.
For example:
int temperature = 25;
In this statement:
- int is the data type;
- temperature is the name of the variable;
- 25 is the initial value assigned to the variable.
This is known as declaring and initialising (US: initializing) the variable.
You can name a variable whatever you like, as long as you follow the rules of the language. It’s good practice to pick names that clearly describe what the value means, such as lightValue, distance or buttonState.
Where to declare variables
As we’ve seen in many of the earlier programs, a variable can be declared at the very moment you first give it a value, as in the statement int lightValue = analogRead(A0);. It’s convenient, widely used, and perfectly fine for short programs and for temporary variables – that is, the ones that are only needed inside a single function.
As programs get longer and more complex, though, it’s a good habit to declare your most important variables at the top of the program, giving each one a starting value straight away: 0 for numbers, false for Boolean variables and an empty text for alphanumeric (text) variables – we’ll meet those shortly. This is especially useful for pins, thresholds and any variable that has to hold on to a piece of information from one run of loop() to the next.
There are two benefits:
- Finding your variables easily. If your program isn’t working and you need to hunt down the bug (this is called debugging), having all your variables listed in one place – ideally with a short comment next to each one – lets you see at a glance which values the program uses and check them one at a time.
- Avoiding unpredictable values. A variable declared without an initial value isn’t necessarily zero: it can contain a random value left over in Arduino’s memory. Always initialising your variables helps you avoid odd behaviour that can be very hard to track down.
Here’s an example of a program organised this way:
// --- Pins used ---
const int ledPin = 13;
// --- Thresholds and fixed values ---
const int lightThreshold = 500;
// --- State variables ---
int lightValue = 0; // Last sensor reading
bool ledOn = false; // Current state of the LED
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
lightValue = analogRead(A0);
// ...
}
You don’t have to apply this rule to every single variable: a counter that’s only used inside a for loop, for example, can be declared right where it’s used. What matters is to choose a rule and stick to it: variables that describe the overall behaviour of the program go at the top, well commented, while temporary ones go where they’re needed – but always with a starting value.
One more thing to keep in mind: variables declared at the top of the program, outside setup() and loop(), stay in memory for as long as the program runs. The Arduino UNO R3 has very little RAM (just 2 KB), so it’s best to keep this spot for the variables that really need it.
The main data types
Not all variables hold the same kind of information, which is why Arduino offers several data types, each suited to particular situations.
Let’s look at the ones we’ll use most often in our projects.
The int type
The int type is used to store integers, i.e. whole numbers with no decimal part.
For example:
- int distance = 30;
- int lightValue = 650;
These variables can hold whole numbers that are handy for representing a distance in centimetres (US: centimeters), an analog reading or a value used in a condition.
On the Arduino UNO R3, which uses the ATmega328P microcontroller, an int variable takes up 2 bytes and can hold values from -32768 to 32767.
The float type
The float type lets you store numbers with a decimal part, known as floating-point numbers.
For example:
- float temperature = 23.5;
- float distance = 18.7;
It comes in handy when working with measurements that need decimal values, such as some temperatures or calculated distances.
On the Arduino UNO R3, a float takes up 4 bytes. Decimal values are stored with limited precision, so they shouldn’t be treated as perfectly exact in every calculation.
Note: in Arduino code, decimals are written with a point, not a comma. So you write 23.5, not 23,5.
The bool type
The bool type, short for Boolean, can store only two values: true and false.
For example:
bool objectDetected = false;
This variable could tell us whether a sensor has spotted an object: true means the object has been detected, while false means it hasn’t.
The bool type is especially useful for representing the state of a system, such as an LED being on or off, or a device being active or inactive.
The long type and the unsigned keyword
Besides the data types we’ve already seen, Arduino also offers long, which is useful when you need to store whole numbers bigger than an int can hold.
On the Arduino UNO R3, which uses the ATmega328P microcontroller, int and long take up different amounts of memory:
- int takes up 2 bytes and can represent whole numbers from −32,768 to 32,767.
- long takes up 4 bytes and can represent whole numbers from −2,147,483,648 to 2,147,483,647.
The keyword unsigned, which means without a sign, can be used with some numeric types to say that the variable will only ever hold non-negative values. That way, using the same amount of memory, you can represent larger positive numbers.
For example, on the Arduino UNO R3:
- unsigned int takes up 2 bytes and can hold values from 0 to 65,535.
- unsigned long takes up 4 bytes and can hold values from 0 to 4,294,967,295.
Here’s an example:
int temperature = -5;
unsigned long duration = 25000;
The first variable can even represent a negative temperature. The second stores a duration in microseconds and, since it never needs to be negative, uses the unsigned long type.
This data type is particularly useful when you’re measuring time intervals or working with counters that can reach very high values. For example, Arduino uses unsigned long for the millis() function, which returns the number of milliseconds that have passed since the board was powered up.
Remember: choose the data type according to the kind and range of values you need to store. Not every variable needs to hold big numbers, and not every variable needs to be able to go negative.
Alphanumeric (text) variables: char and String
So far we’ve only stored numbers and true/false values. In our projects, though, we’ll often need to handle text as well: a message to show on the LCD display, a sentence to send to the serial monitor, the name of a sensor. That’s what Arduino’s alphanumeric variables are for: they can hold letters, digits and symbols.
The two main types are char and String.
The char type
The char type stores a single character: a letter, a digit or a symbol. It takes up 1 byte. The character is written between single quotes:
char letter = ‘A’;
char symbol = ‘#’;
The String type
The String type stores text of any length, i.e. a sequence of characters. Text is written between double quotes:
String message = “Bright light”; String sensorName = “”;
Note that String is written with a capital S, because Arduino is case-sensitive. To initialise an empty text variable, use two double quotes with nothing in between (“”), not a space: a space is a character in its own right.
A String variable can be printed to the serial monitor, and it can be joined to other text or to numbers:
String message = “Light value: “;
int lightValue = 650;
Serial.println(message + lightValue);
In this case, the serial monitor displays Light value: 650.
Watch out for the two kinds of quotes. ‘A’ (single quotes) is a character of type char, while “A” (double quotes) is a piece of text. Mixing them up is a very common mistake when you’re starting out.
A tip for the Arduino UNO R3. String variables are very handy, but they manage memory dynamically and, with the Arduino UNO R3’s tiny 2 KB of RAM, heavy use can make a program unstable. They’re perfectly fine for our projects, as long as you avoid constantly creating and changing very long pieces of text inside loop().
Changing the value of a variable
A variable can change value while the program is running. Take this example:
int counter = 0;
void setup() {
}
void loop() {
counter = counter + 1;
delay(1000);
}
Every time the loop() function runs, the value of counter goes up by one. After one second it’s 1, after two seconds it’s 2, and so on.
In the statement:
counter = counter + 1;
the = symbol stands for assignment. Arduino takes the current value of counter, adds 1 and stores the new result in the same variable.
This statement is different from a mathematical equation: it tells the program to work out the value on the right of the symbol and assign it to the variable on the left.
Constants: values that never change
Sometimes we want to use a value that has to stay fixed while the program runs. To do that, we can declare a constant using the keyword const.
For example:
const int lightThreshold = 500;
This tells Arduino that lightThreshold is an integer value that the program mustn’t change after it has been initialised.
Constants are handy for reference values, such as the threshold above which an LED should switch on, or the minimum distance we want to use in a project.
Using a descriptive name instead of a number written straight into your statements makes the program easier to read and makes later changes simpler.
Choosing the right data type
When we create a variable, it’s important to pick a data type that suits the information we want to store.
Here are a few simple rules to remember:
- we use int for whole numbers;
- we use float for numbers that may have a decimal part;
- we use bool to represent true or false conditions;
- we use char for a single character and String for text;
- we use const when a value has to stay fixed after initialisation.
In our Arduino programs, variables let us hold sensor readings, count events, remember the state of devices and make decisions based on the values we’ve acquired.
For convenience, here’s a summary of all the variable types you can use on the Arduino Uno. Some of them haven’t been explained yet, but we’ll cover them when the time comes.
| Data type | Size | Description |
|---|---|---|
| char | 1 byte | Container for characters and alphanumeric values (e.g. ‘a’, ‘b’, ‘1’, etc.) |
| bool | 1 byte | Container for Boolean values (e.g. true, false) |
| int | 2 bytes | Container for whole numbers in the range -32,768 to 32,767 |
| unsigned int | 2 bytes | Container for unsigned whole numbers in the range 0 to 65,535 |
| long | 4 bytes | Container for whole numbers in the range -2,147,483,648 to 2,147,483,647 |
| unsigned long | 4 bytes | Container for unsigned whole numbers in the range 0 to 4,294,967,295 (2^32 − 1) |
| float | 4 bytes | Container for floating-point numbers (numbers with decimals) in the range 3.4028235E+38 to -3.4028235E+38 |
| double | 4 bytes | Container for floating-point numbers (numbers with decimals) in the range 3.4028235E+38 to -3.4028235E+38 |
| String | Variable | Container for text (e.g. “Resistance”) |
In the next section, we’ll take a closer look at operators and conditions, learning how to compare the values of variables and combine several conditions to decide how our program should behave.

8.2 Arduino Operators and Conditions: Making Decisions with if / else
n Arduino programs, it’s often not enough just to read a value from a sensor: you also need to compare it with another value and decide what to do based on the result. For example, we might turn on an LED when the light level goes above a certain threshold, or trigger a signal when an object gets too close.
To do this, we use operators and conditions.
Arithmetic operators
Arithmetic operators let you do calculations with numeric values.
The main ones are:
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 6 / 3 | 2 |
| % | Remainder (modulo) | 7 % 2 | 1 |
The % symbol returns the remainder of a division (it’s known as the modulo operator). For example, dividing 7 by 2 gives 3 with a remainder of 1, so 7 % 2 returns 1. This operator can come in handy for telling even numbers from odd ones, or for carrying out an action at regular intervals.
It’s important to remember that when you divide one integer by another integer, the result is calculated as an integer. For example:
int result = 5 / 2;
Here, result is 2, because the decimal part is thrown away. If you need a result with a decimal point, you can use the float type, and at least one of the values must be written as a decimal number:
float result = 5.0 / 2;
Here, result is 2.5.
Comparison operators
Comparison operators let you check how two values relate to each other. The result of a comparison is always a Boolean value, i.e. true or false.
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | temperature == 25 |
| != | Not equal to | temperature != 25 |
| > | Greater than | distance > 30 |
| < | Less than | distance < 30 |
| >= | Greater than or equal to | lightValue >= 500 |
| <= | Less than or equal to | lightValue <= 500 |
Suppose we have a variable called lightValue that holds the reading from the light sensor. We can check whether the value is above 500 by writing:
lightValue > 500
If the reading is 700, the comparison is true. If the reading is 300, the comparison is false.
Watch out for the difference between = and ==. The = symbol assigns a value to a variable, while == compares two values.
int number = 10; // Assigns 10 to the variable
number == 10 // Checks whether number is equal to 10
Mixing up these two symbols is a very common mistake when you’re starting out in programming.
Conditions: deciding what to do with if and else
We’ve already used the if statement in the program that controlled an LED with a button. Now we can apply the same principle to sensor readings.
The if statement runs a block of code only when a condition is true. With else, we can say what to do when the condition is false.
As an example, let’s go back to the light sensor connected to analog input A0 and the LED connected to pin 13:
const int lightThreshold = 500;
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
int lightValue = analogRead(A0);
if (lightValue > lightThreshold) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
delay(100);
}
The program reads the sensor and compares the value it gets with the threshold, which is set to 500. If the reading is above 500, it turns the LED on; otherwise, it turns it off.
The threshold has been declared with const because it’s a value we want to keep fixed while the program runs. Of course, you can change it in the code to experiment with different behaviours.
Remember that, with the sensor circuit described in chapter 6, more light generally gives a higher reading. With a different wiring, though, the relationship could be the other way round.
Combining several conditions (logical operators AND, OR, NOT)
Sometimes a single condition isn’t enough. For example, we might want to turn on an LED only when the sensor value is above a threshold and a button is pressed.
To combine conditions, we use logical operators:
- && means AND: both conditions must be true.
- || means OR: it’s enough for at least one of the conditions to be true.
- ! means NOT: it reverses the logical value, turning true into false and vice versa.
Here’s an example with a light sensor and a button:
const int lightThreshold = 500;
void setup() {
pinMode(2, INPUT);
pinMode(13, OUTPUT);
}
void loop() {
int lightValue = analogRead(A0);
int buttonState = digitalRead(2);
if (lightValue > lightThreshold && buttonState == HIGH) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
}
In this program, the LED turns on only if the sensor reading is above 500 and the button is pressed. If even one of the two conditions is false, the LED stays off.
To see the difference between && and ||, imagine we used this instead:
if (lightValue > lightThreshold || buttonState == HIGH)
In this case, the LED turns on if the light level goes above the threshold or if the button is pressed. Both conditions don’t need to be true.
The ! operator can be used to negate a condition. For example, !(buttonState == HIGH) is true when the button is not pressed. In many cases it’s simpler to write buttonState == LOW directly, but knowing about negation will be useful in more complex programs.
Why operators matter in robotics
Operators and conditions let Arduino react to what’s going on around it. Without these statements, the board could keep reading its sensors all day long, but it wouldn’t be able to choose how to behave based on the values it measures.
In the final project, we’ll use exactly this principle to compare the distance detected by a sensor with a preset threshold. For example, we can decide that an object is close enough when the distance is less than 30 centimetres.
In short, operators are for doing calculations and comparisons, while conditions let the program choose which statements to run. In the next section, we’ll see how to repeat operations using loops, so you don’t have to write the same statements over and over.

8.3 Arduino Loops: for, while and the loop() Function Explained
In Arduino programs, plenty of operations need to be repeated again and again. For example, we might want to read a sensor’s value continuously, make an LED blink (or flash) or check whether a button has been pressed.
We could write the same statements over and over, but the program would get long and hard to modify. To avoid that, we use loops: structures that let us repeat one or more statements.
The Arduino loop() function
In the previous chapters we met two fundamental Arduino functions: setup() and loop().
The setup() function runs only once, when the board is powered up or reset. It’s used, for example, to configure the pins and initialise the LCD display.
The loop() function, on the other hand, runs over and over for as long as the Arduino stays on. When it reaches the end of its block of statements, it starts again from the beginning.
Let’s look at this simple program:
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
The statements inside loop() run one after another: the LED turns on, stays on for a second, turns off and stays off for a second. When the sequence ends, Arduino starts again and repeats everything. (This is essentially the classic Arduino Blink sketch.)
So even though we haven’t written an explicit loop such as for or while, the program is already repeating operations thanks to loop().
The for loop
The for loop is useful when we know how many times we want to repeat an operation.
Its general structure is:
for (initialisation; condition; update) {
// Statements to repeat
}
The three parts inside the round brackets (US: parentheses) each do a different job:
- Initialisation: sets the starting value of a variable used as a counter.
- Condition: decides whether the loop should keep going.
- Update: changes the counter after each repetition.
Here’s a concrete example:
for (int counter = 0; counter < 5; counter++) {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
This loop makes the LED blink five times. Let’s go through how it works:
- int counter = 0 creates a variable that starts at zero.
- counter < 5 checks whether the counter is less than five.
- If the condition is true, the statements between the curly brackets (US: curly braces) are run.
- counter++ increases the counter by one.
- The program checks the condition again and repeats the loop for as long as it stays true.
The counter takes the values 0, 1, 2, 3 and 4: that’s five values, so the loop runs five times. When the counter reaches 5, the condition counter < 5 is false and the loop ends.
The ++ operator (the increment operator) increases a variable by one. For example, counter++ is the same as writing counter = counter + 1.
Once the for loop has finished, the program carries on with the statements that come next. In our example, Arduino goes to the end of loop() and starts again from the top of the function.
The while loop
The while loop repeats statements for as long as a condition is true. Unlike for, it doesn’t have a dedicated place to initialise and update a counter: when you need those operations, you write them separately.
Its structure is:
while (condition) {
// Statements to repeat
}
Here’s an example:
int counter = 0;
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
counter = 0;
while (counter < 3) {
digitalWrite(13, HIGH);
delay(300);
digitalWrite(13, LOW);
delay(300);
counter++;
}
delay(2000);
}
In this program, the LED blinks three times, then stays off for two seconds. After that, loop() starts again and the sequence repeats.
At the start of each run of loop(), the counter is reset to zero. The while loop then checks the condition counter < 3 and repeats the statements until the counter reaches 3.
Warning: inside a while loop, the condition must be able to become false. If the counter weren’t incremented, for example, the program would keep repeating the statements and never leave the loop. That creates a loop that never ends, often called an infinite loop. In some applications an infinite loop is intentional, but it needs to be designed carefully.
Which loop should you use? (for vs while)
Both for and while let you repeat statements, but they tend to be used in different situations.
- for: handy when we know how many repetitions we need, as in five LED blinks.
- while: useful when we want to repeat an operation for as long as a certain condition stays true, such as carrying on with a calculation until a certain value is reached.
These aren’t hard-and-fast rules: in many cases you can use either one. It comes down to which structure makes the program clearer.
Also remember that loop() keeps running even after a for or while loop has finished. So if we put a loop inside loop(), we need to think about both the repetitions of the inner loop and the continuous repetition of the main function.
Hands-on exercise
Try using the LED connected to pin 13 and modify the program with the for loop shown earlier.
- Make the LED blink three times instead of five.
- Change the on and off times from 500 milliseconds to 200 milliseconds.
- Try a time of 1000 milliseconds.
- Explain what happens if you change the condition from counter < 5 to counter < 10.
See how the number of repetitions and the delay times change the behaviour of the circuit.
In the next sections, we’ll see how to organise our code into functions and how to hold on to information about the state of a system. These techniques will be especially useful when we start combining sensors, displays and servo motors in a single project.

8.4 Arduino Functions: How to Create and Use Your Own Functions
As programs get more complex, the number of statements to manage keeps growing. If we wrote everything inside the loop() function, the code could become long, hard to read and awkward to modify.
To organise a program better, we can use functions: blocks of code that we give a name to and can call whenever we need them.
We’ve already met two fundamental Arduino functions: setup() and loop(). Now we’ll see how to create new ones.
What is a function?
A function groups together one or more statements that carry out a specific task. For example, we can create a function that turns an LED on, one that turns it off, or one that reads the value of a sensor.
Let’s look at this example:
void turnLedOn() {
digitalWrite(13, HIGH);
}
void turnLedOff() {
digitalWrite(13, LOW);
}
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
turnLedOn();
delay(1000);
turnLedOff();
delay(1000);
}
The program works like the earlier ones: the LED turns on for a second and off for a second. The difference is that the statements for turning it on and off have been gathered into two separate functions.
When Arduino comes across turnLedOn();, it runs the statements inside the function turnLedOn(). When the function finishes, it goes back to the point in the program where it was called and carries on with the next statement.
The same happens when it comes across turnLedOff();.
The functions turnLedOn() and turnLedOff() are defined before setup() and loop(). That makes the program easy to follow: each function is described before the point where it’s used.
How do you define a function?
A simple function – one that doesn’t return a value and doesn’t need any input data – has this structure:
void functionName() {
// Statements to run
}
Let’s go through the main parts:
- void means the function doesn’t return a value to the program.
- functionName is the name we choose to identify the function.
- The round brackets () can hold any data the function receives as input. In our example they’re empty.
- The curly brackets { } enclose the statements that belong to the function.
The name should clearly describe the task the function carries out. For example, readSensor(), updateDisplay() and checkDistance() are more meaningful function names than function1() or test().
To call a function, you simply write its name followed by round brackets and a semicolon, as in turnLedOn();.
Warning: defining a function doesn’t mean it runs automatically. Its statements run when the function is called, except for the special functions managed by Arduino, such as setup() and loop().
Passing a value to a function (parameters)
A function can also receive an input value, called a parameter. This lets us reuse the same function with different data, without having to rewrite the statements.
For example, we can create a function that turns the LED on and off for a specified length of time:
void blinkLed(int duration) {
digitalWrite(13, HIGH);
delay(duration);
digitalWrite(13, LOW);
delay(duration);
}
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
blinkLed(200);
blinkLed(1000);
}
The blinkLed() function takes a parameter called duration, of type int. When we call blinkLed(200), the parameter is 200 and the on and off times are 200 milliseconds. When we call blinkLed(1000), the same steps run with a duration of one second.
That way, a single function can produce different behaviours simply by changing the value passed between the round brackets.
As in the earlier examples, once the two calls finish, the program reaches the end of loop() and starts again from the top. As a result, the sequence repeats continuously.
Returning a value from a function
A function can also calculate or read a piece of data and hand it back to the point in the program that called it. To do that, we use a data type in place of void, together with the return statement.
For example, we can create a function that reads the light sensor connected to A0:
int readLight() {
int value = analogRead(A0);
return value;
}
void setup() {
Serial.begin(9600);
}
void loop() {
int lightValue = readLight();
Serial.println(lightValue);
delay(500);
}
The function readLight() runs analogRead(A0) and saves the result in the variable value. The statement return value; sends that number back to the program.
When Arduino runs:
int lightValue = readLight();
the value returned by the function is assigned to the variable lightValue, which can then be used in the statements that follow.
In this example, the function returns an integer because int was specified. The value read from an analog input on the Arduino UNO R3 ranges from 0 to 1023.
Why use functions?
Functions help make a program tidier and easier to understand. Their main advantages are:
- Organisation: each function carries out a specific task.
- Reuse: we can call the same block of code as many times as we like.
- Easier changes: if we need to change how an operation is carried out, we can do it inside the function without touching every place where it’s used.
- Easier reading: clear names let you grasp the purpose of the statements without having to analyse every detail straight away.
In the final project, for example, we’ll be able to create one function to read the distance, one to update the display and another to control the servo motor. The main program can then coordinate the different operations without containing all the details itself.
Hands-on exercise
Starting from the program with the blinkLed() function, try making these changes:
- Create a function called turnLedOn() that turns the LED on.
- Create a function called turnLedOff() that turns it off.
- Modify loop() to call the two functions, with a one-second wait between one operation and the next.
- Modify the blinkLed() function so that it receives a parameter, and experiment with different times.
- If you’ve already connected the light sensor, try using the readLight() function to get the sensor value and show it on the serial monitor.
Remember that you don’t need a function for every little operation: it’s worth creating one when it helps organise the code or when a group of statements needs to be reused.
In the next section, we’ll see how to make our code clearer and easier to pick up again later, thanks to comments.

8.5 Arduino Comments: How to Write Clear, Readable Code
So far our programs have been short, and we’ve always known what we were doing. But imagine reopening, six months from now, a program you wrote today: will you remember what each variable is for and why you picked that particular value? Quite possibly not. That’s why, as well as writing correct statements, it’s important to learn how to write comments.
A comment is a piece of text inserted into the program that Arduino ignores completely: it’s only there for whoever reads the code. Comments don’t take up any memory on the board, because the compiler removes them before the program is uploaded. So you can write as many as you need without worrying about the Arduino UNO R3’s tiny 2 KB of RAM.
In most cases, the first person to read our comments is us, months or even years later.
How to write comments in Arduino
The Arduino language gives you two ways to write a comment.
The single-line comment: //
Everything after the two // symbols, up to the end of the line, is ignored. It can take up a whole line or sit at the end of a statement:
// This line is a comment and isn’t executed
int lightValue = analogRead(A0); // Reads the light sensor on pin A0
The multi-line (block) comment: /* ... */
Everything between /* and */ is ignored, even if it spans several lines. It’s handy for longer texts, such as the description at the start of a program:
/*
This is a comment
that takes up
several lines.
*/
There are two rules to remember:
- a // comment always ends at the end of the line, so you don’t need to close it;
- a /* comment must always be closed with */, and comments of this type can’t be nested, i.e. you can’t put one inside another.
Warning: if you forget to close a /* comment with */, the compiler reports an error or, even worse, part of the program silently disappears inside the comment and never runs. If your program behaves strangely after a change, always check that all your comments are properly closed.
Temporarily disabling a line (commenting out code)
Comments are also useful while you’re testing: by putting // in front of a statement, we can disable it without deleting it, to see how the program behaves.
// delay(1000); // Statement temporarily disabled for a test
The Arduino IDE lets you comment or uncomment one or more selected lines with the keyboard shortcut Ctrl + / (Cmd + / on a Mac). Just remember not to leave forgotten lines of commented-out code in the finished program: they make it harder to read.
What to comment (and what not to)
The most important rule is this: a good comment explains why, not what. The code already tells us what is being done; the comment should help us understand why it’s done that way.
A comment that merely repeats the statement is useless:
counter++; // Increases counter by one
A comment that explains the reason is far more valuable:
counter++; // Counts a new valid button press
1. Statements whose meaning isn’t obvious from the context
A typical example is the flag, i.e. a variable that’s set in one part of the program so that it can be read in another:
bool alarmActive = false; // Flag: set to true by checkDistance()
// read by updateDisplay() to show the warning
Without this comment, anyone reading updateDisplay() would have to search the whole program to find where and when the variable gets changed.
2. Values and units of measurement
A number on its own doesn’t tell you whether it’s milliseconds, centimetres or an analog reading:
const int lightThreshold = 500; // Value above which the LED turns on
const unsigned long interval = 1000; // Pause between two state changes
3. Hardware connections
For Arduino projects, noting where each component is connected is essential, especially when the circuit gets taken apart and put back together:
const int buttonPin = 2; // Button with 10 kOhm pull-down resistor
const int ledPin = 13; // LED with 220 Ohm resistor
4. Non-obvious choices
If a line exists for a particular reason, say so:
delay(20); // Short pause to reduce the effect of button bounce
When a comment isn’t needed
If the name of a variable or function is already clear, a comment is superfluous. For example, ledOn and turnLedOn() speak for themselves. Descriptive names and comments aren’t alternatives: clear names tell you what something is, comments explain why it’s done that way.
The program header
A good habit is to start every program with a comment, written in the /* ... */ form, that introduces it. It usually contains:
- the name and purpose of the program;
- the author and the date (or the version);
- the board used;
- the connections of the components.
/*
Light sensor with button
Purpose: turns the LED on only if there’s light and the button is pressed.
Board: Arduino UNO R3
Author: Your name
Version: 1.0
Connections:
- Light sensor: analog pin A0
- Button: pin 2 (with 10 kOhm pull-down resistor)
- LED: pin 13
*/
When you modify the program, you can update the version and add a short note about the changes you’ve made.
Commenting functions
In the previous section we saw how to organise a program into functions. Every function we write should have, right before its definition, a comment explaining what it does, what data it receives, what it returns and, if necessary, which variables it changes. That way, anyone using it – ourselves included, in the future – doesn’t have to read through its contents to understand how to use it.
/*
blinkLed
Turns the LED on pin 13 on, waits, turns it off and waits again.
Parameters:
duration - on and off time, in milliseconds
Return value: none
*/
void blinkLed(int duration) {
digitalWrite(13, HIGH);
delay(duration);
digitalWrite(13, LOW);
delay(duration);
}
Here’s another example, for a function that returns a value:
/*
readLight
Reads the light sensor connected to A0.
Return value:
integer from 0 (dark) to 1023 (maximum light)
with the circuit described in chapter 6.
*/
int readLight() {
return analogRead(A0);
}
The style modern programmers use
In professional projects and in Arduino libraries, function comments often follow a standard format called Doxygen style, which uses the /** symbol at the start and keywords preceded by @:
/**
* @brief Reads the light sensor connected to A0.
* @return Integer from 0 to 1023.
*/
int readLight() {
return analogRead(A0);
}
The most common keywords are @brief (a short description), @param (a description of a parameter) and @return (the return value). The advantage is that there are tools that can read these comments and automatically generate documentation for the program. It isn’t compulsory for our projects: what matters is to choose a format, even a simple one like the one above, and use it consistently throughout the program.
Good habits for programmers
Here’s a summary of the rules that are now considered standard practice when writing comments:
- Comment the why, not the what. Avoid repeating what the code already says clearly.
- Choose clear names for variables and functions: they reduce the need for comments.
- Always state the units of measurement (milliseconds, centimetres, volts) next to values.
- Keep your comments up to date. A comment that no longer matches the code is worse than no comment at all, because it leads you astray. When you change a statement, check the comment next to it too.
- Don’t leave commented-out code in the final version of the program. If you want to keep an earlier version, save a copy or use a version control system such as Git.
- Mark the points still to be completed with conventional words such as TODO (to do) or FIXME (to fix), for example: // TODO: add the button check.
- Use a single language for your comments. In projects shared internationally, English is usually used; for personal projects, your own language is perfectly fine, as long as you keep to the same rule throughout the program.
- Don’t overdo it. Commenting every single line makes a program heavy going to read. Better a few useful comments than lots of obvious ones.
A complete example
Let’s see what the program from the section on operators looks like with a header and proper comments:
/*
Light sensor with button
Purpose: turns the LED on only if the light is above the threshold AND the button is pressed.
Board: Arduino UNO R3
Connections:
- Light sensor: A0
- Button: pin 2 (10 kOhm pull-down)
- LED: pin 13
*/
// --- Pins and fixed values ---
const int buttonPin = 2;
const int ledPin = 13;
const int lightThreshold = 500; // Analog reading (0-1023) above which there’s “enough light”
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
int lightValue = analogRead(A0);
int buttonState = digitalRead(buttonPin); // HIGH = pressed (pull-down circuit)
// The LED turns on only if BOTH conditions are true
if (lightValue > lightThreshold && buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
Hands-on exercise
Take one of the programs you wrote in the earlier chapters and try these activities:
- Add a header at the top of the program with its purpose, the board and the connections.
- Add a comment to every pin and every constant, stating the unit of measurement where needed.
- Find a comment that merely repeats the statement and rewrite it to explain the reason.
- Put // in front of one line of the program, upload the program to the board and see what changes. Then remove it again.
- Try writing a /* comment without closing it with */ and look at the error the compiler reports.
In short: comments don’t change how a program works, but they do change its quality. A well-commented program is easier to debug, to modify and to pick up again after a long time. In the next section, we’ll see how to store and update the state of a system: a kind of program where comments, such as those explaining what a state variable is for, will be particularly useful.

8.6 Storing and Updating State in Arduino: Toggle an LED with a Button
In the programs we’ve built so far, Arduino reads an input and decides what to do based on the value it detects. For example, it can turn an LED on when we press a button and turn it off when we release it.
But what if we want the LED to turn on when we press the button once, and to turn off only when we press it a second time? In that case, Arduino has to remember whether the LED was already on or off.
To get this behaviour, we need to store the state of the system: that is, hold on to a piece of information that describes the current situation, and update it when something happens.
Storing a state in a variable
A variable can hold on to a piece of information from one run of loop() to the next. For example, we can use a bool variable to remember whether an LED should be on or off.
bool ledOn = false;
The variable ledOn can take two values:
- false: the LED is considered off.
- true: the LED is considered on.
We can change this variable while the program is running and use its value to decide how to control the LED.
It’s important to declare it outside setup() and loop() (which makes it a global variable), as in the example above. That way it keeps its value between the different calls of loop(). A variable declared inside a function, on the other hand, normally only lasts for as long as that function is running.
Toggling an LED on and off with each button press
To get the behaviour we want, it isn’t enough to check whether the button is pressed right now. We also need to work out whether it has only just been pressed.
Let’s imagine we’re using a button connected to pin 2, with a 10 kΩ pull-down resistor as in chapter 5, and the LED connected to pin 13.
The following program changes the state of the LED just once for each press of the button:
const int buttonPin = 2;
const int ledPin = 13;
bool ledOn = false;
int previousState = LOW;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void loop() {
int currentState = digitalRead(buttonPin);
if (currentState == HIGH && previousState == LOW) {
ledOn = !ledOn;
digitalWrite(ledPin, ledOn);
}
previousState = currentState;
delay(20);
}
Let’s go through the most important steps.
1. Storing the LED state
The variable ledOn holds the state we want to give the LED. At start-up it’s false, so the LED is initially kept off.
2. Reading the button
The statement digitalRead(buttonPin) reads the logic level present on pin 2. With the circuit we’re using, the value is HIGH when the button is pressed and LOW when it’s released.
3. Detecting a new press
The condition:
if (currentState == HIGH && previousState == LOW)
is only true when the current reading is HIGH and the previous one was LOW. That marks the change from button released to button pressed.
This is called rising edge detection: the program recognises the change of state, not simply the fact that the button is pressed.
4. Inverting the LED state
The statement:
ledOn = !ledOn;
uses the logical operator !, which inverts a Boolean value. If ledOn is false, it becomes true; if it’s true, it becomes false.
Straight afterwards, digitalWrite(ledPin, ledOn) controls the LED according to the stored value. Arduino accepts HIGH and LOW as output levels; in this context the Boolean values true and false correspond to on and off respectively.
5. Updating the previous state
At the end of the loop, the statement:
previousState = currentState;
stores the reading we’ve just taken, so that we can compare it with the next one. If we didn’t update this variable, Arduino might keep treating the button as just pressed on the following runs of loop().
The short 20-millisecond delay limits how often readings are taken, but it doesn’t completely eliminate the problem of the button’s mechanical bounce, which we’ll look at shortly.
Why isn’t it enough to check whether the button is pressed?
In the chapter 5 program, we used a condition similar to this one:
if (buttonState == HIGH) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
The LED stays on for as long as the button is pressed and turns off when it’s released. Arduino doesn’t have to remember a previous action: it’s enough to read the button’s current state.
In the new program, on the other hand, we want each press to change the state of the LED, and we want that state to stay the same after the button is released. To do that, we have to hold on to two pieces of information: the state of the LED and the previous state of the button.
This distinction is very important in automated systems. A sensor can tell us what’s happening right now, whereas a state variable lets the program remember what it has decided or detected before.
The button bounce problem (debouncing)
Mechanical buttons don’t always switch from LOW to HIGH perfectly cleanly. When they’re pressed or released, the contacts can open and close rapidly for a few milliseconds. This phenomenon is called bounce (or contact bounce).
Arduino might interpret these changes as several presses in quick succession, making the LED change state more than once with a single press.
In our example, delay(20) slows down the readings and can reduce some of the unwanted effects, but it doesn’t guarantee that bounce is handled properly. For more reliable behaviour, we use a technique called debounce (or debouncing), which treats a change as valid only after the button’s state has stayed stable for a certain interval. We can explore this technique in the exercises or later on, when we build more complex programs.
Where will we use state memory?
Remembering state is useful in a great many applications:
- keeping an LED on after a button press;
- remembering whether a system is active or inactive;
- storing whether an object has been detected;
- knowing whether a servo motor should search for an object or point in the direction where one has been found;
- avoiding repeating an action over and over when the condition that triggered it stays true.
In the final project, for example, we’ll be able to use variables to remember whether the system is searching for an object or has already detected one. Depending on that state, Arduino can choose whether to carry on scanning or to update the display and aim the servo motor.
In short: variables aren’t just for holding sensor readings. They can also store the state of a system and let the program behave differently depending on what has happened before.
In the next section, we’ll see how to manage time in Arduino programs, learning to tell apart the waits that block execution from the techniques that let you carry out several activities in a coordinated way.

8.7 Arduino millis() vs delay(): How to Manage Time in Your Programs
In Arduino projects, time is an important factor. We may need to make an LED blink at regular intervals, read a sensor every half a second, update a display or control a servo motor while other operations keep running.
In our first programs, we used the delay() function, which lets us wait for a certain number of milliseconds. It’s simple to use, but it has one important limitation: while it’s waiting, Arduino doesn’t carry on with the other statements in the program.
To understand how to manage time more flexibly, let’s first look at how delay() works and then introduce the millis() function.
The delay() function
The delay() function pauses the execution of the program for the specified time, expressed in milliseconds.
Let’s remember that:
- 1000 milliseconds is 1 second;
- 500 milliseconds is half a second;
- 100 milliseconds is a tenth of a second.
For example:
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
The LED stays on for a second and off for a second. The program is simple and works well for this kind of exercise.
During each wait, though, Arduino doesn’t run the other statements in loop(). If we put a button reading between the two waits, the program could only check it when it reached that statement. A very short press might therefore go undetected.
For this reason, delay() is fine when a wait is acceptable, but it can become impractical in systems that need to do several things at the same time.
The millis() function
Arduino provides the millis() function, which returns the number of milliseconds that have passed since the board was started or reset.
Unlike delay(), calling millis() doesn’t pause the program. So we can check how much time has passed and decide whether to carry out an operation, while carrying on reading sensors or checking buttons in the meantime.
The value returned by millis() is an unsigned integer of type unsigned long. On the Arduino UNO R3 it’s a 32-bit value and, after about 49.7 days, it reaches its limit and starts again from zero (this is known as rollover). For the most common time intervals in our projects, this behaviour isn’t a problem as long as we make our time comparisons correctly.
Blinking an LED without blocking the program
Let’s see how to get a blink similar to the one we made with delay(), but using millis() instead.
const int ledPin = 13;
const unsigned long interval = 1000;
unsigned long previousTime = 0;
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - previousTime >= interval) {
previousTime = currentTime;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn);
}
// We can add other operations here.
}
The program uses a few variables to remember the time and the state of the LED.
1. Defining the interval
const unsigned long interval = 1000;
The variable interval says we want to change the state of the LED every 1000 milliseconds, i.e. every second. The unsigned long type is suited to holding the values returned by millis().
2. Reading the current time
unsigned long currentTime = millis();
On every pass of loop(), Arduino updates the variable with the number of milliseconds that have passed since start-up.
3. Checking whether enough time has passed
if (currentTime - previousTime >= interval)
This condition checks whether at least one second has passed since the LED last changed.
4. Updating the time and the LED
previousTime = currentTime;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn);
When the interval has elapsed, Arduino stores the current time and inverts the state of the LED. On the next pass, the condition will be false until another interval has gone by.
The subtraction between the current time and the previous time is important: it lets us handle the rollover of the millis() counter from 4,294,967,295 back to zero correctly, as long as the intervals we’re considering are shorter than the counter’s full period.
Controlling several activities in the same program
The main advantage of this method is that the program doesn’t sit still waiting. After checking the time, Arduino can move on and carry out other operations within the same run of loop().
For example, we can add a reading of the light sensor:
const int ledPin = 13;
const unsigned long interval = 1000;
unsigned long previousTime = 0;
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - previousTime >= interval) {
previousTime = currentTime;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn);
}
int lightValue = analogRead(A0);
Serial.println(lightValue);
}
In this example, the LED changes state every second, while Arduino keeps reading the sensor and sending the values to the serial monitor. The readings happen much more often than the blinking, because they aren’t slowed down by a one-second wait.
This doesn’t mean Arduino really carries out all the operations at the same instant: the statements are still run one after another, very quickly. The advantage is that no long wait stops the program from moving on to the other activities.
When to use delay() and when to use millis()
Both methods are useful, but they meet different needs.
- Use delay() when the program is simple and stopping for a while doesn’t cause any problems, for example in a first blinking exercise.
- Use millis() when Arduino needs to keep reading sensors, checking buttons or handling several operations with different timings.
In our first experiments, delay() was useful for understanding the sequence of statements. In more complex projects, millis() will let us coordinate the different activities more flexibly.
One last point: using millis() doesn’t on its own guarantee that every activity will run at exactly the right moment. The time check happens when the program reaches the relevant condition; any long operations can delay the response.
Exercises and experiments
- Change interval from 1000 to 500 milliseconds. What changes in the blinking?
- Try setting an interval of 200 milliseconds.
- Add a light sensor reading and send the value to the serial monitor. Check that the LED keeps blinking while the values are displayed.
- Explain why the program with millis() can check a button more often than a program that uses delay(1000).
- Try to identify the variables that store the time, the interval and the state of the LED. Which of these variables has to change while the program is running?
In short: delay() is a simple way to wait, while millis() lets you measure elapsed time without stopping the program. Learning to choose between these two techniques will be essential when Arduino has to read sensors, update the display and control the servo motor within the same project.
In the next section, we’ll see how to find and fix errors, using the compiler, the serial monitor and an orderly method of checking.

8.8 How to Debug an Arduino Program: Finding and Fixing Errors
When you’re learning to program, making mistakes is perfectly normal. Even people who’ve been developing software for many years often have to check their code, track down problems and fix them. Learning to recognise errors is therefore a fundamental part of programming.
An Arduino program can fail to work for several reasons: the code may contain a syntax error, the logic may be wrong, or the circuit may be wired incorrectly. To find the cause of the problem, it helps to work methodically and check one thing at a time.
The main types of error
We can distinguish three categories of error.
1. Syntax errors
These happen when the code doesn’t follow the rules of the language. For example, a semicolon or a bracket may be missing, or the name of a function may be misspelled.
Let’s look at this example:
void setup() {
pinMode(13, OUTPUT)
}
void loop() {
digitalWrite(13, HIGH);
}
Here the semicolon is missing after pinMode(13, OUTPUT). The compiler will report an error, and the program can’t be uploaded until the problem is fixed.
When a compilation error appears, read the message shown by the Arduino IDE and check the line it points to. Sometimes the cause is right there; other times you also need to check the lines before it, because a missing bracket or another error can trigger further messages.
2. Logic errors
In this case the program compiles and uploads, but doesn’t behave as expected.
For example:
if (lightValue < 500) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
If our aim is to turn the LED on when the sensor value goes above 500, the condition is wrong: we’ve used < instead of >. The program can work perfectly well from a technical point of view, but its behaviour will be the opposite of what we wanted.
To fix a logic error, you need to work out what result you expect and compare it with what actually happens.
3. Wiring errors
Not all problems come from the program. An LED may have been inserted with the polarity reversed, a sensor may be connected to the wrong pin, or the connection to GND (ground) may be missing.
In these cases the program may be correct, but the circuit doesn’t work as expected. Before changing the code, always check the connections and make sure they match the project’s circuit diagram.
A step-by-step method for finding errors
When a project doesn’t work, avoid changing lots of things at once. If you change several connections and various statements at the same time, it becomes hard to tell which change solved the problem. It’s better to follow a simple method:
- Describe the problem. What should the program do, and what does it do instead?
- Check the compilation. If the IDE reports an error, read the message and find the line concerned.
- Check the connections. Check the power, GND, the polarity of the components and the pins being used.
- Try one change at a time. After each fix, compile and test the program again.
- Check the results. If the problem persists, gather more information before changing the code again.
This method makes it easier to find the cause of the problem, and also to understand why the fix works.
Using the serial monitor to check values
The serial monitor is a particularly useful tool when we work with sensors and variables. It lets you display on your computer the data that Arduino sends over the USB connection.
For example, suppose we’re reading the light sensor connected to A0:
void setup() {
Serial.begin(9600);
}
void loop() {
int lightValue = analogRead(A0);
Serial.print(“Light value: “);
Serial.println(lightValue);
delay(500);
}
After uploading the program, open the Arduino IDE’s serial monitor and set the speed to 9600 baud, so that it matches the value specified in Serial.begin(9600).
You’ll see numerical values appear that change according to the light detected by the sensor.
The two print functions work slightly differently:
- Serial.print() writes the text without automatically moving on to the next line.
- Serial.println() writes the value and then moves on to the next line.
The serial monitor can also be used to check other information, such as the state of a button, the distance measured by a sensor or the value of a variable while the program is running.
For example, we can check that a button is being read correctly:
void setup() {
pinMode(2, INPUT);
Serial.begin(9600);
}
void loop() {
int buttonState = digitalRead(2);
Serial.println(buttonState);
delay(100);
}
With the pull-down circuit used in chapter 5, you should see 0 when the button is released and 1 when it’s pressed. If the value doesn’t change, check the circuit before touching the program’s logic.
Checking variables and conditions
An error can also come from an unexpected value or from a condition that never gets satisfied.
Let’s imagine we want to turn the LED on when the light value goes above 500:
int lightValue = analogRead(A0);
if (lightValue > 500) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
If the LED never turns on, the condition isn’t necessarily wrong. It might be that the sensor never reaches the value 500 in the lighting conditions you have.
To find out, we can print the reading to the serial monitor and look at the values we get both in bright light and in the dark. Based on the results, we can choose a more suitable threshold.
It’s important to remember that the values read from an analog sensor depend on the component and the circuit used. There’s no universal threshold that works for every light sensor.
Watch out for names and symbols (common beginner mistakes)
Some mistakes are particularly common when you’re starting out in programming:
- Writing pinmode() instead of pinMode(): the language is case-sensitive.
- Forgetting the semicolon at the end of a statement.
- Not closing round or curly brackets properly.
- Using = instead of == in a comparison.
- Reading a different pin from the one the component is connected to.
- Declaring a variable inside a function and then trying to use it outside that function.
When a program gets longer, using clear names for variables and splitting the code into functions can help reduce errors and make it easier to see where to step in.
Hands-on exercise: spot the error
Try uploading the following program, which reads the light sensor and controls the LED:
const int lightThreshold = 500;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
int lightValue = analogRead(A0);
Serial.println(lightValue);
if (lightValue > lightThreshold) {
digitalWrite(13, LOW);
} else {
digitalWrite(13, HIGH);
}
delay(200);
}
The program compiles and runs, but the LED turns on when the light value is less than or equal to the threshold and turns off when it’s above it.
Try these activities:
- Modify the program so that the LED turns on when the reading goes above 500.
- Look at the values shown in the serial monitor and try changing the threshold.
- If the LED doesn’t react as expected, check the circuit and make sure the sensor is connected correctly.
- Try printing a message as well, such as Bright light or Low light, depending on the condition being tested.
The aim isn’t just to get a working program, but to understand how to track down the cause of a problem and fix it in a methodical way.
In short: programming also means trying, observing, checking and correcting. The compiler helps us find syntax errors, while the serial monitor lets us check values and understand how the program behaves. Together with checking the connections, these tools will be indispensable for tackling the more complex projects in the coming chapters.

Coming up in the next chapter...
So far, Arduino has turned on LEDs, read buttons and displayed messages on an LCD screen. In Chapter 9 – Arduino Sensors: Measure Distance and Detect Motion with HC-SR04 and PIR, we’ll give it something extra: real “senses” to notice what’s happening around it.
We’ll find out what sensors are and how they turn the real world into information our board can understand. We’ll learn to measure the distance to an object without touching it, much like bats do with ultrasound, and to make Arduino react when someone walks across the room, just like burglar alarms and motion-sensor lights that switch on as we walk by.
Then we’ll see how to measure air temperature and humidity, and take a quick look at plenty of other little modules that can make our projects even more interesting. There will be hands-on exercises and a final challenge: building a small obstacle detection system that warns us when something gets close.
With Chapter 9, our projects stop simply following a program and start reacting to the world around them. We’re just one step away from the true spirit of robotics!
If you’re curious to see where this journey will take us, have a look at the page Beginner's Guide to Robotics with Arduino: there you’ll find the full contents list, from the first chapter to the final project, and you can choose whether to carry on in order or go back and review a topic.
If you’ve found this course useful and would like to explore other robotics or hobby electronics projects, you can keep reading by visiting the other content in the Electronics and Robotics section of the site, where you’ll find plenty more practical guides and step-by-step explanations.
I’d like to point out that some of the images in the course were generated by artificial intelligence (AI), and I apologise for any inaccuracies they may contain. The course itself was also written with the help of AI, but the structure is the result of my own experience: I’m a retired programmer and, over the course of my career, I’ve taught several courses. So I chose the topics, organised the whole structure of the course and reviewed the text myself.
I care a great deal about the quality and originality of the content I publish. That’s why I’d prefer it not to be copied or republished elsewhere. If you think this guide could be useful to other people, though, I’ll be really happy if you share the link to the page: it’s the right way to spread the information and to support the work behind every article.
Thank you
Luciano (Capitan Farloc)

English (United Kingdom)
Italiano (Italia)