Chapter 6. Object detection

This chapter covers

  • Detecting objects with ultrasound
  • Range finding with active infrared
  • Detecting motion with passive infrared

In this chapter we’re going to begin exploring how to get meaningful data from the objects and environments around your Arduino controller and use it in your Arduino programs. Of course, meaningful data could mean any number of things: temperature, sound, light, color, and so on. To start, we’ll focus on detecting objects.

There are a number of fields where this is important, including robotics, monitoring, interactive applications, security, and home automation, to name a few. There are three simple technologies that this chapter will explore: ultrasonic sensors, active infrared sensors, and passive infrared sensors. All are relatively low-power and easy to configure and control, but each has distinct advantages and disadvantages that you’ll want to understand before creating sensing applications.

We’ll start with ultrasound.

Figure 6.1. How ultrasonic waves are transmitted and received by a distance sensor

6.1. Object detection with ultrasound

Ultrasound is an excellent way of figuring out what’s in the immediate vicinity of your Arduino. The basics of using ultrasound are like this: you shoot out a sound, wait to hear it echo back, and if you have your timing right, you’ll know if anything is out there and how far away it is. This is called echolocation and it’s how bats and dolphins find objects in the dark and underwater, though they use lower frequencies than you can use with your Arduino.

An ultrasonic sensor consists of two separate components: one that sends out the sound, and one that listens for it to bounce back. The sensor will also contain additional components, including a small microcontroller, that are responsible for determining the time between sending and receiving a sound. The time value is encoded in a voltage; the longer the delay, the higher the voltage. Because ultrasonic sensors communicate at 5V, the value is between a maximum 5V and a minimum 0V.

The trick of echolocation is in knowing what to do with the length of time between sending the signal and receiving it back. The meaning of that time will always be dependent on the particular component that you’re using, be it a Parallax Ping (also known as the PING)))), the Devantech SRF05, or another ultrasonic range sensor. This information can always be found in the product’s data sheet in one format or another. For instance, the datasheet for the Parallax Ping contains the following: “The PING))) returns a pulse width of 29.033 uS per centimeter.”

That’s helpful and points you in the right direction, but there’s one catch: you get the time for every centimeter travelled, when what you really want is the centimeters travelled to the object, not to and back. So you divide by two and you’re good to go.

Let’s examine two specific sensors.

6.1.1. Choosing an ultrasonic sensor

We’re going to focus on two different ultrasonic sensors: the Devantech SRF05, shown in figure 6.2, and the Parallax Ping, shown in figure 6.3.

Figure 6.2. The Devantech SRF05, an ultrasonic sensor

Figure 6.3. The Parallax Ping, an ultrasonic sensor

Both of these sensors work the same way: you signal the sensor that you want it to send out a signal, and then you read the response. The response comes back using what the Arduino calls a pulse, or simply a HIGH signal with microsecond fidelity, which means that the difference between an object that’s 30 cm away and 2 m away is approximately 40 millionths of a second.

You need a special method to read values that quickly, and the Arduino provides one:

pulseIn(pin, value)

The first value is an integer that indicates which pin you’re going to read the pulse on, and the second specifies whether you’re expecting a pulse that’s LOW or HIGH. Some components communicate by pulling the pin LOW to 0V, and others communicate by setting the pin HIGH to 5V (or 3.3V if you’re using a 3.3V powered Arduino), so it’s important to know which one you should be expecting.

The differences are slight but significant. The Parallax Ping operates in a single mode, which is to say there’s only one way to do it. It can read ranges from 3 cm to 3 m. The Devantech SRF05 has two modes, a three-wire mode and a four-wire mode, and it can read ranges from 3 cm to 4 m.

Because there’s only one way to operate the Ping, we’ll return to it later; the Devantech’s three-wire versus four-wire modes are worth exploration.

6.1.2. Three wires or four

The fourth and fifth extra pins on the Devantech SRF05 might seem strange at first, because the Ping needs only three, but there’s a good reason for it. The SRF05 had a predecessor called the SRF04, and when Devantech updated their ultrasonic range finder, they made the SRF05 compatible with wiring for the SRF04. This meant that older designs that couldn’t be changed could still easily update to a newer controller.

