Logo ilsitodelfaidate.it

11.1 From a Simple Circuit to an Integrated System

In the previous chapters we’ve learnt to use a whole range of electronic components with Arduino: we’ve read the values from a light sensor, measured distance with an ultrasonic sensor, shown information on an LCD display, and controlled actuators such as LEDs, buzzers and servo motors.

So far we’ve often looked at these components one at a time, building small circuits and programs dedicated to a single job. Now it’s time to take a step forward and learn how to get several components working together in the same project.

An integrated system is a set of elements that work together to get a job done. In our case, the Arduino is the control hub: it receives information from the sensors, processes it by following the instructions in the program, and drives the outputs according to the results.

Inputs, Processing and Outputs

To understand how an integrated system works, we can break it down into three basic parts.

1. Inputs: Gathering Information

Inputs let the Arduino receive information from its surroundings or from the user. A light sensor, for example, can detect changes in lighting, while an ultrasonic sensor can estimate the distance to an object.

A push button (or pushbutton) is an input too: when it’s pressed, it signals a change of state to the system.

2. Processing: Interpreting the Information

The Arduino reads the incoming data and uses it to carry out the instructions in the program. It can compare a value with a threshold, check a condition, update a variable or decide which action to take.

For example, we might decide that if an object is less than 20 cm (about 8 inches) from the sensor, the system should trigger a warning signal.

3. Outputs: Communicating or Taking Action

Outputs let the system produce a result. An LED can light up, a buzzer can make a sound, a display can show a message and a servo motor can move to a preset position.

What happens depends on the instructions in the program and on the information gathered through the inputs.

We can therefore picture the overall workings like this:

Environment → Sensors and inputs → Arduino processes the data → Outputs and actuators → Response

This diagram captures the basic principle behind many programmable electronic systems, from simple control devices to home automation and smart home systems, and even robotics.

A Practical Example: Detecting a Nearby Object

Let’s imagine we want to build a device that shows the distance of an object and sounds an alarm when that object gets too close.

To build it, we can use an HC-SR04 ultrasonic sensor, an Arduino UNO R3 board, a 1602 LCD display and a buzzer.

The way it works can be described in a few steps:

  1. The sensor measures the distance to the object.
  2. The LCD display shows the measured distance.
  3. The program checks whether the distance is less than 20 cm.
  4. If the condition is true, the Arduino turns on the buzzer.
  5. If the distance is 20 cm or more, the buzzer stays off.

Here is a graphical representation of the process we’ll be building:

Flowchart: the ultrasonic sensor measures the distance, the LCD shows it, and the buzzer sounds if it is under 20 cm.

In this example, the sensor doesn’t decide on its own when to make the sound: it provides a measurement, and it’s the program running on the Arduino that decides how to use that data.

It’s also important to consider what happens when the sensor fails to pick up a valid echo. In that case, the program has to recognise that it doesn’t have a reliable measurement, instead of treating the result as if it were a real distance.

The project is simple, but it already contains the essential ingredients of an integrated system: an input that detects a physical quantity, a program that interprets the data, and an output that produces a response.

A Flowchart Unlike the Previous Ones

If we compare this diagram with the flowcharts we’ve seen so far, we notice an important difference. In the previous chapters, each block corresponded to a single operation, usually something that can be written in one or at most two instructions: turning on an LED, reading a button, writing a message to the display.

Here, instead, most of the blocks describe a macro operation, in other words a complete task that needs several instructions. “The ultrasonic sensor measures the distance to the object” is a good example: behind that one sentence are sending the pulse, measuring the duration of the echo, calculating the distance and checking that the measurement is valid.

Describing the system this way has two advantages:

  1. A macro operation can be written as a function in its own right, and that’s the preferable approach: it has a clear job to do and can be called whenever it’s needed.
  2. If necessary, each macro operation can in turn be broken down into a more detailed flowchart, right down to the level of individual instructions.

This is the method used in more complex projects: you start with a general outline showing the macro operations to be carried out, then focus on one smaller, more manageable piece at a time until you’re ready to write its code. We’ll follow the same path: the diagram you’ve just seen is our starting point, and in the next sections we’ll develop its parts one at a time.

Why Integrating Several Components Matters

When we connect several components, it isn’t enough for each one to work properly on its own. We also have to check that they work together the way we intend.

A sensor might give a correct reading, but the program might interpret it wrongly. A buzzer might work perfectly, yet be triggered under the wrong condition. A display might show a value, but fail to update it properly.

For this reason, when designing a project we need to think about both how the individual components work and how the system behaves as a whole.

We’ll learn to proceed step by step, adding one function at a time and checking each stage before moving on. This approach makes it easier to track down errors and helps us understand the role of each part of the project.

Diagram with an Arduino UNO R3 in the centre: inputs on the left (light sensor, ultrasonic sensor, push button), outputs on the right (LED, buzzer, LCD display, servo motor).

In the next section we’ll see how to design a system’s behaviour before writing the program, spelling out what information it needs to collect, which conditions it has to check and which actions it has to carry out.

11.2 Designing the Behaviour of the System

When we’re building an Arduino project, it’s important not to dive straight into writing code. First we need to be clear about what we want to achieve, what information the system has to collect and how it should react in different situations.

This step matters even more when a project involves several components. A sensor can provide a measurement, a program can interpret it, a display can show the result and an actuator can carry out an action. To get all these elements working together properly, we need to organise the system’s behaviour before turning it into instructions.

In this section we’ll see how to start from a goal, break it down into simpler operations and pick out the functions that will let us write a program that’s tidy and easy to test.

Defining the Project Goal

Let’s go back to our example: a device that shows the distance to an object and turns on a buzzer when that distance is less than 20 cm.

Before writing the program, we need to define the behaviour we want:

  • The ultrasonic sensor measures the distance to the object.
  • The LCD display shows the measured distance.
  • The Arduino checks that the measurement is valid.
  • If the measurement is valid, the program compares the distance with the 20 cm threshold.
  • If the object is less than 20 cm away, the buzzer sounds.
  • If the object is 20 cm or more away, the buzzer stays off.
  • If the measurement isn’t valid, the program must not treat it as a real distance, and keeps the buzzer off.

These points make up a first description of how the system behaves. We haven’t written any code yet, but we already know which operations it will have to perform and which results we’ll need to check.

Note that we’ve also decided what to do when a measurement isn’t valid. Settling these situations in advance stops the program from behaving unpredictably when the sensor fails to pick up an echo.

Breaking the Problem Down into Simpler Tasks

Once the goal is defined, we can work out which operations are needed to achieve it. When a problem gets complicated, it’s always good practice to break it down into smaller sub-tasks that are easier to manage.

In our example we can identify four main tasks:

  1. Acquiring the distance. The program has to send the command to the HC-SR04 sensor, measure the duration of the echo and calculate the distance. It also has to tell a valid measurement apart from the absence of a valid echo.
  2. Displaying the distance. When the measurement is valid, the program shows it on the LCD display.
  3. Deciding what to do. The program uses the measured distance to decide whether the object is close enough to call for a warning.
  4. Driving the buzzer. Depending on the outcome of that decision, the program turns the sound on or keeps it off.

This breakdown is useful because each task has a clear purpose and can be tested separately. For example, we can first check that the sensor measures distances correctly, and then check that the buzzer responds to the conditions we’ve set.

From Flowchart to Program

The tasks we’ve just identified correspond to the macro operations in the flowchart from the previous section. Each of them has three characteristics that make it suitable to become a self-contained part of the program:

  1. it performs one specific task;
  2. it has well-defined boundaries;
  3. it communicates with the rest of the program by exchanging just a few pieces of data, known as parameters.

That’s why we can match each macro operation with a dedicated function and end up with a tidier program.

Organising the Program with Functions

One possible way to organise it is as follows:

  • readDistance() takes care of acquiring the measurement from the ultrasonic sensor.
  • updateDisplay() shows the measured distance on the LCD display.
  • checkBuzzer() decides whether to turn the buzzer on or off based on the distance and on whether the measurement is valid, so it combines the third and fourth tasks.
  • loop() coordinates the operations, calling the functions in the order required.

Each function looks after its own task only. readDistance() simply reads the sensor and returns the result: it doesn’t decide whether the buzzer should sound, and it doesn’t worry about displaying the measurement. updateDisplay() receives the measurement that has already been taken, takes care of formatting it and sends it to the display, without knowing how it was obtained. In the same way, checkBuzzer() doesn’t generate the ultrasonic measurement: it receives the data it needs and uses it to drive the actuator.

This separation of acquisition, display, decision and action is one of the fundamental principles of modular programming.

What It Means to Coordinate Functions

Functions don’t necessarily work independently: often one produces a piece of data that another one needs to use.

In our example, the function that reads the sensor has to supply the measured distance. The function that controls the buzzer uses that value to make a decision.

So we need to decide what information a function should receive and what results it should return.

A function can, for instance, receive a distance as a parameter:

void checkBuzzer(float distance, bool validMeasurement) {

// The conditions to control the buzzer

// will go here.

}

In this example, distance is the measured value, while validMeasurement tells us whether we can use that value. The float type can also represent distances with decimal places, whereas bool can only take two values: true or false.

The function shown here is only an example declaration of the job to be done: its full behaviour will be implemented when we write the system’s program.

Why This Approach Makes Debugging Easier

Imagine the buzzer doesn’t turn on when an object gets close.

If the program is organised into functions, we can check each part in turn:

  • Does the readDistance() function return a correct measurement?
  • Is the measurement recognised as valid?
  • Is the condition that compares the distance with the threshold correct?
  • Is the checkBuzzer() function being called, and is it driving the right pin?

We can temporarily add messages to the Serial Monitor to see the values being passed around and work out which step isn’t doing what we expect.

This approach won’t get rid of every error, but it helps us narrow down the possible causes. Instead of rereading one long block of code, we can concentrate on the function responsible for the task in question.

Before Writing the Code

Before starting a new project, let’s get into the habit of answering these questions:

  1. What result do we want to achieve?
  2. Which inputs does the system need to read?
  3. Which conditions does it need to check?
  4. Which outputs or actuators does it need to control?
  5. Which functions can we create to keep the tasks separate?
  6. How can we check that each function, and the system as a whole, works correctly?

This method will become more and more useful as we add components to our project.

Four-step diagram (goal, split into tasks, functions, testing): the four tasks are measuring the distance, showing it on the display, deciding and driving the buzzer.

In the next section we’ll start building the system for real, beginning with reading the distance using the HC-SR04 sensor. We’ll go one function at a time: for each one we’ll first draw a detailed flowchart and then write the code, gradually updating the program with the display and the buzzer.

11.3 Reading and Interpreting a Measurement

In Chapter 9 we learnt how to use the HC-SR04 ultrasonic sensor to measure the distance to an object. Now we’ll pick that component up again, but with an extra goal: organising the program in a modular way, keeping the reading of the sensor separate from everything else.

This separation will be essential in our integrated project. Before long we’ll want to show the distance on the display and sound a buzzer when an object is close. If reading the distance is handled by a dedicated function, we can reuse it without having to rewrite the instructions needed to query the sensor every time.

We’ll build our system step by step, following the organisation into functions we saw in section 11.2. From here on, each section develops one of the three functions and builds on the previous program by adding the new one, until we reach the complete program in section 11.5. Each time we’ll also update setup() and loop(), which will have to call the new functions.

Section Function we add The program at the end of the section
11.3 readDistance() Measures the distance and writes it to the Serial Monitor
11.4 updateDisplay() Also shows the distance on the LCD display
11.5 checkBuzzer() Also turns on the buzzer if the object is less than 20 cm away

 

So in this section we’re taking the first step: the readDistance() function.

Setting Up the Circuit

For this first activity we’ll use:

  • An Arduino UNO R3 board.
  • An HC-SR04 ultrasonic sensor.
  • A breadboard, if it helps keep the connections tidy.
  • Four jumper wires.

Let’s connect the sensor as follows:

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

 

Let’s double-check the connections carefully before powering up the circuit. The standard HC-SR04 sensor works with the 5 V signals of the Arduino UNO R3; other models or other boards may need different connections.

Wiring diagram: the HC-SR04 sensor on a breadboard connected to an Arduino UNO R3, with Trig to pin 9, Echo to pin 10, VCC to 5V and GND to GND.

Creating a Function to Read the Distance

In Chapter 9 we used the instructions needed to send a pulse on the TRIG pin, measure the duration of the signal on the ECHO pin and calculate the distance.

Now let’s gather these operations into a function called readDistance(). Its job will be solely to take the measurement and return the result. Before writing any code, though, let’s follow the method from section 11.2 and draw the function’s flowchart.

Drawing the Flowchart

The first macro operation in the general flowchart from section 11.1 is “The ultrasonic sensor measures the distance to the object”. As we’ve seen, several instructions hide behind this block, so we’ll develop it into a more detailed flowchart dedicated to the readDistance() function alone:.

Flowchart of readDistance(): it sends a pulse on the TRIG pin, measures the echo duration and, if the measurement is valid, returns the distance, otherwise -1.

Following the flowchart, the function:

  1. sends a short pulse on the TRIG pin;
  2. measures how long the ECHO pin stays active, waiting 30 milliseconds at most;
  3. checks whether the echo has been received;
  4. if the echo hasn’t arrived, returns the value -1.0 to signal an invalid measurement; otherwise it calculates the distance in cm and returns it.

Notice that each block now corresponds to one or two instructions, just like in the flowcharts from the previous chapters, and that the function has two possible outcomes: a real distance or -1.0. With this diagram in hand, writing the code becomes a matter of simple translation.

Writing the Program

Let’s now turn the flowchart into code. The program contains the readDistance() function, which takes the measurement, and a loop() that calls it and writes the result to the Serial Monitor:

/* ==============================================================
Exercise No. 11.3
Purpose: Detects the distance with an HC-SR04 Ultrasonic Sensor
         and writes the value to the Arduino IDE Serial Monitor.
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;
const int echoPin = 10;
/* --------------------------------------------------------------------
FUNCTION: readDistance
Reads and calculates the distance using an HC-SR04 sensor.
Parameters:
  none
Return value:
  float - Distance in cm, or -1 if no echo is received
------------------------------------------------------------------ */
float readDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  unsigned long duration = pulseIn(echoPin, HIGH, 30000UL);
  if (duration == 0) { // error: no echo received
    return -1.0;
  }
  return duration / 58.0;
}

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  float distance = readDistance();
  if (distance >= 0) {
    Serial.print(“Distance: “);
    Serial.println(distance);
  } else {
    Serial.println(“No echo”);
  }
  delay(300);
}

Let’s upload the program and open the Serial Monitor, setting the speed to 9600 baud. As we move an object closer to the sensor and further away, we should see the displayed distance change.

The measurement depends on the characteristics of the object and on the conditions of the environment. The standard sensor has an indicative operating range of roughly 2–400 cm (about 1 in to 13 ft), but it can’t guarantee a correct reading in every situation.

Breaking Down the readDistance() Function

Let’s read the code again alongside the flowchart: each block corresponds to one or two instructions.

The function starts with this declaration:

