Logo ilsitodelfaidate.it

9.1 What Is a Sensor and What Can It Measure?

In the previous chapters we learned how to use Arduino to turn on an LED, read a button, measure the brightness of a room and show information on an LCD screen. To build these projects we used components that let the board receive information from the world around it: sensors.

A sensor is a device that can detect a particular physical quantity or a change in its surroundings and turn it into a signal that an electronic system can use.

For example, a light sensor detects brightness, a temperature sensor measures how hot or cold a room is, and an ultrasonic sensor can estimate the distance to an object. Arduino can read the signals produced by these devices, process them with a program and decide how to respond.

What Can a Sensor Measure?

There are sensors designed to detect very different phenomena. Among the most common are:

  • Light: detects the brightness of the surroundings. We have already used a light-dependent resistor (LDR), also known as a photoresistor, for this purpose.
  • Temperature: measures how hot or cold an object or a room is.
  • Humidity: depending on the type of sensor, measures the humidity of the air or the moisture of the soil.
  • Distance: estimates how far away an object is from the sensor.
  • Motion: detects the movement of people or objects, depending on how the sensor works.
  • Magnetic field: detects a magnet, or changes in the magnetic field nearby.
  • Tilt: tells whether a device has been tilted or has changed orientation.

Each sensor is designed for a specific kind of detection and has its own characteristics and limitations. To choose the right one, we need to ask ourselves what information we want to obtain and in what conditions the sensor will be used.

How Does a Sensor Communicate with Arduino?

A sensor doesn’t necessarily give us a ready-to-use value. Depending on how it works, it can produce a digital signal, an analog signal, or use a more elaborate form of communication.

Sensors with a Digital Output

A sensor with a digital output can provide two logic states: HIGH and LOW. These states can represent, for example, whether or not a given condition has been detected.

Imagine a module that signals when it detects movement. Arduino can read its output pin with the digitalRead() function and use the result to turn on an LED or display a message.

int sensorState = digitalRead(2);

In this example, Arduino reads the logic level on digital pin 2. The meaning of HIGH and LOW depends on the sensor and how it is set up: HIGH doesn’t always mean that an object is present.

Sensors with an Analog Output

An analog sensor can provide a voltage that varies according to the quantity being measured. Arduino UNO R3 can read this voltage through one of its analog inputs, for example A0.

We have already used this principle with the LDR connected to a resistor to form a voltage divider. The reading is taken with analogRead():

int sensorValue = analogRead(A0);

On the Arduino UNO R3, the analog-to-digital conversion normally returns a value between 0 and 1023. This number represents the measured voltage relative to the analog reference, not the physical quantity itself. To obtain a temperature or a distance, for example, you need to know how the sensor works and apply the appropriate conversion.

Sensors with Digital Communication

Some sensors use communication protocols to send more complex data. In these cases Arduino doesn’t just read a simple HIGH or LOW level, but has to follow the rules set by the sensor in order to receive the information.

One example is the DHT11 temperature and humidity sensor, which sends the measured values as a sequence of digital signals. To make reading easier, a library is often used to handle the details of the communication.

The HC-SR04 ultrasonic sensor, which we’ll look at in the next section, also needs careful timing of its signals to work out the distance. It doesn’t directly give an analog measurement of the distance: Arduino has to measure the length of the pulse received on the ECHO pin and convert it into an estimate of the distance.

From Data to Decision

Reading a sensor is only the first step. To build a useful system, Arduino has to interpret the value it gets and decide what to do.

Suppose, for example, that we want to turn on an LED when an object is closer than 20 cm. The program will have to:

  1. read the data provided by the sensor;
  2. work out the distance, if the sensor doesn’t already provide it as a numerical value;
  3. compare the distance with the 20 cm threshold;
  4. turn the LED on if the object is close enough, and off otherwise.

This sequence puts into practice many of the concepts we have studied so far: inputs, variables, conditions and outputs. It is precisely the combination of these elements that turns a simple electronic board into a system that can react to its environment.

What Do We Need to Know Before Using a Sensor?

Before connecting a sensor to Arduino, it is important to check its technical specifications (the datasheet) and verify a few things:

  • Power supply: what voltage the sensor needs and what its limits are.
  • Connections: which pins are used for power, ground (GND) and the signal.
  • Output type: whether the sensor provides a digital or analog signal, or uses a communication protocol.
  • Measuring range: the limits within which it can take reliable readings.
  • Accuracy and limitations: how far the measurement can differ from the real value, and which conditions can affect it.

This information helps us avoid wiring mistakes and interpret the data correctly. After all, a numerical reading is not automatically an accurate measurement: the result depends on the characteristics of the sensor, the circuit and the conditions in which it is used.

Infographic about Arduino sensors: a sensor detects a physical quantity (light, temperature, humidity, distance, motion, magnetic field, tilt) and sends a signal to an Arduino UNO R3 through a digital output, an analog output or digital communication. At the bottom, the four steps from data to decision: read the sensor, work out the measurement, compare it with a threshold, then switch the output on or off.

9.2 The HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 ultrasonic sensor lets Arduino measure the distance to an object without touching it. It is used in many robotics projects, for example to detect obstacles, to check how close an object is, or to build parking sensor systems.

It works in a similar way to sonar: the sensor sends out a high-frequency sound and measures how long the sound takes to reach an obstacle and come back after being reflected.

How It Is Built and How It Works

The HC-SR04 module has four pins for connecting it to Arduino:

  • VCC: power supply, normally 5 V.
  • GND: ground, the electrical reference point of the circuit.
  • TRIG: input that receives the command from Arduino to start a measurement.
  • ECHO: output that tells Arduino how long the sound wave took to travel to the obstacle and back to the sensor.

The module also has two round components that look like tiny speakers. They actually do two different jobs: one transmits the ultrasound, while the other receives it.

Diagram of the HC-SR04 ultrasonic distance sensor for Arduino, seen from the front: the ultrasonic transmitter on the left, the receiver on the right and the crystal oscillator at the top centre. Below, the four pins: Vcc (+5 V), Trig (input pin), Echo (output pin) and GND (connected to 0 V and ground, also called “ground” in the US).

Ultrasound consists of sound waves with a frequency too high for the human ear to hear. The HC-SR04 uses a frequency of about 40 kHz.

To measure a distance with the HC-SR04, Arduino has to send a 10 µs pulse to the TRIG pin. The sensor then switches on and transmits a burst of ultrasonic waves made up of 8 cycles at 40 kHz. Right after the burst is sent, the ECHO pin goes from LOW to HIGH. When the echo returns to the sensor, the ECHO pin goes back to LOW and the pulse ends.

The length of this pulse is therefore the time the ultrasonic waves took to travel, at the speed of sound, from the sensor to the obstacle and back again.

Arduino can measure this duration and use it to calculate the distance.

How to Calculate the Distance

Sound travels through air at a speed of about 343 metres per second (US: meters per second) at a temperature of 20 °C. This speed can vary slightly with temperature and environmental conditions.

To calculate the distance, we need to know how long the sound wave took. However, the measured time includes both the trip to the obstacle and the trip back. For this reason, the result has to be divided by two, so the formula is:

Distance = speed of sound × time / 2

For the HC-SR04, it is common to use a simplified formula that directly gives an approximate distance in centimetres (US: centimeters):

Distance (cm) = ECHO pulse duration (µs) / 58

The symbol µs stands for microseconds, that is, millionths of a second.

For example, if Arduino measures an ECHO pulse lasting 1,160 microseconds, the calculation is:

1,160 / 58 = 20 cm

The sensor therefore estimates that the obstacle is about 20 centimetres away (roughly 8 inches).

Range and Limitations of the Sensor

Under favourable (US: favorable) conditions, the HC-SR04 can measure distances from about 2 cm (under 1 inch) up to 400 cm (around 13 feet). These values are only a guide: in practice, these limits may be different.

Not all objects reflect ultrasound in the same way. A large, hard surface facing the sensor tends to reflect it well. Soft materials, angled surfaces or very small objects, on the other hand, may return a weak echo or deflect it elsewhere. For this reason, a measurement may be inaccurate or may not be available at all.

It is important to remember that the sensor doesn’t recognise (US: recognize) what is in front of it: it measures the time the echo takes to return and uses it to estimate the distance. It therefore can’t tell a person from a wall or any other object on its own.