The slight disadvantage is that the SRF05 is a little more complex than the Ping: it has two modes. It can either use one pin to send the signal and another to listen to the result, or it can use a single wire to both send the signal and get the resulting data. Connecting the mode pin to ground means that you’re going to use the SRF05 in three-wire mode, just like the Ping. Connecting the mode pin to 5V indicates that the SRF05 will be used in four-wire mode.

6.1.3. Sketches for ultrasonic object finding

First we’ll cover working with the Parallax Ping and then the Devantech SRF05.

Sketch for the Parallax Ping

To begin, you need to configure the Arduino pin to whichever signal pin of the Ping will be connected as an input. To trigger the sensor, you set the connection pin LOW briefly and then HIGH for 5 microseconds. After that you can read the distance to any object as a length of time using pulseIn(). Note the microseconds, which are millionths of a second and can be set using delayMicroseconds(); they’re not milliseconds, which are thousandths of a second and can be set using delay().

Something else important to note is that you don’t want to send a pulse more frequently than every 30–50 milliseconds or so, because, depending on the distance of objects from the sensor, you might end up with ultrasound waves interfering with one another travelling to and from an object. After you send a pulse, calling delay(50) will ensure that your readings are free from interference.

To build this example, you’ll need the following components:

  • 1 Arduino Uno (or similar)
  • 1 Parallax Ping

This sketch will let you read ranges from the Ping.

Listing 6.1. Reading ranges with the Parallax Ping

Sketch for the Devantech SRF05

Now we’ll look at the SRF05 configured in classic or four-wire mode. The three-wire mode code for the SRF05 (using 5V, ground, and input/output pin) is very similar to the Ping, so for the sake of brevity we’ll omit that listing.

The four-wire mode requires that you set the output pin HIGH for 10 milliseconds to signal to the sensor that you’d like it to fire an ultrasonic signal, and then you can read it back in. Because the input pin is a separate pin, you pass that pin number to the pulseIn() method to read the echo distance from the SRF05.

For the example in the next listing you’ll need the following:

  • 1 Arduino Uno (or similar)
  • 1 Devantech SRF05
Listing 6.2. Reading distances with the SRF05

The 10-microsecond pause is necessary to signal to the SRF05 that you want it to send a signal . If the pause is any shorter, it won’t send out an ultrasonic wave. If it’s any longer, you might miss the wave coming back.

Now that you’ve seen the code, we can look at connecting the two controllers.

6.1.4. Connecting the hardware

To use the Ping, connect the signal pin to a digital pin on the Arduino, the 5V pin to either the power out on the Arduino or on a breadboard rail, and the ground to either the ground or a ground rail. This is shown in figure 6.4.

Figure 6.4. Connecting the Parallax Ping to the Arduino

To use the SRF05, you’ll connect differently depending on the mode that you decide to use. Figure 6.5 shows how to use the four-wire mode because that setup is different from the Ping.

Figure 6.5. Connecting the Devantech SRF05 to the Arduino

Connecting the pin marked MODE to 5V tells the SRF05 that you’ll be using it in four-pin mode, whereas connecting the MODE pin to ground indicates that you’ll be using three-pin mode.

6.1.5. Upload and test

When you upload your code, you should see the LED stay lit for a period of time proportional to the distance that the ultrasonic sensor is detecting. If you want to continue exploring, you might consider building one of the classic tropes of physical computing: the electronic theremin, which we’ll explore in the next section with a different technique: infrared (IR).

6.2. Infrared for range finding

You might choose to use infrared because it has a few advantages over ultrasound. It works much more quickly than ultrasonic sensors because, as your intuition might tell you, light travels more quickly than sound. That means the danger of interference is much lower. It also uses a much narrower beam, meaning that you can pinpoint the location you want to monitor more easily. This also avoids the problem of ghost echoes, where the width of a beam hitting a corner and echoing back creates a ghost reading for an object that isn’t there.

Infrared has disadvantages as well, though. It relies on light, so in bright direct sunlight, infrared sensors often won’t work well, if at all—sunlight will saturate the sensor, creating a false reading. Furthermore, infrared is often not able to read at the same distances as ultrasonic. For instance, the SRF05 ultrasonic sensor can clearly detect objects up to 4 m away, whereas the Sharp GP2D12 infrared sensor that we’ll use in this chapter has a maximum range of 80 cm.

