Reader small image

You're reading from  Practical Python Programming for IoT

Product typeBook
Published inNov 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838982461
Edition1st Edition
Languages
Right arrow
Measuring Distance and Detecting Movement

Welcome to our final core electronics-based chapter. In the previous chapter, we learned how to control three different forms of motors in complex ways. In this chapter, we will direct our attention to detecting movement and measuring the distance with our Raspberry Pi and electronics.

Detecting movement is very useful for automation projects such as turning on lights when you walk into a room or building, an alarm system, building counters, or detecting revolutions of a shaft. We will be looking at two techniques for movement detection, including a Passive Infrared (PIR) sensor that uses heat detection to detect the presence of a person (or animal), and a digital Hall-effect sensor that detects the presence of a magnetic field (or, more liberally, we can say that the Hall-effect sensor can detect when a magnet moves past it...

Technical requirements

To perform the exercises in this chapter, you will need the following:

  • Raspberry Pi 4 Model B
  • Raspbian OS Buster (with desktop and recommended software)
  • Minimum Python version 3.5

These requirements are what the code examples in this book are based on. It's reasonable to expect that the code examples should work without modification on Raspberry Pi 3 Model B or a different version of Raspbian OS as long as your Python version is 3.5 or higher.

You will find this chapter's source code in the chapter11 folder in the GitHub repository available at https://github.com/PacktPublishing/Practical-Python-Programming-for-IoT.

You will need to execute the following commands in a terminal to set up a virtual environment and install the Python libraries required for the code in this chapter:

$ cd chapter11              # Change into this chapter's folder
$ python3 -m venv venv # Create Python Virtual Environment
$ source venv/bin/activate...

Detecting movement with a PIR sensor

A PIR sensor is a device that can detect infrared light (heat) emitted by an object (for example, a person). We see these types of sensors all around us in applications such as security systems and automatic doors and lights that react to our presence. The passive in PIR means the sensor just detects movement. To detect what moved and how, you would need an active infrared device, such as a thermal camera.

PIR sensors come in a few different forms and varieties; however, their basic usage is the same – they act as a simple digital switch. When they do not detect movement, they output a digital LOW, and when movement is detected, they output a digital HIGH.

Shown in the following figure is the HC-SR501 PIR sensor module that we will be using for our example. Pictured are the top of the module, the underside, and a common schematic symbol for a PIR sensor:

Figure 11.1 – HC-SR501 PIR sensor module

Some PIR sensors, including our...

Creating the PIR sensor circuit

In this section, we will connect our PIR sensor to our Raspberry Pi. The following is the schematic diagram of the circuit we are about to build. As you can see, it has relatively straightforward wiring from the perspective of the PIR sensor:

Figure 11.2 – PIR sensor module circuit

Let's connect it to our Raspberry Pi as illustrated in the following figure:

Figure 11.3 – PIR sensor circuit breadboard layout

Here are the steps to follow to create your breadboard build. The step numbers match the numbers in black circles in Figure 11.3:

  1. Connect each terminal of your PIR sensor to your breadboard. You will need three male-to-male jumper cables.
  2. Connect a 5-volt pin on your Raspberry Pi to the same breadboard row used by the PIR's Vcc terminal. PIR sensors only use a little current, so it will be okay to connect the 5-volt Vcc pin directly to your Raspberry Pi.
  3. Connect a GND pin on your Raspberry Pi to the same...

Running and exploring the PIR sensor code

The code for out PIR circuit is found in the chapter11/hc-sr501.py filePlease review the source code before proceeding to get a broad understanding of what this file contains.

The HC-SR501 datasheet stipulates that the sensor needs around 1 minute after power-on to initialize and stabilize itself. If you try and use the sensor before it becomes stable, you may receive a few erroneous triggers when you start the program.

Run the hc-sr501.py file in a terminal. When the HC-SR501 detects movement, the program will print Triggered on the terminal, or Not Triggered when no movement is detected, as shown in the following output:

(venv) $ python hc-sr501.py 

PLEASE NOTE - The HC-SR501 Needs 1 minute after power on to initialize itself.

Monitoring environment...
Press Control + C to Exit
Triggered.
Not Triggered.
... truncated ...

If your program is not responding as expected, try adjusting one or more of the Sensitivity...

Measuring distance with an ultrasonic sensor

In the previous section, we learned how to detect movement with a PIR sensor. As we discovered, our PIR sensor was a digital device that signaled movement detection by making its output a digital HIGH.

It's time to learn how to measure distance with our Raspberry Pi. There are a variety of sensors that are capable of performing this task, and they commonly either work with sound or light. Our example will be based around the popular HC-SR04 ultrasonic distance sensor (it works on sound), as pictured in the following figure:

Figure 11.4 – HC-SR04 ultrasonic distance sensor module

A place where you commonly find ultrasonic distance sensors is modern car bumper bars (they're often little round circles, which is a different form factor than the HC-SR04 pictured in the preceding figure). These sensors calculate the distance between your car and a nearby object and, for example, make a beeper inside your car...

How an ultrasonic distance sensor works

Let's see how the transmitter (TX) and receiver (RX) work together to measure distance. The basic operating principle of an ultrasonic sensor is illustrated in the following figure:

Figure 11.5 – Ultrasonic distance sensor operation

Here is what happens:

  1. First, the sensor sends out an ultrasonic pulse from the transmitter (TX).
  2. If there is an object in front of the sensor, this pulse is bounced off the object and returns to the sensor, and is detected by the receiver (RX).  
  3. By measuring the time between transmitting a pulse and receiving it back, we can calculate the distance between the sensor and the object.

With this high-level understanding of how the sensor works, next, we will go deeper and discuss how to use the TRIG and ECHO terminals on the HC-SR04 together in a process to estimate distance.

HC-SR04 distance measurement process

In this section, we will cover the process used to measure distance with the HC-SR04. Don't get concerned if this does not make immediately sense. I've provided the details here as background material, as this is the logical process that is implemented by our example program to make the sensor work. You will also find the process documented in the sensor's datasheet.

We measure distance with the HC-SR04 through the correct use and monitoring of the TRIG and ECHO pins. The process looks like this:

  1. Pull the TRIG pin HIGH for 10 microseconds. Pulling TRIG HIGH also makes the ECHO pin HIGH.
  2. Start a timer.
  3. Wait for either of the following to happen:
    • ECHO to go LOW
    • 38 milliseconds to elapse (from the datasheet, this is the time for >4 meters)
  4. Stop the timer.

If 38 milliseconds have passed, we conclude that there is no object in front of the sensor (at least within the effective range of 2 centimeters to 4 meters). Otherwise...

Building the HC-SR04 circuit

It's time to build our HC-SR04 circuit. A schematic of our circuit is shown in the following figure. This wiring will be suitable for both an HC-SR04 or HC-SR04P module:

Figure 11.6 – HC-SR04 (5-volt logic ECHO pin) circuit 

As a reminder, the HC-SR04 module (or an HC-SR04P wired like this to a 5-volt source) is a 5-volt logic module, and hence you will notice the voltage divider in the circuit created by the two resistors to convert 5 volts into 3.3 volts. If you need a refresher on voltage dividers, we covered them in detail in Chapter 6, Electronics 101 for the Software Engineer

Let's build this circuit on our breadboard:

Figure 11.7 – HC-SR04 circuit breadboard layout (part 1 of 2)

Here are the steps to follow to create the first part of your breadboard build. The step numbers match the numbers in black circles in Figure 11.7:

  1. Place a 1kΩ resistor (R1) into your breadboard.
  2. Place a 2kΩ...

Running and exploring the HC-SR04 example code

The example code for the HC-SR04 can be found in the chapter11/hc-sr04.py file. Please review the source code before proceeding to get a broad understanding of what this file contains.

Place a solid object in front of the HC-SR04 (about 10 cm) and run the code in a terminal. As you move the object nearer or further from the sensor, the distance printed in the terminal will change, as indicated here:

(venv) python hc-sr04.py
Press Control + C to Exit
9.6898cm, 3.8149"
9.7755cm, 3.8486"
10.3342cm, 4.0686"
11.5532cm, 4.5485"
12.3422cm, 4.8591"
...

Let's review the code.

Firstly, we define the TRIG_GPIO and ECHO_GPIO pins on line 1, and the VELOCITY constant for the speed of sound at line 2. We're using 343 meters per second.

Our code is using 343 m/s for the speed of sound, while the datasheet suggests the value 340 m/s. You will also find other HC-SR04 examples and libraries that use slightly different...

Detecting movement and distance with Hall-effect sensors

Our final practical example in this chapter will illustrate the use of a Hall-effect sensor. Hall-effect sensors are simple components that detect the presence (or absence) of a magnetic field. In contrast to a PIR or distance sensor, you can use a Hall-effect sensor together with a magnet to monitor small-range – and even very rapid – movements. For example, you could attach a small magnet to the shaft of a DC motor and use a Hall-effect sensor to determine the motor's revolutions per minute.

Another common application of a Hall-effect sensor is in mobile phones and tablets. Some phone and tables covers and cases have a small magnet in them. As you open or close the case, your device detects the presence or absence of this magnet with a Hall-effect sensor and automatically turns on or off the display for you.

Hall-effect sensors come in three types, described as follows:

  • Non-latching switch types (digital):...

Creating a Hall-effect sensor circuit

We will be building the following circuit on our breadboards. Similar to our HC-SR04 example and circuit in Figure 11.5, we need to use a voltage divider since our Hall-effect sensor outputs 5-volt logic, which we need to shift down to 3.3 volts:

Figure 11.10 – Hall-effect sensor circuit

You will notice that the output of this circuit is dualistic and will depend on which sensor you are using:

  • For a non-latching switch or latching switch type Hall-effect sensor, you will connect the circuit directly to GPIO 21 since the sensor will output a digital HIGH/LOW signal.
  • For a ratiometric type Hall-effect sensor, you will need to connect the sensor to your Raspberry Pi via your ADS1115 analog-to-digital converter since the sensor outputs a varying analog voltage.
I have not included the ADS1115 wiring in Figure 11.9 or in the following stepped breadboard layouts. We have already seen how to connect an analog output...

Running and exploring the Hall-effect sensor code

You will find the code for Hall-effect sensors in the chapter11/hall_effect_digital.py file for switch and latching switch type Hall-effect sensors and the chapter11/hall_effect_analog.py file for ratiometric type Hall-effect sensors.

What you will find when you review these two files is the following:

  • chapter11/hall_effect_digital.py is functionally identical to the PIR code example we covered previously in this chapter in the section titled Running and exploring the PIR sensor code. Both the PIR and non-latching/latching Hall-effect sensors are digital switches. The only difference is that our reference Hall-effect sensor is active LOW.
  • chapter11/hall_effect_analog.py is similar to other analog-to-digital examples we have seen using the ADS1115 ACD, including the circuit wiring and code from Chapter 5, Connecting Your Raspberry Pi to the Physical World.
The varying voltage range outputted by the AH3503...

Summary

In this chapter, we looked at ways to detect movement and estimate distance with our Raspberry Pi. We learned how to use a PIR sensor to detect broad movements, and how a switch-type Hall-effect sensor can be used to detect the movement of a magnetic field. We also discovered how to use an ultrasonic range sensor to estimate absolute distance on a larger scale, and how to use a ratiometric-type Hall-effect sensor to measure relative distances on a small scale.

All our circuits and examples in this chapter have been input focused – telling our Raspberry Pi that some event has occurred, such as the detection of a person moving or that a distance is being measured.

You are in a great position now to combine input circuits such as those covered in this chapter (and also in Chapter 9, Measuring Temperature, Humidity, and Light Levels), with output-based circuits and examples from Chapter 7, Turning Things On and OffChapter 8, Lights...

Questions

As we conclude, here is a list of questions for you to test your knowledge of this chapter's material. You will find the answers in the Assessments section of the book:

  1. Can a PIR sensor detect the direction that an object is moving?
  2. What are some factors that can affect the measurement accuracy of an ultrasonic distance sensor?
  3. How does the output of a latching or non-latching Hall-effect sensor differ from the output of a ratiometric Hall-effect sensor?
  4. In relation to this PiGPIO function call, callback = pi.callback(GPIO, pigpio.EITHER_EDGE, callback_handler), what does the pigpio.EITHER_EDGE parameter mean?
  5. In a 5-volt to 3.3-volt resistor-based voltage divider consisting of a 1k Ω and 2k Ω resistor, why is important to connect the two resistor values the correct way around in a circuit?
  6. Both the HC-SR04 ultrasonic distance sensor and the HC-SR501 PIR sensor were powered using 5 volts connected to their respective Vcc pins. Why did...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Practical Python Programming for IoT
Published in: Nov 2020Publisher: PacktISBN-13: 9781838982461
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime