Sunteți pe pagina 1din 66

DISTANCE MEASUREMENT WITH ARDUINO

Basic use of Arduino and the Ultrasonic Sensor


HC-SR04
Experienced in an application for distance measurement

Universidad Nacional del Callao

Autors:
José Espinoza Castillo
Fabrizzio Castillo Gonzales
José Aquino Buenalaya
Fabricio Zacarías Ramírez

Tutor: Jhino Pardavé Brancacho

Course: English IV

2018
DISTANCE MEASUREMENT WITH ARDUINO

Index of Contents

INTRODUCTION..............................................................................................................1

Current context...............................................................................................................1

Actuality.....................................................................................................................1

Motivation..................................................................................................................2

Free software, open source and free Arduino hardware.............................................3

The Arduino community............................................................................................8

Objectives of the Project..............................................................................................10

Distance measurement with Arduino.......................................................................10

Analysis of benefits..................................................................................................10

Technical means necessary...........................................................................................11

UNO Arduino...........................................................................................................11

Ultrasonic sensor HC-SR04.....................................................................................12

Prototype plate (Protoboard) and cables..................................................................12

Computer..................................................................................................................13

USB Cable................................................................................................................13

Planning........................................................................................................................14

Budget..........................................................................................................................15

Regulatory Framework.................................................................................................17

General Telecommunications Law...........................................................................17

Organic Law on Data Protection..............................................................................18

Law of Environmental Responsibility......................................................................18

Structure of the document............................................................................................18


DISTANCE MEASUREMENT WITH ARDUINO

ARDUINO.......................................................................................................................22

Hardware..................................................................................................................23

Software...................................................................................................................25

Prototype plate..........................................................................................................29

Arduino UNO...............................................................................................................30

Hardware..................................................................................................................31

ULTRASONIC SENSOR.................................................................................................34

Sensors.....................................................................................................................34

Ultrasonic sensors....................................................................................................36

Sensor HC-SR04......................................................................................................39

PROGRAM DESIGN......................................................................................................42

Definition of the System..............................................................................................42

Scope........................................................................................................................44

Restrictions...............................................................................................................44

Circuit diagram.............................................................................................................44

IMPLEMENTATION OF THE PROGRAM...................................................................48

Development environment...........................................................................................48

Installing the Arduino IDE.......................................................................................48

Execution of the Arduino IDE..................................................................................50

Appearance of the Arduino IDE...............................................................................51

General structure of an Arduino sketch....................................................................51

Program code................................................................................................................53

Internal operation of the sensor................................................................................54

Code of the final sketch............................................................................................54


DISTANCE MEASUREMENT WITH ARDUINO

EVALUATION AND RESULTS.....................................................................................57

Tests..............................................................................................................................57

Test 1. From the sensor to a wall 1 [cm] away.........................................................59

Test 2. From the sensor to a wall 3 [cm] away.........................................................59

Test 3. From the sensor to a wall 10 [cm] away.......................................................60

CONCLUSIONS..............................................................................................................61

Reflections....................................................................................................................61

Bibliography.....................................................................................................................63
1

INTRODUCTION

Current context

Actuality

With the growing evolution of ICT (Information and Communication Technologies) in

recent years, we are increasingly, the people who seek to adapt the various technologies and

devices that we have at our disposal, our activities and daily needs. Every day, we use

computers and mobile devices: at home, in the studio, at work, in personal relationships and

in the practice of recreational activities. Choosing the appropriate technology according to

the needs and purposes that we seek to satisfy, will be an important decision that will take

us or

no, to achieve our goals.

On the Internet you can find a lot of information, but it is necessary to contrast it. In

order to carry out any research work, it is therefore essential to consult different sources of

information (and this has been the case in this case, through a multitude of manuals,

websites and forums) before establishing the conclusions that lead us to the choice of one

technology or another.

Different communities or groups of users emerge around the evolution of technology

who want to know how it works, to study it, participate in its implementation or adapt it to
2

their needs. In addition, the increase in the development of free software, open source and

hardware Free, allows to share concerns and knowledge, using the network of networks, the

Internet, as the main means of communication.

Motivation

Since the use of computer science comes hand in hand with the application of other

sciences and nowadays it is applied to all of them, with this work it is about showing how,

choosing the appropriate technology and knowing the limits of it, through of a simple

program (which we will call sketch, since that is how the programs on the Arduino platform

are known), it can be achieved, no need for advanced electronic knowledge, a practical

application such as distance measurement.

After a first research task to find the most suitable technology to measure distances in a

simple, practical and economic way, it was concluded that the most appropriate for our

needs was to rely on Arduino technology. Specifically, an Arduino will be used UNO and

an HC-SR04 ultrasound sensor compatible with it.

Arduino was born to teach Interaction Design (Interaction Design), that is, the design of

any interactive experience (between humans and objects) through a process based on the

creation of loyalty prototypes in constant growth, through electronic technology. Within

Interaction Design, the specific field related to Arduino is Physical Computing or Physical

Interaction Design (Physical Interaction Desing), which uses electronics to create


3

prototypes of new materials for designers and artists, can create interactive objects, which

can communicate with humans through sensors and actuators (or activators) controlled by

software running on a microcontroller (a small computer on a single chip). Through

Arduino, you can learn the basic elements of electronics and sensors quickly, creating

simple prototypes without too much investment.

Free software, open source and free Arduino hardware

The Arduino software is its logical set of instructions (program), integrated into the

development environment (IDE); the hardware is the set of its physical components (the

card itself). The platform or Arduino system is based on free software, open source and

hardware free (although the HC-SR04 sensor, compatible with Arduino, no). These

concepts, which are often related, sometimes lead to confusion. The basic foundations are

explained below.

Free software (free software) provides its users (both individually and collective) the

permanent, irrevocable and unjustified freedom to execute it in any system and for any

purpose; to study it and see how it works; to modify it and improve it, accessing its source

code without having to notify it; copy it, distribute it and publish it (preferably in the form

of executables, which are usually simpler to install) with its corresponding source code,

with or without modifications, without having to ask for permission or pay for it, and

charging, or not, a fee ( because although it is free, it does not have to be free), so that the
4

rest of users (what is known as "the community") continue to benefit from their revisions

and subsequent versions, and in this way, they can control said software and what it does

As it has been explained, for a software to be free software, it must be open source

software. Open source, which arises from the concept of free software, seeks to offer

everyone access to the code, allowing its modification and redistribution. The source code

of Arduino can be downloaded or consulted freely, from its official website1.

There are two non-profit organizations worldwide, the OSI (Open Source Initiative) 2