6.2.1. Infrared and ultrasound together

Certain objects don’t respond well to infrared beams, and other objects don’t respond well to ultrasound. For instance, an ultrasound sensor doesn’t do particularly well with window curtains or very soft fabrics. An infrared sensor, as you might imagine, doesn’t do well with fog, smoke, particulate matter, or focused sunlight. Because the two types of sensors use very different ways of detecting objects, you can easily pair them—set them side by side or on top of one another—without risking interference.

There are many infrared distance sensors. In this chapter we’re going to focus on one in particular: the Sharp GP2D12.

6.2.2. The Sharp GP2D12 range finder

The GP2D12 has been around for a long time and consists of two components: an infrared LED that projects a focused beam, and an infrared receiver that detects the variance in the angle of the returned beam. The sensor is durable and reads from 10 cm to 80 cm without the delay that the ultrasonic sensor requires to avoid signal interference. The Sharp GP2D12 is shown in figure 6.6.

Figure 6.6. The Sharp GP2D12 IR Ranger

6.2.3. Nonlinear algorithm for calculating distance

One of the interesting aspects of working with infrared distance sensors is that the results are nonlinear, which means that getting the results from the distance sensor involves a bit more math than simply dividing or multiplying. To understand why, take a look at figure 6.7.

Figure 6.7. Distance to voltage output from the GP2D12

As you can see, the voltage returned from the GP2D12 isn’t a straight line; it’s a curve, so to interpret that correctly you need a way of dealing with the tail of that curve. Luckily, there’s a way. The following bit of code will correctly convert the voltage to centimeters:

float ratio = 5.0/1024;
float volts = analogRead(PIN);
float distance = 65*pow( (volts*ratio), -1.10);

This accounts for the nonlinear slope that you can see in the diagram.

Now that you know how to convert the data, let’s look at some more full-featured code that will show you how to set up and use the GP2D12.

6.2.4. Sketch for range finding

It’s time to do something interesting with the values that the infrared ranger is returning. As we mentioned earlier, you’re going to build one of the classic tropes in physical computing: the theremin.

For this example you’ll need:

  • One Arduino
  • One speaker
  • One Sharp GP2D12

Positioning the GP2D12 facing upwards allows you to hold your hand out over the beam, and by moving your hand up and down, you can change the notes that are played. The Arduino is never going to make particularly great sounds, but it can accurately reproduce notes by using the delayMicroseconds() method to modulate the note.

The sketch in listing 6.3 maps the distance from the infrared sensor to the 12 notes. You can create a specific tone by powering a speaker for very short periods of time. You’ll see in the following sketch that different notes are defined as lengths of time—microseconds—between powering and then stopping power to the speaker. This will create an approximation of the note.

Listing 6.3. Creating a theremin with the GP2D12

The freqout() method in listing 6.3 uses the distance to create a note that’s appropriate for the distance that the infrared ranger is returning and reacts to the amount of change the ranger detects: the larger the movement, the shorter the note. This has the effect of making the notes feel as if they’re being more precisely controlled by the user. You might want to play around with different techniques for creating this sensation of control by parameterizing the sounds even further.

6.2.5. Connecting the hardware

Connecting the GP2D12 is simple, as shown in figure 6.8. Select the pin that you would like to receive the signal on, and then connect the other two pins of the GP2D12 to 5V power and ground. The speaker should be connected to digital pin 4, with the resistor between the PWM pin that will power the speaker and the speaker itself.

Figure 6.8. Connecting the GP2D12 to the Arduino

6.2.6. Upload and test

When you run the code, you should hear the frequency of the note that’s played changing as you move your hand closer and further from the infrared sensor. You can position the sensor so that it points upwards or outwards, depending on which motion you think makes the most sense.

6.3. Passive infrared to detect movement

While an infrared ranger shoots a beam of light out and waits for it to come back, there are times when you might want to monitor a larger area and you don’t need such specific data. You simply want to know if something moved. You’re in luck, because that’s exactly the purpose of passive infrared (PIR) sensors. It’s quite likely that at some point you’ve turned a light on or off by triggering a PIR sensor either in a large room or in a yard.