Arduino Compatibility

The HC-SR04 is well suited to use with the Arduino UNO R3, because the module normally runs at 5 V and the ECHO signal uses a logic level that is compatible with this board.

With boards that run at 3.3 V, however, you need to check that the signals are compatible: the ECHO pin of the HC-SR04 can output about 5 V, a voltage that could damage an input that isn’t designed to withstand it. In these cases you may need to use a voltage divider (made of two resistors) or a logic level shifter.

Diagram showing how the HC-SR04 ultrasonic sensor works when wired to an Arduino UNO R3: pin 9 goes to TRIG, pin 10 to ECHO, 5V to VCC and GND to GND. The sensor sends out an ultrasonic wave that bounces off an obstacle and returns as an echo. The three steps: 1. TRIG sends, 2. the sound bounces back, 3. ECHO receives.

In the next section we’ll connect the sensor to Arduino and write a program that can measure the distance and show it on the Serial Monitor.

9.3 How to Connect the HC-SR04 Ultrasonic Sensor to Arduino

Now that we understand how the HC-SR04 sensor works, we can connect it to Arduino and write our first program to measure a distance.

The goal is to read the distance to an object and show the result in the Serial Monitor of the Arduino IDE. This way we can move an object in front of the sensor and watch how the measured value changes.

What You Need

To carry out the experiment you will need:

  • An Arduino UNO R3 board and its USB cable for connecting it to the computer.
  • An HC-SR04 ultrasonic sensor.
  • A breadboard, if it helps you keep the connections tidy.
  • Four jumper wires.

Fritzing wiring diagram showing the HC-SR04 ultrasonic sensor mounted on a breadboard and connected to an Arduino UNO R3 board. The sensor’s Vcc and Gnd pins go to the breadboard power rails, which are wired to the 5V and GND pins on the Arduino. The Trig and Echo pins are connected with two jumper wires to digital pins 9 and 10.

Connecting the Pins

Before you start, unplug the USB cable from Arduino. Make the connections following this table.

HC-SR04 Pin Connection to Arduino UNO R3
VCC 5V
GND GND
TRIG Digital pin 9
ECHO Digital pin 10

 

Check the labels printed on the module: the physical layout of the pins can vary between different models. Don’t rely only on the position of the connectors.

Once the wiring is done, check it carefully again and connect Arduino to the computer via USB.

Let’s Draw the Flowchart

As shown in the diagram in the previous section, the HC-SR04 ultrasonic distance sensor is made up of two separate parts: an ultrasonic transmitter controlled by the Trig pin and an ultrasonic receiver linked to the Echo pin.

To measure the distance, it is enough to send a HIGH signal on the Trig pin for 10 microseconds and, immediately afterwards, measure on the Echo pin the time (also counted in microseconds) it takes to receive the echo of the signal that was sent.

If the signal isn’t received within a maximum time, it means that the echo wasn’t detected, because there are no obstacles closer than the maximum detectable distance.

The flowchart of the steps to carry out could be drawn like this:

Flowchart of the Arduino program for the HC-SR04 ultrasonic sensor. After the start, TRIG is set as an output and ECHO as an input, and serial communication begins. Then the program loops: a LOW signal on TRIG, a 10-microsecond HIGH pulse, TRIG back to LOW, and a measurement of the ECHO pulse duration. If the reading is valid, the distance is calculated and shown on the serial monitor; otherwise the message “No echo detected” appears. Finally, the program waits 300 milliseconds.

Let’s Write the Program

Following this flowchart, we can start writing the program code.

Open the Arduino IDE, create a new sketch and enter this code:

/*
Exercise No. 09.3-1
Purpose: Detects the distance with an HC-SR04 ultrasonic sensor and writes the value to the Arduino IDE console.
Board: Arduino UNO R3
Author: Luciano (Capitan Farloc)
Version: 1.0
Connections:
- HC-SR04 Distance Sensor
- Trig: Digital pin 9
- Echo: Digital pin 10
*/
const int trigPin = 9; // Constant for the sensor’s Trig pin
const int echoPin = 10; // Constant for the sensor’s Echo pin
unsigned long duration; // Microseconds between sending and receiving the echo
float distance; // Calculated distance

void setup() {
  pinMode(trigPin, OUTPUT); // Trig as Output to send the signal
  pinMode(echoPin, INPUT); // Echo as Input to receive the echo
  Serial.begin(9600); // Start the Arduino IDE console
}

void loop() {
  // Prepare the TRIG pin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Send the 10-microsecond trigger pulse
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Measure how long the ECHO pulse takes to return
  duration = pulseIn(echoPin, HIGH, 30000UL);
  if (duration > 0) {
    distance = duration / 58.0;
    Serial.print(“Distance: “);
    Serial.print(distance);
    Serial.println(“ cm”);
  } else {
    Serial.println(“No echo detected”);
  }
  delay(300);
}

Uploading and Running the Program

Select the Arduino UNO board and the correct port in the Arduino IDE, then upload the sketch.

When the upload has finished, open the Serial Monitor and set the speed to 9600 baud, the same value given in the Serial.begin(9600) instruction.

Place an object in front of the sensor, at first about 20–30 cm away (roughly 8–12 inches). In the Serial Monitor you should see lines like these:

Distance: 24.15 cm

Distance: 24.19 cm

These values are only examples: the actual measurements depend on the position of the object and the conditions of the experiment.

Slowly move the object closer and further away. The displayed distance should change accordingly. If no valid echo is detected within the time allowed by the program, the message No echo detected appears.

Understanding the Main Instructions

The first two lines define the pins used:

const int trigPin = 9;

const int echoPin = 10;

The word const indicates that these values are constants: they won’t change while the program is running.

The variables duration and distance are used to store the measured time and the calculated distance respectively. We use unsigned long for the duration, because the value returned by the time measurement can be stored in this unsigned type. We use float for the distance, so that it can also hold values with a decimal part.

In setup() we configure TRIG as an output and ECHO as an input. We also start serial communication at 9600 baud.

In the loop(), Arduino sets TRIG to LOW for a short time, then sets it to HIGH for 10 microseconds and finally brings it back to LOW. This pulse starts the sensor’s measurement.

The instruction:

duration = pulseIn(echoPin, HIGH, 30000UL);

measures how long the ECHO pin stays HIGH. The third parameter sets a maximum waiting time of 30,000 microseconds, that is, 30 milliseconds. This way, if the echo never arrives, the program doesn’t wait forever. If no valid pulse is measured within the limit, pulseIn() returns 0.

When duration is greater than zero, we calculate the distance with:

distance = duration / 58.0;

The value 58 is a handy approximation for converting the echo duration into centimetres. Dividing by 58.0 lets us get a decimal result as well.

Finally, Serial.print() and Serial.println() send the result to the computer, while delay(300) adds a pause of 300 milliseconds before the next measurement.

Let’s Try It and See

To check that it works, try placing the target at different distances and look at the values returned.

  • At about 10 cm, the value should be close to 10.
  • At about 30 cm, it should be close to 30.
  • If you move the target sideways or tilt it a lot, the reading may become unstable or the echo may not be detected.

Don’t expect identical measurements every time: small variations are normal. For more reliable results, keep the target still, with a large enough surface facing the sensor.

Arduino can now measure a distance without any contact. In the next section we’ll look at another type of sensor, the PIR, used to detect the movement of people or animals.

9.4 The PIR Motion Sensor and How It Works with Arduino

The PIR sensor (Passive InfraRed) can detect the movement of people and animals by watching for changes in the infrared radiation in its surroundings.

It is widely used in burglar alarms, in motion-activated lights that switch on automatically, and in devices that need to react to someone’s presence. By connecting it to Arduino, we can build a system that turns on an LED when it detects movement.

How a PIR Sensor Works

All bodies at a temperature above absolute zero emit electromagnetic radiation. Part of this radiation is infrared, which is invisible to the human eye and is related to the temperature of the body.

The PIR sensor contains an element that is sensitive to changes in infrared radiation. When a person or an animal moves within its detection range, the distribution of the radiation it receives changes, and the sensor can recognise (US: recognize) this change.

The term passive means that the sensor doesn’t send out a signal to illuminate or scan its surroundings, unlike the HC-SR04 ultrasonic sensor. The PIR simply detects the changes in the infrared radiation it receives.