and the FSF (Free Software Foundation) 3, related to the concept of "free software" (from

the Anglo-Saxon term "free software") and the concept of "open source software" ("open-

source software", in English). In defense of the rights of free software users, they support

and encourage the open source movement, promoting licenses for their free distribution

(among which the GPL and LGPL licenses, under which Arduino stands) stand out.

For legal purposes to speak of free software, it must be subject to some type of

distribution license that characterizes it as such. Some of the free software licenses (and

opensource) best known are: the GPL license, the CC and the BSD. The BSD (Berkeley

Software Distribution) 4, allows derivative works without any restriction, so that the author

only keeps recognition for their contributions. But Arduino, however, uses the other two

(GPL and CC).


5

The GPL (General Public License) 5, arising from the project for the GNU operating

system (from the FSF), seeks to ensure the rights when using, studying, sharing and

modifying code, with the sole obligation that the code derivative, use the same license.

Arduino consists of two licenses of this type: the GPL license and the LGPL license.

- The GPL or General Public License (Version 2, June 1991. Copyright © 1989, 1991

Free Software Foundation, Inc.) 6, establishes eleven terms and conditions regarding Copy,

distribution and modification refers. Under this license is the processing code that, in

general, forms the visual programming environment of Arduino.

- The LGNU license or Less General Public License (Version 2.1, February 1999.

Copyright © 1991, 1999 Free Software Foundation, Inc.) 7, successor to the previous one,

establishes fifteen terms and conditions for copying, distribution and modification. Under

this license are the rest of the libraries and packages, specially designed for the control of

the Arduino microcontroller at an internal level. Both are online8, on the Arduino website

and, in general, on the GNU website.

The CC (Creative Commons) 9 is a non-profit organization that establishes a set of

licenses through which the author of a work can select the rights he wants grant their users,

allowing or not their commercial use, as well as license modifications in derivative works.

Arduino is under the Creative Commons (CC) BY-SA license. "BY" wants say

"Attribution" (for recognition of authorship); and "SA", "Share-Alike" (that is, share in the
6

same way). This means that it allows derivative works, both personal and commercial, as

long as they give credit to Arduino and publish their designs under the same license.

Free hardware allows you to study the hardware, reuse it, modify it, improve it and share

it. Its objective is to facilitate and bring users the electronics, robotics and current

technology in general, involving them to understand it, get more out of it, and participate in

the creation of future technologies. Free hardware allows us to know what is inside things

in an ethically correct way. Therefore, together with free software, it is a generator of

knowledge and, from that point of view, it is important for electronics, information

technology and life in general. In addition, in the same way that free software is based on

open source, free hardware (the one that comes with its technical specifications, so that the

user can create a replica of said hardware itself) is inevitably based on the open design

hardware (the one that it comes with the complete specifications so that the user can

interact with it without any unpleasant surprises and without needing to know what goes on

inside). To talk about free hardware, it is necessary to have access to the schematic files of

the hardware design, with the necessary information (that is, it must provide what

individual components integrate it and what interconnections there are between each one)

so that any user (with the materials, tools and knowledge), you can rebuild it on your own.

Free hardware (unlike free software), has practically no licenses under which to establish

itself as such. For this, it is usually called free hardware design or open source harware10; or

you can apply some type of license similar to those that exist for the software.
7

The OSHW (Open Source HardWare) 11 project is a declaration of intent (not a license as

such) in the form of standards and features, which seeks to establish a collection of

principles that help identify a physical product as free hardware and respect the freedom of

creators to control their technology, so that knowledge can be shared and open exchange of

designs is encouraged, showing an alternative to hardware patents,

to get hardware that is developed under free hardware licenses.

The Arduino card or board is free hardware. The Arduino platform provides the

necessary documentation, as well as the files and design schemes, available under the

Creative Commons (CC) BY-SA, 2.5 Generic12 license. Thus, although the usual thing is to

acquire the Arduino card from a distributor, already assembled and ready to use, a user has

the possibility of making his own, which (being something physical) costs money, so, even

if it is free, it's not free. The Arduino UNO 13 schema shown below and whose latest

revision is Rev3, is available, along with the reference designs, on the Arduino website.
8

One of the movements benefited by open source is the DIY (Do It Yourself), based on

the idea of creating own things, both domestic and industrial level. There are several

approaches to this movement, depending on the scope of application; Educationally and as

a hobby, Arduino is a reference platform and the basis for the development of new systems.

In addition, around an open source project, a community of people can be formed who

selflessly maintain, improve, correct, document or translate the project. These communities

may be more or less organized and often use various tools on the Internet to communicate

and share information. Arduino, of course, also has his.

The Arduino community


9

From the point of view of common development, Arduino is not simply a programmable

card, but part of a project or community, which includes, in addition to hardware, software

for programming and communication with the board; as well as tutorials and

documentation that explain how to learn how to use it, your own wiki14 (called playground)

and various forums15 to communicate and share ideas or knowledge with more Arduino

users.

As previously mentioned, on the Arduino official website you can access the software

and hardware documentation and public repositories (or warehouses), which host the

different parts of Arduino, and from which you can download your source code. The

community can be very useful, as additional support, in topics related to Arduino.

Nowadays, in addition, you can remain in continuous contact with the Arduino community

through Twitter16, Google + 17, Facebook18 and YouTube19.

Objectives of the Project


10

Distance measurement with Arduino

The purpose of this project is to know and work with the Arduino technology and the

HC-SR04 ultrasound sensor to develop a practical application, such as distance

measurement. In addition, the measurements of the distance that are being taken by the

Arduino board and the sensor, have to be visualized, in a simple way, through a computer.

The process of developing the application and the application itself, will be explained

later in this document (specifically in the sections "Program design" and "Program

implementation").

Analysis of benefits

With this project, it is also intended to graphically show the accuracy of the

measurement of distances for future application in high performance developments. For this

reason, various tests have been carried out to visualize this precision and the degree of error

that this measurement system can have. This will give us a more concrete idea of the

specific areas in which this measurement system can be used, and what are its limitations.

The analysis of the features of "Arduino + Ultrasounds", as well as the tests and results

obtained, are detailed later (in the section "Evaluation and Results").

Technical means necessary


11

With a budget of less than S./ 50.00 and a computer (with a Windows operating system,

Mac OS X or Linux) in which you have to install the Arduino IDE, it is possible to perform

the measurement application of Ultrasonic distances objective of this work. In the

realization of the tests, to have as reference a measure of exact distance to a point, instead

of a conventional tape measure, a laser distance meter provided by the GIAA of the

University has been used.

UNO Arduino

The latest version of this card is the R3. For non-expert use it is recommended to use

Arduino UNO R3 with microcontroller in DIP (or PU) format, compared to the SMD, in

case the microcontroller is damaged when working with the board (since it would simply

suffice to replace it to continue using the board). Arduino UNO R3 can be purchased

through the Arduino website, in its official store20, or through the official Arduino21

distributors. Its price is around S/. 25.00.

Ultrasonic sensor HC-SR04


12

The HC-SR04 sensor is compatible with Arduino. It can also be purchased through one

of its official distributors. It costs about S/. 5.00.

Prototype plate (Protoboard) and cables

Both the prototyping plate and the electrical cables for connections can be found, in

addition to the official Arduino store or one of its official distributors, at any electronics

store for around S/. 12.00.

Computer

You need a computer in which you have to download the Arduino IDE, to start writing

the programs. Any PC with a Windows operating system, Mac OS X or Linux can be used.
13

In this project, we used a Samsung R510 laptop PC with Windows 7 Professional

(Copyright © 2009 Microsoft Corporation) 32 bits, RAM 4 [GB] and Intel (R) Core (TM) 2

Duo CPU P8600 @ 2 '40 [GHz] 2'40 [GHZ].

USB Cable

Finally, a USB cable is needed which, in addition to exchanging information between

the computer and the board, will also serve to power it electrically. It serves any cable with

standard USB (Universal Serial Bus) connector, type A / B, for the connection of

peripherals to the PC. It costs about S/ 3.00.

Planning

The following table shows the planning established for the realization of this project,

reflecting the number of estimated hours of work required, and during each days

(understood as days from Monday to Saturday, during school hours).


14

Day 1

Day 2

Day 3

Day 4

Day 5

Day 6
Approach of the idea (distance

measurement) and choice of the

4 hours
appropriate technology (Arduino and a

sensor) to carry it out.


Research on Arduino in general and in

particular on the Arduino UNO board and

4 hours
its compatibility interaction with the HC-

SR04 ultrasonic sensor.


Budget proposal definitive and

4 hours
subsequent acquisition of the necessary

technical means to carry out the project.


Development of the application of

measurement of distances through 4 hours

ultrasound (ie, program implementation,

sketch, using the Arduino IDE).


Realization of the TFG memory.

Structure and design of the document.


4 hours

Drafting. Adding images, tables and

graphics. Correction of possible misprint.


Experimentation in the measurement of
4 hours

Ultrasonic distances developed.

Realization of the system tests.


15

Budget

Next, the budget necessary for the realization of the project is proposed, based on the

necessary resources, both human and material, to carry it out, and according to the planned

planning.

In general, the estimated budget in relation to the necessary material resources, can be

summarized as follows:

Cost (/S.)
Arduino UNO 25.00
Hardware

Ultrasonic Sensor 5.00


Protoboard and Cables 12.00
PC 3.00
Software IDE Arduino 1.8 free
Total Cost 45.00

On the other hand, the budget related to human resources has been subdivided into the

main phases that make up the work:

- Study of the feasibility of the system to be developed: effort estimation and analysis of

the knowledge necessary to carry out the project. It has to do with the approach of the idea

and choice of the appropriate technology (Arduino and a sensor) to carry it out.
16

- System design: general lines of the project, consolidation of previous knowledge, and

research and exhaustive study to expand them, according to the requirements of the system.

It has to be carried out through research on the Arduino platform in general, and

specifically on the Arduino UNO programmable card, and the HC-SR04 ultrasonic sensor.

- Implementation of the system: definition of the system, concrete technical means

necessary for the measurement application, and program development.

- Experimentation and evaluation of the system: choice and execution of the precise

tests, and results obtained graphically.

- System documentation: realization of the memory.

But we are students, so the cost is zero.

Regulatory Framework

Although, as far as this project is concerned (in terms of legal aspects), it is not directly

affected by the laws in force at the state level regarding telecommunications, data

protection and environmental protection, although, indirectly, it is worth mentioning the

current regulatory framework applicable to any computer engineering project.


17

General Telecommunications Law

General of Telecommunications22, pursues as one of its main objectives, to recover the

market unit in the telecommunications sector, founding procedures for coordination and

resolution of conflicts between state sectoral legislation and the legislation of the competent

administrations issued in the exercise of its powers that may affect the deployment of

networks and the provision of services.

Organic Law on Data Protection

The Organic Law on the Protection of Personal Data23, is intended to guarantee and

protect, with regard to the processing of personal data, public liberties and fundamental

rights of natural persons, and especially their honor and personal and family privacy.

Law of Environmental Responsibility

Law on Environmental Responsibility24, regulates the responsibility of the operators to

prevent, avoid and repair environmental damage, in accordance with Article 45 of the

Constitution and with the principles of prevention and that "the polluter pays".

Structure of the document


18

So far, as an introduction to the work, they have tried to explain the basic foundations

and objectives of this project. In addition to the material means necessary to carry it out, the

work planning, the associated budget and the current regulatory framework.

The footnotes found in some of the terms used in the writing of this document can help

clarify them, since many of them refer to the website from which they were extracted and,

in others, It explains where you can find more information about it. Any link to web pages

is shown underlined. The Anglo-Saxon terms appear in italics. And the references to the

functions of the programming language are shown with different type of letter and color, in

order to differentiate them from the normal text.

Below is a brief description of the successive sections that make up this project.

In the section called "Arduino", it will begin by giving an overview of the Arduino

platform explaining its main hardware and software features. As the section progresses, we

will delve more deeply into the explanation of the Arduino board model that has been used,

the Arduino UNO. Most of the information about the Arduino platform in general, and

about the Arduino UNO board in particular, has been extracted from the official Arduino

website.

Then, in the section called "Ultrasonic Sensor" both the concept of sensor and the

concept of ultrasound will be explained. And we will go into detail in the explanation of the
19

characteristics and the internal operation of the ultrasonic sensor used in this project, the

HC-SR04 sensor, which is compatible with Arduino.

Later, in the section "Program Design", the system to be implemented will be defined,

taking into account the scope and restrictions of the same. It will also show the circuit

diagram that form the Arduino UNO R3 board next to the HC-SR04 sensor. And finally, the

operational environment in which it can be applied will be described.

Then, in the section "Implementation of the Program", the entire process that has been

followed to carry out the application of distance measurement will be explained. From the

installation of the IDE, to the elaboration of the program and the communication details

between the Arduino UNO board R3, the computer with the Arduino IDE installed, and the

HC-SR04 ultrasonic sensor.

Then, in the sections "Evaluation and results" and "Conclusions" will show the tests

performed and the results obtained, which will give an approximate idea as to the degree of

error that may be in the measurement of some distances or other, allowing reflection on the

functionality of the developed application, its limitations and its potential application in

high performance developments. In addition, it will give an idea of possible future works,

from this.

Finally, in the section "Bibliography" you can find bibliographic references to the main

manuals, books and websites that have been consulted throughout this work.
20

ARDUINO

Arduino is a free platform of integrated circuit and computer system, for the creation of

electronic prototypes. It consists of a hardware part (the plate itself) and a software part (in

form of integrated programming environment or IDE, Integration Development

Environment), both flexible and simple to use. It emerged from the idea of an Italian

engineer (Guianluca Martino, in 2005) for teaching purposes and, perhaps due to its

affordable price and its open-source nature (which allows its design and free distribution),

its use has been extended in recent years. years to multiple projects, many of them related

to industrial design and interactive art. The official information of Arduino can be found

online, on its official website.

There are different models of official Arduino boards on the market. All of them, include

as a main element microcontrollers of the AVR technological family (of the Atmel brand),

so its internal functioning is similar. The pins of the microcontroller are internally

connected to the pins of the board. So, through the board and the Arduino IDE, through

sensors (like the ultrasound used in this project) you can extract information from the

physical world, that is, the environment that surrounds us (for this, the inputs or "input

pins" of the board, receive electrical impulses that become current electric); in addition,

through actuators or activators (such as LEDs, speakers, displays, motors or screens) can

provide information (Therefore, the outputs or "output pins" of Arduino offer electrical

values). Some models of Arduino boards have integrated sensors and actuators but, in
21

general (and this is also the case with the Arduino UNO board), we work with external

sensors and actuators, and with a prototype board that simulates the future printed circuit,

and in which the connections can be easily mounted and dismounted by cables. In addition,

to the different models of Arduino boards, you can add shields (complementary boards that

maintain the same arrangement as the pins of Arduino boards, to stack them comfortably on

them, simplifying more complicated connections). There are shields of Ethernet, GPS or

TFT screens, among others.

The plates, can be built by hand or purchased already pre-assembled and the official IDE

to work with Arduino, can be downloaded for free. In addition, developments with Arduino

may require an operating system to run, or not (stand-alone), or even interact with a

program that is running on a computer (Flash, for example).

Hardware

Hardware is the set of components that make up the material part of Arduino, that is, the

Arduino board itself. It is a programmable card, in the form of a printed circuit (PCB,

Printed Circuit Board), whose surface is made of a non-conductive material (fiberglass

reinforced resins, ceramic or plastic) and traced with tracks of a conductive material

(copper, usually) that electrically connect the different components welded to the plate,

forming a certain design of internal circuitry, whose main element is the microcontroller (of

Atmel) of 8 bits of resolution (with the exception of the microcontroller of the Arduino

DUE board, which is 32 bits). It consists of three types of memory, variable capacity
22

depending on the type of microcontroller (depending on the model of the board): Flash

memory, with a capacity between 16 and 256 [KB], SRAM (Static Random Access

Memory) memory of 1, 2 or 8 [KB], and EEPROM memory (Electrically Erasable

Programmable Read-Only Memory) of 512 bytes, 1024 bytes (or 1 [KB]) or 4 [KB]. The

microcontroller has a series of connectors or pins that are used as input or output, memory

registers, an internal oscillator (which provides the microcontroller with a series of pulses

to keep the working speed stable), and interfaces for serial communication; among its main

components.

On the other hand, the Arduino board also consists of a series of inputs and outputs (in

the form of connectors or pins), both analog and digital. The digital input or output pins can

be

behave, as its own name indicates, as digital inputs or outputs, as specified in the sketch

programmed in the IDE; the analog inputs accept analog values (ie, voltage readings from a

sensor) and convert them to a value between 0 and 1023; and the analog outputs are

reprogrammed digital outputs to offer analog output values through the sketch created in

the IDE.

The plate, to operate, needs power. The power supply to the board can come either from

an external power source (the general electrical network or a battery) or from the computer

to which the board is connected via a USB cable. If there is not a source of

external power, the power will come from the USB, but as soon as you plug in a power

supply, the board will use it automatically.


23

The original design of Arduino includes the electronic components necessary to feed and

communicate with the microcontroller so, other design alternatives should incorporate them

or at least, show the way to add them easily. The reference designs of Arduino, as already

mentioned above, are under the license of CC BY-SA (2.5 Generic) 25.

See link 26, as a summary of the main componentshardware of each of the different

Arduino board models:

Software

As for the software part, to program the Arduino hardware (indicating what to do and

under what conditions, and so, provide outputs or react to inputs), you need a development

environment or IDE (Integration Development Environment) in of a set of software tools to

develop and test programs, called sketches in Arduino. The official Arduino IDE is based

on the open source programming language Processing27, specially designed for people

without programming experience; and on the Wiring28 platform, for the simple development

of application prototypes. This official IDE can be downloaded from the Arduino website

for free29. There are other unofficial alternative IDEs that also could be used to work with

Arduino (such as: CodeBlocks, Gnoduino, Codebender, Visualmicro, EmbedXcode,

Scratch for Arduino -S4A-, ModkitMicro, Minibloq, or Ardblock, among others). Although

it will not be the case of this project, in which the official IDE has been used, since it is the

most standardized for Arduino.


24

The programming language of Arduino30 is known as Arduino Programming Language.

It is based on the C language, so it supports any standard C construction (and some of the C

++ functionalities). Link with the Libc AVR library, allowing the use of any of its functions.

Broadly speaking, the programming language of Arduino, can be divided into three large

groups: structures or blocks (such as setup (), loop (), operators, etc.), values (variables and

constants) and functions. There are also a large number of libraries31 for the interaction of

Arduino with certain types of hardware. And numerous code contributions by the

community.

In this way, the board can be programmed to interact with the real world. But the outputs

that the Arduino board offers and the inputs to which it can react, are of an electrical nature.

Therefore, when sending or receiving signals (ultrasound, in the case of this project)

through external sensors (the HC-SR04 sensor, in this case), the value read by the sensor

must be transformed into a value electrical, process it using Arduino and transform it again,

into something usable (which in the case of this project, will be a distance in centimeters,

which will appear on the IDE serial monitor installed on the computer with which you are

working).

In this way, the board can be programmed to interact with the real world. But the outputs

that the Arduino board offers and the inputs to which it can react, are of an electrical nature.

Therefore, when sending or receiving signals (ultrasound, in the case of this project)

through external sensors (the HC-SR04 sensor, in this case), the value read by the sensor
25

must be transformed into a value electrical, process it using Arduino and transform it again,

into something usable (which in the case of this project, will be a distance in centimeters,

which will appear on the IDE serial monitor installed on the computer with which you are

working).

In any process of compilation (or of translation of a program to an executable machine

language) two stages follow: a first one (of analysis), to divide a source program in the

elements that compose it and to create an intermediate program; and a second stage (of

synthesis), to build the object program that will be transformed, through a linker, into the

executable program.

In the Arduino kernel, the toolchain is the sequence of programs34 that are invoked each

time a project is compiled, generating the machine code file with extension * .hex that will

be sent to the Arduino board (to your micro) through USB or serial connection (or an ISP

programmer, if you do not have the bootloader installed). During the Arduino compilation

process, both the sketch (or the sketches) of the project with extension * .ino are compiled,

as well as the libraries included, and the files that Arduino uses. The "* .ino" files are

merged (in a "main sketch file") before being sent to the avr-gcc compiler, while the "* .c"

and "* .ccp" files are compiled separately.

First, the Processing preprocessor is executed, which transforms the source code of the

Arduino language into C ++ language. The setup () and loop () structures of the program in

Arduino, become functions of a C ++ program and are saved in a file "* .ccp" in the
26

temporary directory35 of the project, whose path can be made visible in the console of the

IDE activating the output Detailed.

Then, the compiler "avr-gcc" is executed. All the necessary routes are included in the

path (the sketch directory, the destination directory36, the "include avr" directory37 and the

library directories). The compiler analyzes the text of the file "* .ccp" (to which the rest of

files with the extension * .ccp, * .c or * .s) are added and the rest of the files included in the

path. Compile the sketch, the bookstores and core. Each file "* .ccp" or "* .c" is compiled

(with "avr-g ++") as a file object different and several "* .o" files are generated in the

project's temporary directory.

Later, the linker program38 joins all the object files and places them in the positions that

will occupy in the memory. By "avr-ar", it joins the files "* .o" and compresses them into a

file "* .a"; and through "avr-g ++", generates a static library file, "* .elf" (a standard of

executable files in UNIX) with all object code generated before. The file "* .elf" is convert

(through "avr-objcopy") to a file "* .hex" (or Intel Hex Format39) that contains the

Machine code that will be loaded and executed in the microcontroller. Finally, the file is

sent end (with * .hex extension) to the Arduino board.

The bootloader, which is the first to run when the Arduino board is started, waits a while

for the "* .hex" file to arrive. If it does not reach you, it passes to the execution of the main

program; and if it arrives, start recording the program in Flash memory. When loading

(after verifying) a sketch in the IDE, the "avrdude" program communicates through a small
27

protocol with the bootloader through the USB port. On the Arduino board, the USB to

serial translation is performed and the "avrdude" program sends the file "* hex." To the

bootloader, which has permission to write to the microcontroller's Flash memory

(program), sends it the data that the "avrdude" has passed; And when it ends, Restart the

CPU.

Prototype plate

The prototype plate, also known as protoboard, breadboard or plugboard is a plastic

plate with holes, each of which has a spring contact and a distance of 2'54 [mm] from each

other. It is used as a seamless test plate in which components and cable ends can be inserted

to simulate a printed circuit.

The inner holes of the breadboard are usually divided into two blocks (a block would be

formed by the vertical lines A, B, C, D, E; and the other by the vertical lines F, G, H, I, J)

and are connected to each other in vertical line, so that, if a voltage is applied to a hole in a

block, inserting one of the contacts of the component in one of the holes in the breadboard,
28

all the holes of the same vertical line (of that block) will have the same tension. The blocks

are electrically separated from one another so that, when a chip is connected, there is no

short circuit.

The upper and lower rows of the horizontal edges of the breadboard (which are usually

red and blue, and are usually marked with the + and - signs, depending on their polarity) are

the power buses. They are connected horizontally to carry power through the prototype

board so that, when power (power supply) or ground is needed, it can be provided quickly

with a cable that connects two points of the circuit.

Arduino UNO

Arduino UNO is one of the most widespread Arduino boards commercially and,

therefore, the one chosen for this project. Of all the varieties of Arduino40 plates that exist

in the market (UNO, Due, Leonardo, Mega, Micro, Mini, Nano, Ethernet, Esplora, Fio, Pro,

Pro Mini, Lilipad, Yún, Tre and Robot) the most standardized and used model is Arduino

UNO. The one used here, in particular, is the Arduino UNO R3 programmable card. "R3"

means that it is the third revision of the plate, the last one in the UNO range.

There have been multiple revisions of the Arduino board in the Arduino USB range,

fromthat the first board named Arduino (USB Arduino) appeared which has been evolving

(since V2.0 USB Arduino, Arduino Extreme, Arduino Extreme V2, Arduino NG, Arduino
29

NG RevC, Arduino Decimila and Arduino Duemilanove) until reaching the last one,

Arduino UNO, the latest model of boards with USB and, according to its official website,

the reference model, together with the future Arduino 1.0 for the Arduino platform. Arduino

UNO differs from other plates in the USB range. Previously, it does not use the FTDI

controller from USB to serial, but it has the Atmega16U2 chip (Atmega8U2, up to the

Arduino UNO R2 version) programmed as a USB to serial translator. Since its appearance

in 2010, Arduino UNO has undergone 3 revisions. The plate that has been used for this

project will be the last, Arduino UNO R3. Because it is the last revision, the Arduino UNO

R3 board has some advantages, in addition to new visual tags to identify the inputs and

outputs easily, compared to previous versions (SDA and SCL output pins near the AEREF

pin, two new pins near the RESET pin, an IOREF instruction that allows the shields adapt

to the voltage supplied by the board, a consistent reset circuit, and the Atmega16U2 chip in

time of the Atmega8U2).

Hardware

Arduino UNO consists of an Atmega328P microcontroller. The programmable card

contains everything necessary to support the microcontroller, simply connect it to the

computer with a USB cable and connector to start programming and use it. You can expand

its functionality with a variety of shields for specific functions.

The length and width of the Arduino UNO board are about 2'7 and 2'1 inches

respectively, except for the area of the USB and power connector, which protrudes a few
30

millimeters. The distance between the digital pins is 0.1 inches (except between pins 7 and

8, which is 0'16 ['']). It has 4 holes to be able to screw the plate to any surface. Its operating

voltage is 5 [V], with a recommended input voltage between 7 and 12 [V] (the theoretical

limits are 6 and 20 [V]) and a maximum DC current of the I / O pins of 40 [mA] (50 [mA]

for pin 3.3V).

The board has, in addition to the ATmega328P microcontroller with its corresponding

memory (Flash of 32K, SRAM of 2K, and EEPROM of 1K) and head ISCP, with a

prepared zone for connection of feeding, another area for the USB connection, and a series

Connector (pins) input output: 14 digital I / O pins (6 of which can be used as analog PWM

outputs) and 6 analog input pins. It also includes a ceramic resonator with a frequency of 16

[MHz], a reset button (and several ways to restart the board), interfaces for communication

with UART, I2C (or TWI) and SPI 14 and another microcontroller (the ATmega16U2), with

another ISCP. Among others.

Below is an image of the plate, with the main parts differentiated. In the next lines, they

are described in more detail.


31
32

ULTRASONIC SENSOR

Sensors

A sensor (from the Latin sentĭo, to feel) is an electronic device designed to receive

information. It detects a certain external action and transmits it appropriately. For this

purpose, it is responsible for transforming the physical or chemical quantities

(instrumentation variables such as temperature, pressure, distance, displacement,

acceleration, inclination, etc.), in magnitudes, normally electrical, that we are able to

quantify and manipulate

More and more frequently, we can find sensors applied to any technological area and in

many of the elements that surround us (traffic lights, mobile phones, industry, surveillance,

etc.). Devices that incorporate sensors react to the information they receive from them. In

this way, the sensors allow interacting with the environment, providing information about

certain variables that surround us, to process them, generate orders or activate processes.

It is usual for the output signal of a sensor not to be suitable for processing by the

actuator circuits, and it must be adapted and amplified. In addition, as it usually happens, if

it depends on conditions such as temperature or supply voltage, it is also necessary to

linearize the sensor and compensate for its variations by means of signal conditioners.
33

Microcontrollers are a type of economic, versatile signal conditioners, and able to

process virtually any type of signal. They consist of some inputs and outputs (I / O) digital

devices that can receive signals and deliver signals to other resistor, transistor and

operational bridge type conditioners. They can also implement signal converters

Programmable ADCs, capture inputs and pulse counts, and I2C serial communication lines.

The most commercially extended, are those of the manufacturer Microchip and those of

Atmel.

When choosing a sensor, to use it in a specific application, aspects that allow achieving

the best performance for that application must be taken into account, such as the speed of

response, the situation in which they will use, the radius of action that they have to have,

the reliability that is expected for their correct operation, the feeding tensions, the

consumption of current, the temperature margins of its operation, the possible interferences

produced by external agents, its resistance to said external agents or the price-quality ratio.

In addition, it is necessary to know some properties of the sensor, which give information

as to the effectiveness that can have, mainly the resolution, the sensitivity, the degree of

error, of precision or repetitiveness, among others.

As a rule, depending on the application to be given to the sensor, a sensor of one type or

another is normally chosen. To name the most common in this regard, it can be said that in

lighting, for example, photoresistive sensors or photoelectric sensors are usually used;

however, to work with temperature, thermistors are used. In humidity measurement,

resistive sensors or capacitive sensors can be applied. To measure positions or inclination, it


34

is usual to use mechanical sensors, resistive sensors, accelerometers or magnetic sensors.

Related to pressure, are piezoelectric sensors or resistive sensors. To measure flow, there

are piezoelectric or magnetoresistive sensors. In presence detection, a good Choice are

magnetic sensors, infrared sensors or ultrasonic sensors. And for distance measurement

(objective of this project) you can choose to use infrared sensors (Infrared Radiation, IR) or

ultrasound sensors (ultrasonic rangers).

Among the infrared sensors for distance measurement compatible with Arduino, there

are the analog IRs of the Sharp GP2 range. The GP2 IR sensors, are formed by an emitter

and an infrared receiver. When the infrared beam sent by an emitter hits an obstacle, it

bounces off the obstacle and strikes the receiver with a certain starting angle. from which

the distance to said obstacle can be calculated, according to the voltage returned by the

sensor (through its analog connector), which is shown in a graph of the specifications sheet

of the sensor manufacturer, whose value will need to be calibrated, in each particular case.

Other infrared sensors such as QRD (1113/1114), similar to GP2 in terms of operating

mode, they have been designed, more than for distance measurement, to detect presence

over short distances, since their detection range goes only from 0 to 3 [cm]. On the other

hand, for measuring distances through Arduino, the sensors par excellence (in terms of

performance, efficiency and simplicity when programming them with the Arduino IDE) are

the ultrasounds. They are explained in more detail below.


35

Ultrasonic sensors

Ultrasounds are acoustic signals (mechanical vibrations in the form of elastic waves

longitudinal) that propagate in an elastic medium (such as air) with frequencies that exceed

the range of frequencies perceptible by the human ear, approximately from 20 [kHz] (up to

more than 1 [GHz]). Due to their nature, they can suffer phenomena of reflection, refraction

and diffusion. They are usually used in distance measurement or presence detection. And

they require a emitting device, a receiving device and a measuring device.

When ultrasound is emitted, which propagates at the constant speed of sound (340 [m /

s] to 25 [° C] of temperature, or 343 [m / s] to 20 [° C]), and collides perpendicularly with

an obstacle, they bounce, at the same speed, but in the opposite direction (usually with an

angle, so you have to enter a correction factor). The ultrasonic sensors use this property and

calculate the time it takes for the ultrasonic waves since they are emitted by the sensor itself

until its rebound is received.

To generate ultrasound, ultrasonic sensors use variable electric fields to, based on a

piezoelectric deformation effect that certain crystals experience when they enter an electric

field, oscillate a crystal (usually quartz, and at a frequency of 40 [KHz]). Generally they are

formed by two transducers in the form of cylindrical capsules (one emitter of ultrasounds

and, another one, receiver of the rebound or echo of said ultrasounds) and connectors or

pin (male type) digital input or output.


36

The ultrasonic sensors have been designed to calculate the time elapsed between the

emission and subsequent reception of the ultrasound that it sends. Thus, once said time has

been obtained and knowing the speed of propagation of the ultrasound in the air, the

distance between the sensor and the object that is in front of it can be calculated (estimated)

and that has caused the rebound of the ultrasound that it sent.

The operation of an ultrasonic sensor is summarized below. First, the emitter (emitter

capsule) of the sensor generates and sends an ultrasonic acoustic signal, normally 40 [kHz].

The emission must be short (between 10 and 600 [μs]), to avoid large signal trains that can

interfere with each other and distort the echoes produced in the rebounds of the ultrasonic

signal. Then, a safety waiting time (of approximately 2 [ms], depending on the number of

cylindrical capsules of the sensor), will avoid false readings over short distances. Once the

emission and safety times have passed, a circuit associated with the receiver (receiving

capsule), which internally detects if a signal is received at any time ultrasonic acoustics.

Depending on the maximum measuring distance for which the ultrasound sensor is

designed (its transducer capsules), a specific time must be allowed, after which, in the event

that the receiver does not receive the echo of the ultrasonic signal sent by the receiver.

transmitter, the sender will interpret that there was not an obstacle in the way and will

proceed again to emit another ultrasonic signal. This waiting time may also depend on other
37

factors such as temperature; for a temperature of 25 [° C], it is usually around 23 [ms], for a

range of 4 [m] (8 [m] of round trip). Through the programming of a microcontroller and

knowing the distance formula (d = ½ * v * t) and interpreting the voltage signals provided

by the sensor, the distance to an object or obstacle can be calculated, once received the

ultrasound echo that the sender sent.

Sensor HC-SR04

The HC-SR04 sensor is blue and silver (like the Arduino card). Its dimensions are 4'3 x

2 x 1'5 [cm] approximately. And its mass of about 10 [g]. It looks like this:

It consists essentially of transmitters and ultrasonic receivers and internal control

circuitry. The main features of the HC-SR04 sensor can be summarized as follows:

- Operating voltage (or voltage): 5 [V] DC (minimum 4'5 and maximum 5'5).

- Working current (or operating consumption): around 15 [mA] (minimum 1 [mA] and

maximum 20 [mA]).
38

- Static current (or idle consumption): normally <2 [mA] (minimum 1'5 [mA], and

maximum 2'5 [mA]).

- Frequency of the ultrasonic waves that it emits: 40 [kHz]. -� Measurement angle: 30 °,

effective less than 15 °.

- Distance detection: from 2 [cm] to 4'5 [m].

Detection can be detected more than four meters away, but

A good measurement is guaranteed.

- Accuracy: can vary between 2 or 3 [mm].

- Output signal (trig): initial pulse of 10 [μs] at TTL level.

- Input signal (echo): pulse at TTL level of a duration equal to the round trip time of the

ultrasound from the sensor, to the obstacle to which the distance is to be measured.
39

The connection pins of the HC-SR04 through which it must be connected to the Arduino

board (through or not the protoboard, which does not have to be necessary) are: the VCC

pin (+5 [V] DC ) will be attached to the 5V output of the Arduino card that will supply the

sensor with power to operate it; the Trig pin, to send the trigger signal, will be connected to

the digital pin of the Arduino board responsible for the emission or triggering of the

ultrasound; the Echo pin, for the echo signal (of reception), will be attached to the digital

input pin of the Arduino board destined for the reception of the ultrasound; and the GND

pin, to the grounding of the Arduino card.

The HC-SR04 sensor works like a sonar would. It allows estimating the distance to a

point, through the time measurement system that incorporates, through which, calculates

the time difference that occurs between transmitting and receiving the digital pulses that it

sends and captures through the cylindrical transducers that It is coupled to its surface. In the

schedules of the specification sheets, graphically and explain how these pulses have to be.
40

PROGRAM DESIGN

Definition of the System

In the development of the target distance measurement application of this project, an

Arduino board of the UNO range (the most extended) has been used, to which the HC-

SR04 ultrasonic sensor (the most commonly used in the measurement of distances,

currently). For there to be communication between two devices, the input of one (the

Arduino UNO board) has to go connected to the output of the other (the HC-SR04), and

vice versa. Also, in an asynchronous communication, they will have to communicate at the

same speed.

Arduino UNO, when connected by a cable with USB connector to a computer

(Windows, Mac OS X, or Linux) with the Arduino IDE, behaves before the computer, as a

port

series through which the plate and the computer can transmit information to each other.

The information transmission system in this case is a serial communication UART

(Universal Asyncronus Receiver / Transmiter) through which serial communication is

performed asynchronously, that is, without a clock signal that indicates determine the speed

of transmission of information (how often the readings or writings are made) and

synchronize the transmission of information between the Arduino UNO board and the

computer. The board and the Arduino IDE installed in the computer, will have to coincide
41

in the speed at which the transmission of information is carried out, determined by the

bauds or [bps] (signal units). In essence, the greater the number of bauds chosen, the less

time is spent in the transmission of information and, therefore, more information can be

transmitted with respect to time. In terms of bits, if each baud equals 1 bit, the bauds will

indicate the bits that are transmitted per second. In this way, you can calculate how long the

1-bit transmission takes. Thus, if a communication is configured with a baud rate of 9600

baud (the one established by default in the IDE serial monitor, and the most usual), 1 bit

will be transmitted approximately every 104'17 [μsec] (since 1 [ sec] / 9600 [baud] =

1'0417 * 10-4 [sec]).

In this project, Arduino will have two main tasks: measure the distance from the sensor

to an obstacle (thanks to the HC-SR04 ultrasonic sensor) and communicate this distance to

the computer (showing it on the serial monitor of the Arduino IDE). But since you do not

perform these tasks simultaneously, the longer you occupy one, the less time you have to

perform the other, that is, the more bits that are transmitted per second (the more baud in

the sketch and the monitor serial IDE) enters the board and the IDE, while the board and

the sensor are taking the measurements of the distance, less time will take to transmit this

information to the computer (and display it on the serial monitor). For this project, it has

been decided to use the maximum baud rate possible in Arduino, which is 115200 [bps], a

transmission speed that allows you to view each of the distance measurements taken in a

measured way, in the serial IDE monitor.


42

Scope

- Distance detection: from 2 [cm] to 4'5 [m]. More than 4 [m] can be detected, but a

good measurement is not guaranteed.

- Accuracy: may vary, between 2 or 3 [mm].

- Measurement angle: 30 ° (effective: <15 °)

Restrictions

- Operating voltage: minimum 4'5 [V], maximum 5'5 [V]. Normally 5 [V] -� Current:

static or idle: minimum 1'5 [mA], maximum 2'5 [mA] .Normally <2 [mA]. -� Working

current: minimum 1 [mA], maximum 20 [mA]. Normally 15 [mA]. -� Working frequency

(frequency of ultrasonic waves): 40 [kHz].

- Input and output signals (trigger and echo) at TTL level.

- The output or trigger signal has a signal (pulse) of high level (HIGH) of at least 10

[μs].

Circuit diagram

To graphically show the design of the circuit, Fritzing has been used, a support software

for circuit design with Arduino. It allows to graphically represent the connections in the

breadboard and thus, the assemblies are easily understandable. In addition, it offers
43

everything necessary to transform the project into a real PCB, for example, to create new

sields.

Provided that the connections are made correctly, there are infinite possibilities of circuit

design to implement the ultrasonic distance measurement with Arduino UNO and the HC-

SR04 sensor. The one shown here is the one that has been used in the design of the sketch

that has been developed for this project. The analog pin A3 of Arduino UNO, has been

configured as a digital pin, connected to the Trig pin of the HC-SR04. The analog pin A2 of

Arduino UNO, has been configured as a digital pin, connected to the Echo pin of the HC-

SR04. The 5V pin of Arduino UNO, has joined the pin Vcc of the HC-SR04. The GND pin

of Arduino UNO has been linked to the GND pin of the HC-SR04.
44

The Trig and Echo pins of the HC-SR04 sensor could have been connected to any

Arduino UNO digital pin. Also, in this circuit, it would not have to be necessary to use the

breadboard (has used, because it allows to connect the four pins of the HC-SR04 sensor to

it and in this way it is always kept in the same position on it, which is to make the

subsequent distance measurement tests more feasible). The scheme that has been shown in

the image previous, without using the breadboard, could be simplified in the following way.
45

IMPLEMENTATION OF THE PROGRAM

Development environment

Installing the Arduino IDE

The Arduino must be programmed to react when it receives an electrical impulse from

any of its inputs, and offers something through its outputs. For this, as already mentioned

above, there is an Arduino provides an official IDE that facilitates the development of the

code and It is available for Linux, Windows, Mac OS X. It can be downloaded for free. The

last stable version is Arduino 1.0.5 (r2, adapted for Windows 8) so we have opted for it to

perform this work.

For the development of this project, a PC with the Windows operating system has been

used (Windows 7 Professional version) currently the most widespread. In this case, when

downloading the Arduino executable file ("Windows ZIP file") and unzipping it, the

following directories are obtained: drivers (drivers, specific to the type of operating system,

which allow communication of the Arduino card with the Arduino IDE) , examples (code

examples, sketches, which can be consult and test), hardware (tools and information about

the Arduino hardware, which will use the IDE itself), java (Java execution environment,

JRE, to use the IDE), lib (Java libraries and configuration graphics of the appearance of the

IDE), libraries (Arduino libraries to simplify the programming of certain components),


46

reference (documentation on the references of the Arduino programming language) and

tools (tools for Arduino IDE). All of them are found next to the Arduino application itself

(with its extensions) and a text document, revisions (with IDE Arduino revisions).

The next thing that has been done, following the corresponding instructions, is to

connect the Arduino to the PC. Immediately, on the Arduino UNO board, the On LED will

be activated (which will remain lit in green) and the L LED (flashing orange); on the PC an

alert message will appear indicating that the installation process has not been carried out

successfully.

On the PC, go to Control Panel> Security and System> System> Device Manager. A

series of PC driver devices and a device still unknown to the PC (the Arduino UNO board)

will appear. We click with the right mouse button on that unknown device and select

"Update driver software ..." Then we select in the option "Search driver software on the

computer" and "Browse". Let's go directory where we had downloaded the IDE file that we

unzipped. Select the Drivers directory (including subfolders), go to the next step and accept

the installation. You can check that on the PC, in "Device Manager", Arduino Uno (COM4)

appears, that is to say that the appropriate drivers have been installed that will allow the

USB port connected to the PC and the Arduino board to appear as a serial port or "COM"

inside the PC, so that communication with the Arduino board, now connected to that port of

the PC, can be carried out. Now it can Start using Arduino.
47

Execution of the Arduino IDE

To execute the development environment, simply go to the directory where Unzipped

the Arduino IDE and selected the Arduino application file (Arduino.exe). It will open a

window with an aspect similar to the one shown in the following image, where we can start

write the program code executable by Arduino or sketch.

To start programming the board through the Arduino IDE, you should check in the IDE

window, in the Tools menu> Card, the selected board is Arduino UNO, and in Tools menu>
48

Serial port, select the same COM port as the one that was enabled in the installation of the

drivers for serial communication between the board and the computer (COM4).

Appearance of the Arduino IDE

The main window of the IDE is divided into five sections that, from top to bottom are: a

menu bar, a section of buttons, a text editor, a section and console messages and a status

bar. They are explained in more detail below.

At the top of the IDE appears the menu bar that, to complement the functions that can be

done with the button section, is divided into five main entries:

- File. It offers different actions, some standard (New, Open, Save, Load in the memory

of the micro, Print and Close) and other specific.

- Edit. It allows to perform typical actions of any text editor (such as copy, paste, select,

comment, search or search and replace)

General structure of an Arduino sketch

Sketch is called any program designed or developed to run on an Arduino board. It is

mainly divided into three sections (common to any sketch). The upper part of the sketch is

reserved to import the libraries that will be used, define the constants of the program, and
49

declare the global variables. Next, it is essential to use the void setup () function; the code

written within this function, delimited by keys, will be executed only once, each time the

board is started. It will therefore include the initial settings of the Arduino card. Finally, it is

necessary to program the function void loop (); is function, also delimited by keys, will be

executed immediately after the void function setup () and in an orderly and continuous

manner, as if it were a loop, until you turn off the board. You must include the instructions

that you want to run permanently on the Arduino card and that will integrate the program

itself.
50

Program code

For the measurement of distances by means of an ultrasonic sensor, the signals have to

be processed, in order to be able to process them and thus obtain, as accurate as possible, a

measurement of distance to objects. In the following lines its operation is explained more

extensively.
51

Internal operation of the sensor

As already mentioned, the HC-SR04 sensor calculates the difference in time between

transmitting and receiving a series of pulses that it sends and captures. From this system of

time measurement, it allows us to calculate the distance to an object.

Code of the final sketch

#include<LiquidCrystal.h> // Incluye la librería para el LCD


LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Define los pines de Arduino que se van a usar
con el LCD
#define Pecho 6 // Define los pines de Arduino que se van a usar con el
Sensor HC-SR04
#define Ptrig 7
long duracion, distancia;

void setup() {
pinMode(Pecho, INPUT); // Define el pin 6 como entrada (echo)
pinMode(Ptrig, OUTPUT); // Define el pin 7 como salida (triger)
lcd.begin (16, 2); // Inicializa el LCD como 2 filas de 16 caracteres
lcd.setCursor(0,0);
lcd.print(" HELLO TEACHER");
lcd.setCursor(0,1);
lcd.print("GROUP 5 PROJECT.");
lcd.print(" ");
delay(7000);
lcd.setCursor(0,0);
lcd.print(" Let's go ");
lcd.setCursor(0,1);
lcd.print(" ");
delay(7000);

void loop() {
52

digitalWrite(Ptrig, LOW);
delayMicroseconds(2);
digitalWrite(Ptrig, HIGH); // genera el pulso de triger por 10ms
delayMicroseconds(10);
digitalWrite(Ptrig, LOW);

duracion = pulseIn(Pecho, HIGH); // Recibe señal de Triger


distancia = (duracion/2) / 29; // Calcula la distancia en centimetros

if (distancia >= 500 || distancia <= 0){ // Si la distancia es mayor a 500cm o menor a
0cm
lcd.setCursor(0,0); // Determina dónde escribir (segunda línea)
lcd.print(" ");
lcd.print("OUT RANGEF"); // No mide nada, envía mensaje de fuera de
rango, o no hay sensor
lcd.print(" ");
lcd.setCursor(0,1);
lcd.print("OR NOT SENSOR!!");
delay(1500);
lcd.setCursor(0,0);
lcd.print(" ");
lcd.print("APPROACH");
lcd.print(" ");
lcd.setCursor(0,1);
lcd.print("OR CONNECT SENSOR");
delay(2000);
lcd.setCursor(0,0);
lcd.print(" ");
lcd.print("THEN RESTART");
lcd.print(" ");
lcd.setCursor(0,1);
lcd.print(" ");
delay(1500);
}
else {
lcd.setCursor(0,0); // Determina dónde escribir (primera línea)
lcd.print("------"); // Decoración
lcd.print(distancia); // Envía el valor de la distancia por el LCD
lcd.print("cm"); // Pone "cm" al lado del valor
lcd.print("------"); // Decoración
lcd.setCursor(0,1);
lcd.print(" "); // Segunda línea vacía (Necesario, porque sino se quedaría
escrito algúno de los textos de más adelante)
delay(500);
}
53

if (distancia>20){
lcd.setCursor(0,1);
lcd.print("IS FAR");
delay(500);
}

if (distancia <= 20 && distancia >= 15){


lcd.setCursor(0,1);
lcd.print("IS NEAR"); // envia texto a LCD (segunda línea)
delay(500);
}
if (distancia <= 14 && distancia >= 10){
lcd.setCursor(0,1);
lcd.print("IS MORE NEAR"); // envia texto a LCD (segunda línea)
delay(500);
}
if (distancia <= 9 && distancia >= 5){
lcd.setCursor(0,1);
lcd.print("IS TOO NEAR"); // envia texto a LCD (segunda línea)
delay(500);
}
if (distancia <= 4 && distancia >= 1){
lcd.setCursor(0,1);
lcd.print("FORWARD SENSOR"); // envia texto a LCD (segunda línea)
delay(500);
}

}
54

EVALUATION AND RESULTS

Tests

To carry out the tests of the system (as shown in the next image), the assembly

comprising the Arduino UNO board, the HC-SR04 ultrasonic sensor and the prototype

board, together with a laser distance meter94, high precision, similar to that used for

measuring distances in the performance of activities related to technical architecture. In this

way, we can more accurately study the degree of error that is obtained when measuring

distances using Arduino UNO and HC-SR04, comparing the results with the distance

measured by said laser. The prototyping plate is not an indispensable element in this circuit,

but it is useful in that it allows the sensor to remain in a stable position while measurements

are taken, whose values are displayed in the Arduino IDE, when connecting a USB cable to

the Arduino UNO board and execute the corresponding sketch.

Next, the results obtained in the various tests that have been carried out are shown

graphically.

On the vertical axis (Y) of each of the graphs, the exact distance to a point of an object

or person is represented, depending on the case. This distance will be taken as reference for,

comparing it with the distance measured by the sensor, showing the degree of error

associated with it. In order to know the real distance that the obstacle of the ultrasounds is
55

in each of the tests, has used the laser distance meter (for tests at distances from 20

centimeters, the minimum that this instrument can provide) or a ruler or meter (at distances

less than 20 [cm]). It must be considered that there is always the possibility of introducing

measurement errors, the result of the human factor in experimentation.

On the horizontal axis (X), the measurements taken by the HC-SR04 sensor appear at

the same point at which the reference distance was taken. In each of the graphs, twenty

consecutive sensor measurement samples have been taken, which have been displayed on

the Arduino IDE serial monitor.


56

Test 1. From the sensor to a wall 1 [cm] away.

Test 2. From the sensor to a wall 3 [cm] away.


57

Test 3. From the sensor to a wall 10 [cm] away.


58

CONCLUSIONS

Reflections

From this research work on Arduino UNO together with the HC- ultrasonic sensor SR04

As far as distance measurement is concerned, some reflections can be carried out.

Why use Arduino and not other similar technology

The Arduino system differs from other existing platforms in the market (as explained by

Massimo Banzi, co-founder of Arduino), essentially in that: it is a multiple platform

environment (multiplatform) that can be executed in the main operating systems Windows,

Mac OS X and Linux; Your IDE is based on the programming language Processing, an

environment easy to use development, used mostly by artists and designers; it is easily

programmed by means of a cable with USB connector, and not through a serial port itself

(which some modern equipment does not have); its software and hardware is free (you can

download your IDE and its circuit diagrams, buy the components and create your own

plate, without having to pay anything for it to the creators of Arduino); the hardware is

economical (a full Arduino USB board costs about € 30 and in addition, its chips can be

replaced, so it allows you to make mistakes); is an active and constantly growing

community of users, so there are many people who can help; it was developed in an
59

educational environment, so you can get simple projects to work quickly without being an

IT or electronics expert.

Increase in the accuracy of the application developed

At the speed of sound, and therefore also that of ultrasound, values such as temperature,

humidity and latitude affect it. In this project, for the development of a simple application

for measuring distances using Arduino UNO and the HC-SR04 sensor, the constant sound

speed of 340 [° C] has been taken, assuming a temperature of 25 [° C] , a humidity of [] and

a latitude of [], since the main idea of the research work has focused solely on the

interaction of Arduino with a single sensor. But in more complex development, where the

lowest possible error degree and the interaction of Arduino with several sensors and sensors

with each other, adding a temperature sensor to the circuit, could increase the precision of

the same, so that the The ultrasound speed was influenced according to the temperature of

the medium in which the Arduino UNO board was located next to the HC-SR04 sensor.
60

Bibliography

The bibliographic references consulted for the elaboration of this end-of-degree project
are shown below, according to the standard indicated by ISO 690: 2010 and its Spanish
version UNE-ISO 690

Books consulted:

Ribas Lequerica, Joan. Arduino práctico, manual imprescindible. [En papel]. Madrid:
Ediciones Anaya Multimedia (Grupo Anaya S.A.), 2014. 400 p. ISBN: 978-84-415-3419-3.

Torrente Artero, Óscar. Arduino, curso práctico de formación. [En papel]. Madrid: RC
Libros, 2013. 588 p. ISBN: 978-84-940725-0-5.

Banzi, Massimo. Introducción a Arduino. [En papel]. Madrid: Ediciones Anaya


Multimedia (Grupo Anaya S.A.), 2012. 128 p. ISBN: 978-84-415-3177-2.

Lajara Vizcaíno, José Rafael. Pelegrí Sebastià, José. Sistemas integrados con Arduino.
[En papel]. Barcelona: Marcombo S.A., 2014. 308 p. ISBN: 978-84-267-2093-1.

Serna Ruiz, Antonio. Ros García, Francisco Antonio. Rico Noguera, Juan Carlos. Guía
práctica de sensores. [En papel]. Madrid: Creaciones Copyrigth, S.L., 2010. 226 p. ISBN:
978-84-92779- 49-9.

Morón Fernández, Carlos. García García, Alfonso. Sensores y actuadores. [En papel]
Madrid: Escuela Politécnica de Madrid, (Fundación general), 2009. 140 p. ISBN: 978-84-
96737-53-2.

Reference websites:

Arduino. Arduino Website, 2014 [consulta 2014]. Disponible en: http://www.arduino.cc


61

In addition to the websites that have been named in various footnotes throughout this
document, and a multitude of video tutorials on the Internet.

1 En la web de Arduino, está su código fuente:


https://code.google.com/p/arduino/source/browse/#svn/trunk

2 Sitio web oficial de la Open Source Initiative (OSI):


http://opensource.org/

. 3 Sitio web oficial de la Free Software Foundation (FSF):


https://www.fsf.org/

4 Para más información sobre las licencias BSD, se puede consultar:


http://en.wikipedia.org/wiki/BSD_licenses

5 Las licencias de GNU OperatingSystem pueden consultarse en:


http://www.gnu.org/licenses/licenses.en.html

6 La licencia GPL de Arduino se puede consultar en:


http://www.gnu.org/licenses/gpl-2.0.html

7 La licencia LGPL de Arduino se puede consultar en:


http://www.gnu.org/licenses/lgpl-2.1.html

8 Licencias GPL y LGPL de Arduino:


https://code.google.com/p/arduino/source/browse/trunk/license.txt

9 El sitio web de la CC, donde se pueden encontrar sus licencias, es:


http://creativecommons.org/

10 Los conceptos de “free hardware design” y “open-source hardware”, que vienen a


significar lo mimo, se pueden consultar en:
http://en.wikipedia.org/wiki/Open_source_hardware

11 Para mayor información sobre el proyecto OSHW, se puede consultar:


http://freedomdefined.org/OSHW y http://www.oshwa.org/

12 La licencia CC BY-SA (2.5 Generic), bajo la que se encuentra Arduino, se puede


consultar la CC, en los enlaces: http://creativecommons.org/licenses/by-sa/2.5/

ó http://creativecommons.org/licenses/by-sa/2.5/legalcode

13 El hardware de Arduino, es libre. Sus diseños y esquemas de referencia se pueden


consultar o descargar desde el sitio web de Arduino, en:
62

http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

14 La wiki de Arduino, conocida como playground es: http://playground.arduino.cc/

15 El foro oficial de Arduino es: http://forum.arduino.cc/

16 Puedes seguir a Arduino en Twitter, en el enlace: http://www.twitter.com/arduino

. 17 Puedes seguir a Arduino en Google+, en el enlace: https://plus.google.com/


+Arduino/posts

18 Cuenta de Facebook de Arduino: https://www.facebook.com/official.arduino

19 Canal de Youtube de Arduino: http://www.youtube.com/user/arduinoteam

20 Tienda oficial de Arduino: http://store.arduino.cc/

21 Distribuidores oficiales de Arduino: http://arduino.cc/en/Main/Buy

22 Ley de las Telecomunicaciones:


http://transparencia.mtc.gob.pe/idm_docs/normas_legales/1_0_892.pdf

23 Ley Orgánica de Protección de Datos:


http://www.pcm.gob.pe/transparencia/Resol_ministeriales/2011/ley-29733.pdf

24 La ley de Responsabilidad Medioambiental:


http://www.minam.gob.pe/wp-content/uploads/2013/06/ley-general-del-ambiente.pdf

S-ar putea să vă placă și