A PIR sensor is essentially an infrared camera that measures infrared light radiating from objects in its field of view. Typically it calibrates for a short period of time to create a map of the infrared energy in front of it, and once the calibration is done, it triggers a signal when the amount of infrared changes suddenly. Everything emits some low-level radiation, and the hotter something is, the more radiation it emits.

The sensor in a motion detector is split in two halves because we’re trying to detect motion (change), not average infrared levels. The two halves are wired up so that they cancel each other out. If someone walks through an area that’s monitored by a PIR sensor, the hot spot on the surface of the chip will move as the person does. If one half sees more or less infrared radiation than the other, the output will swing HIGH or LOW.

As mentioned at the beginning of this section, PIR sensors are simply triggers. They typically only report movement, not information on the amount of movement, the location of that movement, or any other information beyond the amount of time that the movement lasted. But there are plenty of times when that’s all you need.

6.3.1. Using the Parallax PIR sensor

One of the more venerable and commonly used PIR sensors is the one made by Parallax. The PIR sensor has a range of approximately 20 feet, though this can vary with environmental conditions.

The sensor requires a warm-up time in order to function properly—the settling time required to learn its environment—which can be anywhere from 10 to 60 seconds. During this time, there should be as little motion as possible in the sensor’s field of view. The sensor is designed to adjust to the slowly changing conditions that would happen normally as the day progresses and as environmental conditions change. But when sudden changes occur, like someone passing in front of the sensor or something quickly changing the infrared field in front of the sensor, it will detect the motion.

The sensor’s output pin goes to HIGH if motion is present and to LOW when the infrared detected is the same as the background. But even if motion is present, it goes to LOW from time to time, which might give the impression that no motion is present. The program in listing 6.4 deals with this issue by ignoring LOW phases shorter than a given time, assuming continuous motion is present during these phases.

The sensor itself is small, light, and easy to connect. It’s shown in figure 6.9.

Figure 6.9. The Parallax PIR sensor

Notice the three connector pins, which are power, ground, and the signal pin.

6.3.2. Sketch for infrared motion detection

The first thing you may notice about the following PIR sensor code is how the calibration time is used to essentially stall the loop() from reading the PIR sensor until 30 seconds have passed. This is because the PIR sensor needs time to create an accurate map of the environment to compare against.

The next thing to note is how the loop() method contains a conditional statement to detect whether the sensor is returning HIGH or LOW and how long it’s been pulled HIGH, if it has been. The Parallax PIR sensor returns HIGH until the motion ceases, so by keeping track of the amount of time since the sensor was pulled HIGH, you can determine how long the object or entity moved in the field of vision of the PIR sensor (see the following listing).

Listing 6.4. Detecting motion with the Parallax PIR sensor

When the motion ends, the program writes the duration of the motion in front of the PIR sensor to the serial monitor.

6.3.3. Connecting the hardware

For this example you’ll need the following components:

  • A Parallax PIR sensor
  • An Arduino
  • A 10k resistor

To connect the PIR sensor, you simply connect the power pin to 5V, ground to GND, and the data pin to D3, as shown in figure 6.10. A pull-up resistor is used to ensure that the pin stays HIGH until it’s actually pulled low by the PIR sensor. Without this, the readings from the sensor might float after the initial HIGH reading.

Figure 6.10. Connecting the Parallax PIR sensor to the Arduino

6.3.4. Upload and test

An easy way to test that the sensor is detecting motion is to point it at the ceiling, count to 30, and then wave your hand a meter or so above the sensor. You should see the length of time that your hand moves in front of the sensor returned in the Arduino IDE serial monitor. This will also give you a sense of the width of the field of vision of the sensor.

6.4. Summary

In this chapter, you’ve learned a few different techniques to make the Arduino contextually aware, enabling it to perform simple object detection, range finding, and motion detection. This sort of capability goes a long way toward making interactive systems that can react to their users and respond to the location of their users or objects in their environments. These are the first steps toward creating autonomous vehicles, detection systems, security systems, simple presence-activated systems, and of course, fun musical instruments.

In the next chapter, you’ll learn about using LCD screens with your Arduino.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset