# 18 – Circuit with distance sensor

#### Objectives

• Introduce the ultrasonic distance sensor
• More on time measuring: delayMicroseconds()
• More available functions: PulseIn()
• Importing an external library

#### BILL OF MATERIALS

 Arduino Uno or equivallent. We can use any other Arduino board in this chapter. A solderless Breadboard plus some jumper wires. Distance sensor HC-SR04 A LED diode and a resistor.

#### HOW DOES A ULTRASONIC DISTANCE SENSOR WORK?

We have seen in documentaries, that bats are able to fly in complete darkness and yet overcome obstacles or catch insects in flight. We know they do it, but we rarely think how.

We have a vague idea that this phenomenon is called echolocation, which, more or less, has to do with a high-pitched sounds emitted and then collected with those big ears that God has given them, but we rarely ask ourselves how this is possible.

Dolphins and whales use a similar system to catch their prey, and even we have seen that in any submarine films, at the culminating moment, the captain orders issuing a single sonar pulse to locate the enemy.

The basic concept is always the same, knowing how fast sound travels, if we issue a short sonic pulse and hear how long it takes the echo to return we can calculate the distance to the object on which the signal has bounced.

• The radar works similarly but using radio waves, often very short and with a huge problem itself. A radiofrequency pulse is emitted from the antenna and the returned echo is collected at the speed of light..

What we will do in this chapter is to use a simple remote sensor HC-SR04 (very similar to modern car parking sensors), which allows us to send these ultrasonic pulses and hear the return echo. By measuring this time, we can calculate the distance to the obstacle.

• The human ear does not perceive sounds above 20 kHz. Therefore, the higher frequency waves are called ultrasound waves, that is, waves beyond the sound. Ultrasonic sensors operate on 40 kHz.
• They are not perfect as they are influenced by environment temperature, moisture and materials on which they are reflected, creating some uncertainty. But instead they are cheap and effective up to 3 meters under normal conditions, provided that accuracy is not a key problem

#### CIRCUIT WIRING DIAGRAM

Let’s see how to connect one these sensors to our Duinos. Here is the circuit schematic diagram courtesy of Fritzing:

And again here it is the wiring schematic diagram:

#### THE CONTROL PROGRAM

#define trigPin 13
#define echoPin 12
#define led 2

So far we have seen that we could define a variable as int, for example, and also as a constant (const int pin). Here we use another method, the #define preprocessor directive.

This only means that the compiler (actually the preprocessor) will change all occurrences of these #define in our program for their value before compiling. This is the classic form of C++ to do this and has the virtue that does not occupy memory defining a variable (and this can be critical at times for an Arduino UNO, because it hasn’t very much memory).

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

We’re more than accustomed to the delay function (millis()), but the internal Arduino clock measure time in microseconds so we have another similar function, delayMicroseconds(microseconds), that simply freezes Arduino the specified number of microseconds.

To send an ultrasonic pulse what we have to do is to activate the Trigger pin for a few microseconds, setting it HIGH, before hearing the echo:

digitalWrite(trigPin, LOW);     // Nos aseguramos de que el trigger está desactivado
digitalWrite(trigPin, LOW);     // We set the trigger LOW
delayMicroseconds(2);           // We make sure the trigger is already LOW
digitalWrite(trigPin, HIGH);    // We set HIGH the output pulse
delayMicroseconds(10);          // Wait 10µs. Pulse keeps HIGH during this time interval
digitalWrite(trigPin, LOW);     // We set the pulse LOW and wait for the echo

To listen to the pulse we will use another function, pulseIn() (oh yes, there are many, too many functions). To read the reference information about pulseIn(), look for Arduino pulseIn in google and you will find it out soon.

Basically pulseIn() reads a pulse on the chosen pin looking for a signal to go HIGH (if you pass HIGH as a parameter) and counts the time it takes to go LOW again.

long duracion, distancia ;
duracion = pulseIn(echoPin, HIGH) ;

We know now the time it takes the echo to return in microseconds. As the speed of sound is 343 m / sec, it takes 1/343 = 0.00291 seconds to cover a meter.

To use a more convenient measure we will convert it to microseconds per centimeter:

As our echo measures the time it takes the pulse to go and come back, the distance will be the half:

And this is the final sketch:

#define trigPin 13
#define echoPin 12
#define led 2

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

void loop()
{   long duration, distance ;
digitalWrite(trigPin, LOW);        // We set the trigger LOW
delayMicroseconds(2);              // We make sure the trigger is already LOW
digitalWrite(trigPin, HIGH);       // We set HIGH the output pulse
delayMicroseconds(10);             // Wait 10µs. The pulse keeps HIGH during this time interval
digitalWrite(trigPin, LOW);        // We set the trigger LOW and wait for the echo
duration = pulseIn(echoPin, HIGH) ;
distance = duration / 2 / 29.1  ;
Serial.println(String(distance) + " cm.") ;
int Limit = 200 ;                  // Measure of the sensor in vacuum
if (distance < Limit)
digitalWrite ( led , HIGH) ;
else
digitalWrite( led , LOW) ;
delay (500) ;                       // To limit the number of measures
}

To turn this into a motion detector we have defined a variable that holds a value slightly less than the measure that the sensor receives in vacuum (in my case about 200 cm). If the measured distance falls below this value is that something has been interposed and therefore we will turn on an alarm, in our case a humble LED.

After this exercise in physics and mathematics, which will certainly cause a stir among applied students, we will rewrite the same program but using an external library, that someone has bothered to write for those few people who do not enjoy science problems, so we can see the difference.

You can download the library here NewPing v1.5, or just from the author’s web.

To install an external library not included in the Arduino IDE we have to import it navigating to Sketch\Include Library\Add .ZIP Library…

In the window we must search and select the file NewPing_v1.5.zip, that we have previously downloaded.

It is done. Arduino has imported the library and all the examples are included. If you turn now to Sketch\Include Library, you will see that the NewPing library is now available at the end of the list. The zip file also includes several examples.

We will load an example sketch equivalent to the previous sketch.

Navigate to File \ Examples \ NewPing \ NewPingExample:

Arduino will load an example sketch. The key statements used in the sketch are first, the statement to initialize a sonar object of the library:

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE) ;

And second, the statement to measure distance:

unsigned int uS = sonar.ping() ;

This is the example code:

#include <NewPing.h>

#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11    // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance

void setup()
{
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop()
{
delay(50);
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS)
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM);
Serial.println("cm");
}

As you see, the library is responsible for the initialization of the necessary pins, sending the pulses, hearing the return echo and doing the math. Not that bad.

• Pay attention to the fact that the example use different pins to which we have used, so we have to modify them. Similarly, the example initializes the serial port to 115,200 baud. The transmission speed must match the Serial port speed otherwise you will see many strange things on the screen.
• Sharp students should have noticed that Arduino IDE is full of examples that they can load and use. I invite you to investigate and play with these examples as you want.

#### Summary

• We have known the ultrasonic distance sensors:
• They are used to measure something up to 3 or 4 meters.
• They are not perfect but are useful and cheap.
• More on measuring time: delayMicroseconds().
• More available functions: PulseIn().
• We have learnt to import an external library. We will use them more and more in further chapters as elements get more sophisticated