float readDistance() {

The word float means that the function returns a number that can have a decimal part. The name readDistance describes what the function does, while the empty parentheses show that it doesn’t need to receive any parameters in order to run.

Inside it we find the instructions that generate the pulse on the TRIG pin and measure the duration of the ECHO signal. The pulseIn() function waits for a pulse and measures how long it lasts; in this program the maximum waiting time is 30,000 microseconds, that is, 30 milliseconds.

The variable:

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

stores the duration of the pulse in microseconds. We use unsigned long because time is a non-negative value and can exceed the limit of a smaller integer type. The UL suffix indicates that the numeric value is of type unsigned long.

If pulseIn() doesn’t detect the pulse within the set time, it returns 0. That’s why we check the result:

if (duration == 0) {
  return -1.0;
}

In this case the function returns -1.0 to signal that no valid measurement is available. It doesn’t mean the object is at a negative distance: it’s simply a conventional value chosen to tell an error apart from a real distance.

If, on the other hand, the measurement is valid, we carry out the calculation:

return duration / 58.0;

The result is an estimate of the distance in cm. Dividing by 58 is an approximate formula commonly used with the HC-SR04.

The return keyword therefore does two important things: it hands the result back to whoever called the function, and it ends the function’s execution.

How We Use the Result in loop()

In the main loop we find:

float distance = readDistance();

This statement calls the readDistance() function and stores the value it returns in the distance variable.

Next, the program checks whether the result is valid:

if (distance >= 0) {
  Serial.print(“Distance: “);
  Serial.print(distance);
  Serial.println(“ cm”);
} else {
  Serial.println(“No echo”);
}

If the function has returned a valid distance, the program shows it on the Serial Monitor. If it has returned -1.0, it displays an error message instead.

Notice that the function dedicated to the sensor doesn’t decide what to display and doesn’t control any actuator. It only takes the measurement and returns the result. This way we can reuse it in other programs, leaving it to the other functions to interpret the data.

Why This Structure Is Useful

Suppose that, in the complete project, the display shows the wrong distance. We can start by checking the result returned by readDistance() using the Serial Monitor.

If the value is already wrong at this stage, we can focus on the sensor, the connections and the calculation. If, on the other hand, the distance is correct on the Serial Monitor but not on the display, we’ll need to check the part of the program that updates the screen.

This separation doesn’t automatically solve every problem, but it lets us examine one part of the program at a time, making the search for errors simpler and more orderly.

With this activity we’ve completed the first step of our system: the program can measure the distance and report the result on the Serial Monitor.

In the next section we’ll use the value returned by readDistance() to add the second function, updateDisplay(), which will show the distance on the LCD display. The measuring function will stay unchanged: we’ll just add the new one alongside it and update setup() and loop().

11.4 Showing Information on the LCD Display

In the previous section we developed the first function of our system, readDistance(), which acquires the distance measured by the HC-SR04 ultrasonic sensor. We’re now at the second step of the journey: starting from that program, we add the updateDisplay() function, which shows the distance on the 1602 (16x2) LCD display with an I2C interface that we already used in Chapter 7.

Our aim is to show the detected distance on the display, so that we can read the result directly on the device without having to keep the computer’s Serial Monitor open.

The program from section 11.3 won’t be rewritten: readDistance() stays unchanged and we simply add the new function alongside it. This way each part keeps a clear job and can be tested separately.

Connecting the LCD Display

On top of the circuit with the HC-SR04 that we’ve already built, we add a 1602 LCD display with an I2C interface.

The connections to the Arduino UNO R3 are as follows:

Display pin Connection to Arduino UNO R3
GND GND
VCC 5V, if supported by the module
SDA SDA or A4
SCL SCL or A5

 

Let’s remember that on the Arduino UNO R3 board the SDA and SCL pins correspond to A4 and A5 respectively. We can use the dedicated SDA and SCL pins or their equivalents, depending on the layout of the board.

The display has to be compatible with the power supply being used, and the library installed in the IDE has to support the module. In the example below we’ll use the LiquidCrystal_I2C library and the address 0x27, which is common but not universal: if the display doesn’t work, we may need to check its address and the compatibility of the library.

Wiring diagram: a 1602 I2C LCD display is added to the HC-SR04 circuit and connected to an Arduino UNO R3, with SDA to A4, SCL to A5, VCC to 5V and GND to GND.

Creating a Function to Update the Display

The function that reads the distance stays the one we developed in the previous section. Now we add a second function, called updateDisplay(), which receives the distance value and the information about whether it’s valid. Once again we start from the flowchart.

Drawing the Flowchart

The second block of the general flowchart in section 11.1 is “The LCD display shows the measured distance”. As with the previous function, we develop the macro operation into a more detailed flowchart, dedicated to the updateDisplay() function:

Flowchart of updateDisplay(): it writes “Distance:” on the first line and, on the second, the distance in cm if the measurement is valid, otherwise “No echo”.

The function receives two pieces of information, the distance and whether it’s valid, and uses them to decide what to write on the display:

  1. it always writes the title “Distance:” on the first line;
  2. if the measurement is valid, it writes the value with one decimal place on the second line, followed by “cm”;
  3. if the measurement isn’t valid, it writes the message “No echo” on the second line.

Notice that the function doesn’t take any measurement: it just receives the data and displays it. That’s why its flowchart is independent of the one for readDistance(), and we can develop and test the two functions one at a time.

Writing the Program

Now let’s add the code. Compared with the program in the previous section, the new elements are:

  • the two libraries Wire.h and LiquidCrystal_I2C.h and the creation of the lcd object;
  • the new updateDisplay() function;
  • the initialisation of the display in setup();
  • the validMeasurement variable and the call to updateDisplay() in loop().

The readDistance() function stays exactly the same. The complete program now becomes:

/* ==============================================================
Exercise No. 11.4
Purpose: Detects the distance with an HC-SR04 Ultrasonic Sensor
         and shows the value on the 1602 LCD display.
Board: Arduino UNO R3
Author: Luciano (Capitan Farloc)
Version: 1.0
Connections:
  - HC-SR04 Distance Sensor
    - Trig: Digital pin 9
    - Echo: Digital pin 10
  - 1602 LCD Display
    - SDA: Analog pin A4
    - SCL: Analog pin A5
============================================================ */
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int trigPin = 9;
const int echoPin = 10;
LiquidCrystal_I2C lcd(0x27, 16, 2);
/* --------------------------------------------------------------------
FUNCTION: readDistance
Reads and calculates the distance using an HC-SR04 sensor.
Parameters:
  none
Return value:
  float - Distance in cm, or -1 if no echo is received
------------------------------------------------------------------ */
float readDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  unsigned long duration = pulseIn(echoPin, HIGH, 30000UL);
  if (duration == 0) {
    return -1.0;
  }
  return duration / 58.0;
}
/* --------------------------------------------------------------------
FUNCTION: updateDisplay
Sends a message to the LCD display with the distance received as input
Parameters:
  float – Distance to display
  bool – TRUE if the measured distance is valid
         FALSE if the measurement was unsuccessful
Return value:
  none
------------------------------------------------------------------ */
void updateDisplay(float distance, bool validMeasurement) {
 lcd.setCursor(0, 0);
  lcd.print(“Distance:”);
  lcd.setCursor(0, 1);
  if (validMeasurement) {
    lcd.print(distance, 1);
    lcd.print(“ cm “);
  } else {
    lcd.print(“No echo”);
  }
}

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  lcd.clear();
}