Many PIR modules, such as those commonly used in educational projects, have a white, dome-shaped lens (a Fresnel lens) that helps to gather the radiation coming from different areas of the room. They often also have adjustments for the sensitivity and for the duration of the output signal.

It is important to understand that a PIR doesn’t measure distance and can’t identify an object with certainty. It detects changes consistent with the movement of warm bodies within its detection range. For example, it can detect a person walking across the room, but it normally can’t reliably detect a person who is completely still.

The Pins of the PIR Module

A typical PIR module has three connections:

  • VCC: power supply for the sensor.
  • GND: ground.
  • OUT: digital output that tells Arduino whether movement has been detected.

The supply voltage depends on the model: many educational modules, such as the popular HC-SR501, can be powered at 5 V, but you should always check the specifications of the component you are using.

Fritzing wiring diagram showing a PIR motion sensor connected to an Arduino UNO R3 board via a breadboard. The sensor’s VCC and GND pins go to the breadboard power rails, which are wired to the 5V and GND pins on the Arduino. The sensor’s OUT pin, shown with the yellow wire, is connected to digital pin 2.

The OUT pin normally takes one of these two states:

  • HIGH: the module is signalling (US: signaling) that movement has been detected.
  • LOW: the module is not signalling movement.

The exact behaviour (US: behavior) and the duration of the signal can vary depending on the module and its settings. In addition, after power-up, some sensors need a short warm-up period to settle before they give reliable readings.

How Arduino Reads the Sensor

Since the PIR provides a digital signal, Arduino can read it with the digitalRead() function, which we already used for the button in Chapter 5.

For example:

int motionState = digitalRead(2);

This instruction reads the state of digital pin 2 and stores the result in the motionState variable.

We can then use a condition to turn an LED on or off:

if (motionState == HIGH) {
  digitalWrite(13, HIGH);
} else {
  digitalWrite(13, LOW);
}

In this example, the LED turns on when the sensor signals movement and turns off when the signal goes back to LOW. To use this snippet in a complete program, you need to set pin 2 as an input and pin 13 as an output in the setup() function.

PIR vs Ultrasonic Sensor: What’s the Difference?

The two sensors meet different needs.

The HC-SR04 ultrasonic sensor measures the distance to an object using the echo’s return time. The PIR Sensor, on the other hand, signals a change in infrared radiation consistent with the movement of a warm body, without telling us how far away it is.

For example, a security system could use a PIR to detect movement in a room and an ultrasonic sensor to measure the distance to an obstacle. By combining different sensors, Arduino can gather more complete information about its surroundings.

In the next section we’ll look at some temperature and humidity sensors, useful for building weather stations and projects that react to the conditions of the air.

9.5 Temperature and Humidity Sensors: DHT11 and DHT22

Besides detecting light, distance and movement, Arduino can measure some environmental conditions, such as temperature and humidity. To do this we can use environmental sensors, components that are very common in electronics and home automation (US: smart home) projects.

These sensors are useful, for example, for building a small weather station, monitoring the conditions in a room, or creating a system that signals when the environment becomes too hot or too humid.

What Do They Measure?

Temperature tells us how hot or cold a room or an object is. In Arduino projects it is normally expressed in degrees Celsius (°C).

Relative humidity, on the other hand, indicates how much moisture is in the air compared with the maximum amount the air can hold at that same temperature. It is expressed as a percentage (%).

For example, a sensor might detect a temperature of 24 °C (about 75 °F) and a relative humidity of 55%. These values describe two different characteristics of the environment and can be used by the program to make decisions.

The DHT11 and DHT22 Sensors

DHT11 temperature and humidity sensor module: a blue plastic housing with ventilation slots, mounted on a small blue circuit board with three pins for connecting to Arduino (power, ground and data).

Among the most common environmental sensors in educational projects are the DHT11 and the DHT22. Both can measure temperature and relative humidity.

  • DHT11: it is inexpensive and easy to use, which makes it a good choice for first experiments. It generally has a more limited accuracy and measuring range.
  • DHT22: it normally offers a wider measuring range and greater accuracy, which makes it better suited when you need more detailed environmental readings.

The exact range and accuracy values depend on the specifications of the component. It is therefore good practice to consult the datasheet of the model you are using.

How Do They Communicate with Arduino?

Unlike an analog sensor such as the LDR circuit we saw in Chapter 6, the common DHT11 and DHT22 send their measurements through a digital protocol. Arduino can’t read them simply with analogRead().

To make communication easier, a software library is normally used, which handles the exchange of data and lets us obtain the temperature and humidity values directly.

The typical wiring involves:

  • VCC: power supply, according to the module’s specifications.
  • GND: ground.
  • DATA: the line through which the data is transmitted.

Some modules already include the components needed for the connection; others require a pull-up resistor on the data line. For this reason it is important to check which type of component you have before building the circuit.

How Can We Use the Measurements?

Once we have the values, we can process them in the program in exactly the same way as we do with the readings from other sensors.

For example, Arduino could:

  • show temperature and humidity on an LCD display;
  • turn on an LED when the temperature goes above a set threshold;
  • signal when the relative humidity drops below a chosen value;
  • record the measurements at regular intervals to see how they change over time.

Imagine we want to turn on an LED when the temperature goes above 28 °C (about 82 °F). The program reads the temperature from the sensor and compares the result with the set threshold. If the value is higher than 28 °C, it turns the LED on; otherwise it turns it off.

The logic is similar to what we have already used to control an LED based on brightness. The main difference is the type of data we receive and the way the sensor communicates with Arduino.

A Few Precautions

The measurements from an environmental sensor are only indicative and depend on where the component is placed and the conditions in which it is used. For example, putting the sensor near a heat source, exposing it directly to the sun or placing it in a spot with little air circulation can affect the reading.

In addition, the DHT11 and DHT22 are not professional precision instruments: they are mainly suitable for educational experiments and simple applications.

9.6 Other Useful Arduino Sensors and Modules

Besides the sensors we have already seen, there are many other components that let Arduino detect features of its surroundings and react to specific situations. You don’t need to know them all straight away: what matters is understanding what information they can provide and choosing the component best suited to the project we want to build.

In this section we’ll look at some common examples, useful for widening the possibilities of our experiments.

Infrared Obstacle Detection Sensors

Infrared obstacle detection (or obstacle avoidance) modules are often used in small robots. They generally contain an emitter that sends out infrared light and a receiver that detects the light reflected by an object.

When the module picks up a strong enough reflection, its output changes state and Arduino can interpret the signal. Depending on the model, the sensitivity or detection threshold may be adjustable.

These modules are useful for detecting the presence of an obstacle at a short distance, but they normally don’t give an accurate measurement of the distance the way the HC-SR04 does. Their operation can also be affected by the colour (US: color), shape and reflectivity of the object, as well as by ambient light.

Magnetic Sensors

Magnetic sensors can detect the presence of a magnetic field. Some modules, for example those based on a reed switch, contain two thin metal contacts that move closer together and close when a sufficiently strong magnetic field is present.

These sensors can be used to detect when a door or window is opened, to check the position of a moving part, or to detect a magnet passing by.

A simple application is to fix a magnet to a door and the sensor to the frame. When the door opens or closes, the relative position of the magnet and the sensor changes and Arduino can detect the change.

Not all magnetic sensors work in the same way: some provide a simple digital signal, while others can measure the strength of the magnetic field.

Tilt Sensors

A tilt sensor can detect whether an object is being tilted or has changed orientation. Some simple models contain a small metal ball or an internal contact that changes position when the sensor is tilted.

These devices can be used to build tip-over alarms, to detect the tilt of a container, or to detect the movement of a mechanical part.

The simplest models generally provide a digital signal: they tell you whether a certain position has been reached, but they don’t accurately measure the tilt angle. To measure orientation in more detail, sensors such as accelerometers and inertial measurement units (IMUs) are used, which require a more in-depth treatment.

Sound Sensors

A sound-sensitive module can detect noises and changes in sound pressure. Some modules have a digital output that changes state when the sound goes above a certain threshold; others provide an analog signal related to the sound received.

For example, we can build a project in which an LED turns on when a loud enough noise is detected. However, a simple sound detection module is not necessarily able to recognise (US: recognize) words or to tell one sound from another with any accuracy.

Modules with Built-In Functions

Not all the components used with Arduino are sensors. There are also modules that perform specific functions and make it easier to build circuits.

For example:

  • Relay modules: they let you control a separate electrical circuit using a control signal. For mains voltage (230 V in Europe, 120 V in the US), proper protection and precautions are necessary: they are not suitable for improvised experiments on a breadboard.
  • Bluetooth modules: they allow data to be exchanged wirelessly with compatible devices, for example to send commands or receive information.
  • Rotary encoder modules: they detect the rotation of a knob and, in many cases, the direction of movement. They can be used to change a threshold or select an option.
  • RTC (Real-Time Clock) modules: they keep track of the date and time, even when Arduino is switched off, thanks to a backup battery in the models that have one.

These examples show that Arduino can be connected to a huge number of devices. To choose the right component, you always need to check what it measures or what function it performs, which signals it uses, how it needs to be powered and how it communicates with the board.

How to Choose the Right Sensor

Before starting a project, ask yourself what information you need to obtain. If you want to know the distance to an obstacle, you can use an ultrasonic sensor; if you want to detect a person’s movement, a PIR may be more suitable; if you want to measure the air temperature, you can choose an environmental sensor such as the DHT11 or the DHT22.

Remember that every sensor has specific limitations and that its signal has to be interpreted correctly by the program. Choosing the component is therefore an important part of the design process.

In the next section we’ll put what we have learned into practice, focusing on checking the connections, reading the data and troubleshooting the most common errors when working with sensors.

Infographic showing eight common sensors and modules to connect to an Arduino UNO R3: an infrared obstacle sensor, a magnetic reed switch sensor, a tilt sensor, a sound sensor, a relay module, a Bluetooth module, a rotary encoder and an RTC (Real Time Clock) module. At the bottom, a guide to choosing a sensor based on what it measures, the type of signal, the power supply and the communication method.

 

9.7 Arduino Sensor Exercises and Practice Projects

In this section we’ll put into practice what we have learned about sensors, using Arduino to read information from the environment and react to what happens. The exercises start with the simplest activities and move on to small applications that require you to combine sensors, conditions and outputs.

For each exercise, first try to work out how the system should behave. Then prepare the connections, write the program and check the result. If something doesn’t work, apply the troubleshooting method we saw in the previous section.

Exercise 1 — Measuring Different Distances

Use the HC-SR04 circuit and program from section 9.3.

  1. Place an object in front of the sensor, at about 10 cm.
  2. Read the value shown on the Serial Monitor.
  3. Repeat the test at about 20, 30 and 50 cm.
  4. Compare the distances estimated by Arduino with those measured using a ruler.

Questions:

  • Do the measured values exactly match those on the ruler?
  • What conditions can affect the measurement?
  • What happens if you tilt the object or move it to one side?

Exercise 2 — Signalling (US: Signaling) an Obstacle with an LED

Modify the HC-SR04 program so that the LED connected to pin 13 turns on when an object is less than 20 cm from the sensor.

The program will have to:

  • read the distance;
  • turn the LED on if the distance is valid and less than 20 cm;
  • turn the LED off when the object is further away or no valid echo is detected.

Hint: use an if condition and check the value returned by pulseIn(). If the duration is zero, you must not interpret it as a distance of zero centimetres.

Exercise 3 — Detecting Movement with the PIR

Connect a PIR module to Arduino following the instructions in section 9.4. Use digital pin 2 for the OUT signal and the board’s built-in LED on pin 13.

Write a program that turns the LED on when the sensor signals movement and turns it off when the signal goes back to LOW.

Before checking the result, wait for the warm-up time the module needs to settle. Then try moving around within its detection range and watch how the LED behaves.

Questions:

  • Does the LED turn on as soon as Arduino is powered up?
  • Does it stay on for as long as you keep moving?
  • Can the PIR tell you how far away the person is?

Exercise 4 — Monitoring the Temperature

If you have a DHT11 or DHT22 sensor, connect it to Arduino and use a compatible library to read temperature and relative humidity.

Show the two values on the Serial Monitor, clearly indicating the units of measurement: °C for temperature and % for relative humidity.