void loop() {
  float distance = readDistance();
  bool validMeasurement = distance >= 0;
  updateDisplay(distance, validMeasurement);
  if (validMeasurement) {
    Serial.print(“Distance: “);
    Serial.print(distance);
    Serial.println(“ cm”);
  } else {
    Serial.println(“No echo”);
  }
  delay(300);
}

After uploading the program, the display should show the text Distance: on the first line and the measured value on the second. If no valid echo is detected, a message will appear to signal the problem.

Breaking Down the updateDisplay() Function

Let’s compare the code with the flowchart: the decision “is the measurement valid?” corresponds to the if statement, while the two branches write either the value or the error message on the second line.

The function starts with this declaration:

void updateDisplay(float distance, bool validMeasurement) {

The word void means that the function doesn’t return a value. Its job is to update the display.

The function receives two parameters:

  • distance, of type float, holds the measured distance;
  • validMeasurement, of type bool, indicates whether the result can be considered a valid measurement.

This way the function doesn’t have to take the measurement itself and doesn’t need to know the details of how the sensor works. It simply receives the information it needs to display the result.

The instructions:

lcd.setCursor(0, 0);
lcd.print(“Distance:”);

place the cursor at the first column of the first line and display the text Distance:.

On the 1602 LCD display the columns are numbered 0 to 15 and the lines 0 to 1. So setCursor(0, 1) places the cursor at the start of the second line.

When the measurement is valid, we use:

lcd.print(distance, 1);
lcd.print(“ cm “);

The second parameter of lcd.print() specifies the number of decimal places to display. In this case we show a single decimal place.

The spaces added after cm are there to wipe out any characters left over from a previous measurement. For example, if 125.0 cm is shown first and then 9.5 cm, the earlier characters mustn’t be left on the display.

If the measurement isn’t valid, the function displays an alternative message on the second line:

lcd.print(“No echo”);

We’ve chosen a short message because the 1602 LCD display has only 16 characters per line. A message like “Invalid measurement”, which is 19 characters long, wouldn’t fit. For a project meant for practical use, it’s always best to choose messages that fit within the 16 columns available.

How the Functions Work Together

In the main loop we find:

float distance = readDistance();
bool validMeasurement = distance >= 0;
updateDisplay(distance, validMeasurement);

The first statement calls the function that reads the sensor. The second checks whether the result is valid, while the third passes the information on to the function that updates the display.

Notice that loop() doesn’t contain the detailed instructions for measuring the distance or for writing to the display. It simply coordinates the operations.

Compared with the previous section, loop() has changed very little: we’ve added the validMeasurement variable and the call to updateDisplay(). Everything else is as it was.

This structure makes the program more readable and lets us change how the information is displayed without touching the measuring function. In the same way, we’ll be able to add the buzzer in a separate function, keeping the different tasks independent.

Testing and Fixing the Program

Once the code is uploaded, let’s run a few checks:

  1. Let’s move an object closer to the sensor and further away, and see whether the value on the display changes.
  2. When possible, let’s compare the value shown on the display with the one on the Serial Monitor.
  3. If the display lights up but shows no text, let’s check the contrast, the I2C address and the compatibility of the library.
  4. If the value doesn’t change, let’s check the TRIG and ECHO connections and make sure the sensor is working.
  5. If leftover characters remain in the text, let’s check the spaces used to clear the previous digits and the length of the messages.

If the distance is correct on the Serial Monitor but not on the display, we can concentrate on the updateDisplay() function. If both show a wrong result, it’s best to check the sensor reading first.

With this activity we’ve added the second function to our system, keeping data acquisition and data display separate. The readDistance() function has stayed unchanged: all we had to do was add updateDisplay() alongside it and call it from loop().

In the next section we’ll add the third and final function, checkBuzzer(), which uses the measured distance to sound a warning when an object gets too close. That way the system will start giving both visual feedback and an audible response.

11.5 Adding a Warning Signal

In the previous section we combined the HC-SR04 ultrasonic sensor with the LCD display, ending up with a system that can measure the distance and show it on the screen. We’re now at the last step of the journey: after readDistance() and updateDisplay() we add the third function, checkBuzzer(), which lets the device give an audible warning when an object gets too close.

This change lets us explore an important aspect of programming: using the same piece of data to control several different outputs. The distance measured by the sensor will be used both to update the display and to decide whether to turn on the buzzer.

We’ll keep organising the code into functions, with the sensor, the display and the buzzer each having its own job.

By the end we’ll have the complete program for the system described in sections 11.1 and 11.2.

Connecting the Buzzer

We keep the connections we’ve already made for the HC-SR04 sensor and the LCD display. Now we add a passive buzzer that can be driven directly by an Arduino UNO R3.

For this example we’ll use digital pin 8:

  • Positive terminal of the buzzer to digital pin 8.
  • Negative terminal of the buzzer to the GND pin.

Let’s check the manufacturer’s instructions, because the connection may vary depending on the component. If the buzzer needs more current than an Arduino pin is allowed to supply, we’ll have to use a suitable driver circuit.

Wiring diagram: a buzzer is added to the HC-SR04 and 1602 I2C LCD circuit, connected to digital pin 8 of an Arduino UNO R3 and to GND.

Defining the Behaviour of the System

Before changing the program, let’s decide what should happen:

  • If the measurement isn’t valid, the buzzer stays off and the display signals the problem.
  • If the distance is less than 20 cm, the buzzer sounds.
  • If the distance is 20 cm or more, the buzzer stays off.
  • The display keeps showing the distance when the measurement is valid.

The 20 cm threshold is a value chosen for our experiment. In a real application we might need to change it, depending on how the device is used and on the characteristics of the sensor.

Creating a Function to Control the Buzzer

We add the checkBuzzer() function to the program. Its job is to receive the distance and the information about whether the measurement is valid, and then decide whether to turn the sound on or off.

Drawing the Flowchart

The checkBuzzer() function combines the last two macro operations of the general flowchart in section 11.1: deciding whether the object is close enough, and driving the buzzer accordingly. The detailed flowchart adds a check that we set out in section 11.2, the one on the validity of the measurement:

Flowchart of checkBuzzer(): if the measurement is not valid or the distance is not below the threshold the buzzer is switched off, otherwise it sounds at 1000 Hz.

The function receives the distance and whether it’s valid, and works as follows:

  1. if the measurement isn’t valid, it switches the buzzer off;
  2. otherwise it compares the distance with the 20 cm threshold;
  3. if the distance is below the threshold, it turns the sound on;
  4. otherwise, it switches the buzzer off.

The flowchart contains two decisions in sequence: the second is made only if the first one came out positive. Notice also that the buzzer is switched off at two different points in the flowchart, and we’ll find that again in the code, with two noTone() statements.

Writing the Function

Let’s turn the flowchart into code. Besides the function, we define two constants: the buzzer pin and the distance threshold.

const int buzzerPin= 8;
const float distanceThreshold= 20.0;

void checkBuzzer(float distance, bool validMeasurement) {
  if (!validMeasurement) {
    noTone(buzzerPin);
  } else if (distance< distanceThreshold) {
    tone(buzzerPin, 1000);
  } else {
    noTone(buzzerPin);
  }
}

This function uses two parameters: distance, which holds the measured value, and validMeasurement, which indicates whether we can use that value.

The first condition checks whether the measurement isn’t valid. The ! operator means negation, so !validMeasurement is true when validMeasurement is false. In this case the buzzer is switched off.

The second condition checks whether the distance is below the set threshold. If it is, the tone() function generates a 1000 Hz signal on pin 8, producing a sound from the passive buzzer.

In all other cases noTone() is executed, which stops the sound signal.

We’ve now gathered all the instructions needed for the buzzer into a dedicated function. If we later want to change the threshold or the frequency of the sound, we can work on this part of the program without touching the function that reads the sensor.

Adding the Buzzer to the Program

Now we put the three functions developed in sections 11.3, 11.4 and 11.5 together in a single program. Compared with the program in the previous section, the new elements are:

  • the buzzerPin and distanceThreshold constants;
  • the new checkBuzzer() function;
  • setting the buzzer pin as an output in setup();
  • the call to checkBuzzer() in loop().

We’ve also reduced the final pause in loop() from 300 to 100 milliseconds, so the buzzer reacts more quickly when an object gets close. The readDistance() and updateDisplay() functions stay unchanged. The complete code is as follows:

/* ==============================================================
Exercise No. 11.5
Purpose: Detects the distance with an HC-SR04 Ultrasonic Sensor
         and shows the value on the 1602 LCD display; if the distance is
         less than 20 cm, a buzzer alarm is triggered.
Board: Arduino UNO R3
Author: Luciano (Capitan Farloc)
Version: 1.0
Connections:
  - HC-SR04 Distance Sensor
    - Trig: Digital pin 9
    - Echo: Digital pin 10
  - 1602 LCD Display
    - SDA: Analog pin A4
    - SCL: Analog pin A5
  - Buzzer: Digital pin 8
============================================================ */
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 8;
const float distanceThreshold = 20.0;
LiquidCrystal_I2C lcd(0x27, 16, 2);
/* --------------------------------------------------------------------
FUNCTION: readDistance
  Reads and calculates the distance using an HC-SR04 sensor.
Parameters:
  none
Return value:
  float - Distance in cm, or -1 if no echo is received
------------------------------------------------------------------ */
float readDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  unsigned long duration = pulseIn(echoPin, HIGH, 30000UL);
  if (duration == 0) {
    return -1.0;
  }
  return duration / 58.0;
}
/* --------------------------------------------------------------------
FUNCTION: updateDisplay
  Sends a message to the LCD display with the distance received as input
Parameters:
  float – Distance to display
  bool – TRUE if the measured distance is valid
         FALSE if the measurement was unsuccessful
Return value:
  none
------------------------------------------------------------------ */
void updateDisplay(float distance, bool validMeasurement) {
  lcd.setCursor(0, 0);
  lcd.print(“Distance:”);
  lcd.setCursor(0, 1);
  if (validMeasurement) {
    lcd.print(distance, 1);
    lcd.print(“ cm “);
  } else {
    lcd.print(“No echo”);
  }
}
/* --------------------------------------------------------------------
FUNCTION: checkBuzzer
  Turns the buzzer on or off depending on the distance received and on
  whether the measurement is valid
Parameters:
  float – Distance to check in order to trigger the alarm
  bool – TRUE if the measured distance is valid
         FALSE if the measurement was unsuccessful
Return value:
  none
------------------------------------------------------------------ */
void checkBuzzer(float distance, bool validMeasurement) {
  if (!validMeasurement) {
    noTone(buzzerPin);
  } else if (distance < distanceThreshold) {
    tone(buzzerPin, 1000);
  } else {
    noTone(buzzerPin);
  }
}

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  lcd.clear();
}

void loop() {
  float distance = readDistance();
  bool validMeasurement = distance >= 0;
  updateDisplay(distance, validMeasurement);
  checkBuzzer(distance, validMeasurement);
  if (validMeasurement) {
    Serial.print(“Distance: “);
    Serial.print(distance);
    Serial.println(“ cm”);
  } else {
    Serial.println(“No echo”);
  }
  delay(100);
}

The complete program brings together the three functions developed along the way: readDistance() takes the measurement, updateDisplay() shows it and checkBuzzer() decides whether to sound the alarm. It’s loop() that coordinates them.

How the Program Works

Every time loop() runs, the Arduino calls readDistance() to take a new measurement. The result is stored in the distance variable, while validMeasurement tells us whether the value can be used.

Next, two functions are called:

updateDisplay(distance, validMeasurement);

checkBuzzer(distance, validMeasurement);

The first updates the information on the display, while the second looks after the buzzer. Both receive the same data, but use it for different purposes.

This is an important feature of modular programming: one function can produce a piece of data that is used by several parts of the program, without each part having to repeat the same measurement.

Also, if the buzzer doesn’t behave properly, we can check the checkBuzzer() function on its own, verifying the threshold, the conditions and the connection to pin 8.

Testing the System

Once we’ve checked the connections and uploaded the program, let’s run a few tests:

  1. Let’s place an object more than 20 cm away and check that the buzzer stays off.
  2. Let’s slowly bring the object closer and see when the sound starts.
  3. Let’s move the object away again and check that the buzzer switches off.
  4. Let’s change distanceThreshold, for example setting it to 30 cm, and repeat the tests.
  5. Let’s check that the display keeps updating the distance while the buzzer is sounding.