As a variation, add a condition that displays the message High temperature when the temperature goes above 28 °C (about 82 °F).

Note: if you don’t have a DHT sensor, you can do the exercise by describing the logic of the program, or come back to the circuit when you have the component.

Exercise 5 — Choosing the Right Sensor

For each situation, say which of the sensors we have studied you would choose and briefly explain why.

  • Automatically turning on a light when a person walks into a room.
  • Measuring the distance between a robot and an obstacle.
  • Turning on an LED when the room gets too dark.
  • Displaying the temperature and humidity of the air.
  • Detecting the opening of a door fitted with a magnet.

There isn’t always just one possible solution, but your choice has to be consistent with the information the system needs to obtain.

Final Challenge — An Obstacle Detection System

Build a small system with an Arduino UNO R3, an HC-SR04 and an LED. The system must continuously measure the distance and signal when an object gets closer.

Define three behaviours (US: behaviors):

  • Distance greater than 40 cm: LED off.
  • Distance between 20 and 40 cm: LED flashing.
  • Distance less than 20 cm: LED on continuously.

If no valid echo is detected, the program must not treat the reading as a real distance.

To complete the challenge you will need to use variables, conditions and loops. For the flashing you can use delay() or, as a more advanced option, millis() to manage the timing without blocking the program during each pause.

Chapter Conclusion

In this chapter we have met several sensors that allow Arduino to gather information about its surroundings. We took a closer look at how the HC-SR04 ultrasonic sensor works, saw how to detect movement with a PIR, and discovered a few sensors for temperature, humidity and other quantities.

We have also learned that every sensor has its own way of communicating, a field of use and limitations to take into account. The program has to read the signal it receives correctly and turn it into a useful decision.

In the coming chapters we’ll be able to use this knowledge to connect other devices to Arduino, display information and build systems that can react to environmental conditions. Sensors are, after all, one of the fundamental elements of robotics: they allow a machine to obtain information about the world around it.

Infographic with the exercises from the Arduino sensors chapter: 1. measuring distances with the HC-SR04, 2. an LED on pin 13 that lights up when an obstacle is closer than 20 cm, 3. motion detection with the PIR sensor, 4. reading temperature and humidity with a DHT11 or DHT22, 5. choosing the right sensor. At the bottom, the final challenge: an obstacle detection system with three zones (over 40 cm LED off, 20–40 cm LED blinking, under 20 cm LED steady on).

Coming up in the next chapter...

So far, Arduino has mostly been a careful observer: it has measured distances, spotted movement and read temperature and humidity. In the next chapter, Chapter 10 - Arduino Actuators: Make a Buzzer Beep and Control a Servo Motor (SG90), it takes the next step and learns to react to what it senses.

We’ll find out how to give our circuits a voice with a small buzzer that can play tones, beeps and warning signals, and even a proper alarm. Then we’ll move from sound to motion, with a tiny servo motor that turns to exactly the position we ask for: first following the instructions in our code, then obeying a simple twist of a knob.

By the end of the chapter, you’ll have built your first projects where a sensor makes the decision and a component takes action. It’s a big step towards the final robotics project of the course.

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)

Warning!

The advice and instructions provided on this site come from hobbyists rather than professional technicians, meaning there is no guarantee that they are accurate or represent the best solution.
Additionally, using the tools and techniques described here should be done with careful consideration of one’s own abilities.
These articles assume that the tasks will be performed by individuals with the necessary skills and knowledge to use the required tools safely, without risking harm to themselves, others, or property.
Therefore, the owners of this site cannot be held responsible for any direct or indirect damages resulting from the application of the content found here.
Before undertaking any DIY activity, it is strongly recommended to read the Safety Notice, which provide a basic (though non-exhaustive) list of precautions to follow.

Copyright

The republication of full articles is strictly prohibited. However, it is permitted to publish brief excerpts of the articles or images, provided that the source is clearly credited at the end. This must include a hyperlink directing readers to the original page from which the content was taken.

The site icon ilsitodelfaidate.it was downloaded from 123rf.com. © captainvector, 123RF Free Images

Disclaimer

Privacy Policy

Cookie Policy

Terms and Conditions

Consent Preferences