The measurement may vary slightly because of the characteristics of the sensor and the surface of the object. For this reason, if the distance is close to the threshold, the buzzer might switch on and off rapidly. In a more advanced system we could introduce a margin between the activation threshold and the deactivation threshold to make the behaviour more stable.

With this activity we’ve completed the first version of our integrated system: three functions, each with a clear job and its own flowchart, coordinated by loop(). The buzzer has been added to a project that was already working, without rewriting the part dedicated to the sensor. Now that the system is complete, in the next section we’ll put it to the test with exercises and design challenges.

11.6 Exercises and Design Challenges

In this chapter we’ve built an integrated system made up of three functions: readDistance(), updateDisplay() and checkBuzzer(). Now we can use it as a base for experimenting.

The exercises that follow start from the complete program in section 11.5 and ask us to modify and extend it. It’s best to tackle them in order, because the difficulty increases gradually.

For each exercise, let’s remember the method we’ve followed throughout the chapter: first we define the behaviour, then we draw the flowchart and finally we write the code. We change one function at a time and test each change before moving on to the next.

Exercise 1 — Changing the Alarm Threshold

In our system the buzzer turns on when the sensor detects an object less than 20 cm away. Let’s change the program so that the alarm goes off when the distance is less than 30 cm (about 12 inches).

Thanks to the distanceThreshold constant, the change takes just one line:

const float distanceThreshold = 30.0;

Questions:

  • Which part of the behaviour changes when we modify this constant?
  • Do we also need to change the function that reads the distance? And the one that updates the display?
  • What should the program do when the measurement isn’t valid?

Exercise 2 — Improving the Information on the Display

Let’s change updateDisplay() so that it shows the distance on the first line and the alarm status on the second. With an object nearby, the display should show, for example:

  • Distance: 15.0 cm
  • ALARM ACTIVE

With an object further away:

  • Distance: 45.0 cm
  • Area clear

If the measurement isn’t valid, the program must show an appropriate message, such as “No echo”, rather than showing a distance that doesn’t exist.

Remember that the display has 16 characters per line: let’s choose short messages and deal with any characters left over from the previous display. To find out whether the alarm is active, the function can compare the distance with the distanceThreshold constant.

Questions:

  • Now the comparison with the threshold appears in both checkBuzzer() and updateDisplay(). What problems could this repetition cause if we later changed the criterion for the alarm?
  • How could we write the condition just once? A hint: a function that returns true or false.

Exercise 3 — Stopping the Buzzer from Switching On and Off Rapidly

In section 11.5 we noticed that when the distance is close to the threshold, the buzzer can switch on and off rapidly. To make it more stable we introduce a margin (known as hysteresis) between the two thresholds:

  • the buzzer switches on when the distance drops below 20 cm;
  • the buzzer switches off only when the distance goes above 25 cm;
  • between 20 and 25 cm the buzzer keeps whatever state it’s in.

To do this we need to remember whether the alarm is active, as we saw in Chapter 8 when talking about the state of a system. Before changing the code, let’s draw the updated flowchart for checkBuzzer().

Questions:

  • Why do we need a variable that remembers the state of the alarm?
  • What happens when the object is at 22 cm? Does it depend on how we got there?
  • Where is it best to declare this variable?

Exercise 4 — Creating Three Distance Zones

Let’s change the system’s behaviour so that it distinguishes three zones:

  • Near zone: distance below 20 cm.
  • Intermediate zone: distance between 20 and 50 cm.
  • Far zone: distance above 50 cm.

Let’s use if, else if and else conditions to choose the message to show on the display. We’ll also give the buzzer a different behaviour for each zone: a continuous sound in the near zone, an intermittent sound in the intermediate zone and no sound in the far zone.

To get the intermittent sound without blocking the program we can use millis(), as we saw in Chapter 8. An invalid measurement has to be handled separately, without placing it in any of the three zones.

Questions:

  • Which functions in the program need to change, and which can stay the same?
  • How does the flowchart for checkBuzzer() change compared with the one in section 11.5?

Exercise 5 — Adding a Function for the Serial Monitor

In the program from section 11.5, the instructions that write to the Serial Monitor are still inside loop(), even though we said that loop() should do no more than coordinate the operations.

Let’s create a fourth function, called for example printSerial(), which receives the distance and whether the measurement is valid, and takes care of writing the message to the Serial Monitor. After the change, loop() should contain only the reading of the measurement and the calls to the other functions.

Questions:

  • Does the system’s behaviour change after this modification?
  • What do we gain in readability?
  • If the Serial Monitor showed a wrong value, which function should we check first?

Final Challenge — Building a Parking Sensor

Using the functions developed in this chapter, let’s design a parking sensor like the ones fitted to many cars. The system will need to:

  1. measure the distance to an obstacle continuously;
  2. show the distance on the display together with a status message, for example “Clear”, “Caution” or “STOP”;
  3. sound the buzzer intermittently, with pauses between beeps that get shorter and shorter as the obstacle gets closer;
  4. emit a continuous sound when the obstacle comes within a safety distance, for example 10 cm;
  5. handle invalid measurements correctly.

As an extra goal, we can store the minimum valid distance detected since power-up and show it on the Serial Monitor. This feature requires comparing each new measurement with the stored value, updating it only if the new measurement is valid and smaller.

There’s no need to build every feature at once. Let’s develop the project in stages: we draw the flowchart for each new or modified function, write the code and check each step before adding the next.

Chapter Conclusion

In this chapter we’ve learnt how to integrate different components into a single system. We designed the behaviour before writing the code, broke it down into macro operations, developed them one at a time with their own flowcharts and turned them into functions coordinated by loop().

We’ve also seen that a project can grow gradually: you start with a simple behaviour, add new functions without rewriting the existing ones, and improve the result through tests and targeted changes.

These skills are the foundation for tackling richer projects, in which sensors and actuators work together to react to what’s happening around them. In the next chapter we’ll add a new element to our system: movement.

Coming up in the next chapter...

For now, this is where the course ends, but another chapter is already in the works: Chapter 12 – ???????? (coming soon). There we’ll take a big step up and put together another integrated system: the prototype of the control system that will let an autonomous, self-driving robot avoid obstacles. That robot will be the main topic of the next course, the Intermediate Robotics Course with Arduino.

I hope to finish this project soon.

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