Ultrasonic Sensor with Raspberry Pi.
April 22, 2018April 28, 2019 2 Comments hc sr04 raspberry pi example, hc sr04 raspberry pi library, hc-sr04, hc-sr04 ultrasonic range sensor, hc-sr04 ultrasonic sensor, OLED, pyaudio, , python ssd1306 oled, raspberry pi distance sensor, ultrasonic sensor, ultrasonic sensor raspberry pi tutorial Measuring distance using Ultrasonic Sensor with Raspberry Pi – Python – HC-SR04.
Today we are going to see how to measure distance using HC-SR04 Ultrasonic sensor with Raspberry Pi.
How to measure distance of an object?.
If you want measure the distance between you and the object in interest, there are quiet a few methods based on the medium.
The different medium that can be used are Light, Sound and Radio Frequency.
In all the mediums the common technique is as follows.
You have a source or transmitter and a sink or receiver.
The transmitter transmits the pattern and it hits the object and reflects.
The reflected source is detected and received by receiver.
Now the time taken for the source to make a round trip is measured and by using the speed of the medium it is derived.
Now lets get in to some detail about the mediums Light, Sound and RF.
The light based distance sensor can be achieved using Infrared distance sensor and Laser sensor.
The Radio based distance measurement is done using Radar sensor technique.
The Sound based technique is done using Infrasonic and Ultrasonic sensor
The key difference in all the three is that the Ultrasonic cannot work on Vacuum
Infrared cannot work at high temperature.
Today we are going to see how to measure the distance using Ultrasonic sensor
An Ultrasonic sensor is a device that measures the distance of an object using ultrasonic sound waves.
It is also called Ultrasonic transducer
The sound wave is classified in to InfraSound (20 Hz down to 0.1 Hz ), Acoustic sound and Ultrasonic waves. Here the Infrasound and Ultrasonic are not audible to human ears.
Interestingly Infrasound can be heard by Elephant and we all know that Bats use ultrasonic waves for navigation.
It is not only Bats but also Cats, Dogs, Dolphins, Mice even Mosquito can hear ultrasonic sound.
There are many devices which use ultrasonic waves to control them e.g Dog whistle.
Although the distance measurement can be achieved by all Infra, Acoustic, Ultrasonic
the audible frequency will be loud and can be disturbed by noise.
Ultrasound operate in frequencies from 20 kHz up to several gigahertz.
They are used in many fields and it can be used detect objects and measure distances.
The below links are part of my affiliate links Raspberry Pi.
Banggood , Amazon Ultrasonic Sensor:.
Banggood Amazon UK Amazon US Amazon Germany Wires:.
Banggood Amazon UK Amazon US Amazon Germany Ultrasonic sensor overview
Now that we have seen some theory lets get started with our project.
The Ultrasonic sensor module that we are using is HC-SR04
There are four pins in the module Vcc, Gnd, Trigger and Echo.
This module operates at 5 volt with a consumption of 15 mA current. It can measure the distance effectively starting from 2 cm to 400 cm (4 Meter). The module works as follows if you send a supply a short 10uS pulse to the trigger input to start the ranging, then the module will send out an 8 cycle burst of ultrasound at 40 kHz.
This 8 burst pattern hits the object and reflects back.
Now once the 8 burst pattern is sent, the Echo pin is set high (i.e 5 V ) and when the signal reflects and comeback the Echo pin is set low (0 V).
This time duration for which the Echo pin stays high is the time taken for ultrasonic wave to travel and comeback, yes the round trip.
Now you know the time taken for the Ultrasonic wave to make a round trip around the object.
We can now derive the distance if we know how fast the Ultrasonic wave travel
The Ultrasonic wave is a sound wave
and the speed of sound is 343 metres per second. If TimeElapsed is the time the Echo pin was high.
Then the formula looke like as shown below.
It is divided by two since it round trip.
distance = (TimeElapsed * 34300 ) / 2 Now we know how the module works and the pinout details lets start connecting the Ultrasonic sensor with Raspberry Pi. Like mentioned earlier the operating voltage of the module is 5V. The input pin on the Raspberry Pi GPIO is only 3.3V tolerant.
Sending a 5V signal into 3.3V input port could damage the GPIO pins.
So we need to solve this problem.
We have two solutions one is to use a logic level converter and other is to use a voltage divider.
The logic level convert is useful if you want to pass the information from both the sides, though it will work in this case it is not required as the Echo pin is just controlled by the HC-SR04 module and Raspberry Pi will only listen for the changes.
So we should use the voltage divider to bring the voltage under the 3.3v.
The above picture is an example of a voltage divider. A voltage divider is a simple circuit which turns a large voltage into a smaller one.
The input voltage is connected to two resistors in series.
Here I fixed the R1 to be 1K ohms resistor and used this online voltage divider calculator to get the value of R2.
It shows that its 1.9 which is close to 2K so I used a 2K resistor.
Note: If you supply 3V to the module, it would operate in 3V and it sounds like a great idea.
But It seems like the ultrasonic sensor module does not work properly at 3V3.
Ultrasonic sensor with Raspberry PI
Now with this knowledge we can start the connection.
We need to connect the pins in the following order.
Vcc = 5V Gnd = Gnd Trigger = Pin 23 Echo (via voltage divider) = Pin 24 Schematics.
The schematics that I am used is shown below.
Now lets get to the software part.
The ultrasonic modules operates on GPIO level and it requires no addition software to be installed.
Everything will work out of the box with python as well.
Here I have created a python script distance.py.
You can log in to the Raspberry Pi via serial or SSH interface and run the script as follows $ python distance.py Output:.
The output can be seen in the terinal console or putty where you run the python code, like shown below.
Here in the the sensor was sitting on the table and pointing to a wall and that distance is approximately 300 CM.
Measured Distance = 302.8 cm Measured Distance = 303.1 cm Measured Distance = 303.5 cm Measured Distance = 303.2 cm Measured Distance = 300.9 cm Measured Distance = 304.0 cm Measured Distance = 302.1 cm Measured Distance = 301.9 cm Measured Distance = 301.4 cm Measured Distance = 303.3 cm Measured Distance = 301.9 cm Measured Distance = 303.0 cm Explanation.
GPIO as GPIO import time GPIO.setmode(GPIO.
BCM) The first two are the import operation, to get the required library for using it in project.
The setmode GPIO.
BCM option means that the pinumber we are using in the script refers to “Broadcom SOC channel” number.
GPIO_TRIGGER = 23 GPIO_ECHO = 24 The pin number 23 is defined as trigger pin and 23 as Echo pin.
OUT) GPIO.setup(GPIO_ECHO, GPIO.
IN) The trigger pin which sends the 10uS pulse to the HC-SR04 module is set as output and the echo pin which sends the signal from module to Pi as input.
def distance(): GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) The function distance, sets the trigger go high wait for a micro second and set the pin to low.
This is tell the module to send the 8 burst pattern using the ultrasonic transducer.
StartTime = time.time() StopTime = time.time() while GPIO.input(GPIO_ECHO) == 0: StartTime = time.time() while GPIO.input(GPIO_ECHO) == 1: StopTime = time.time() Firstly you store the current time in the StartTime and StopTime variables, Now you wait for the Echo pin to go high and until that read the time and store it in StartTime.
And same way after it goes past that block you wait for it to go low and until then read the time and store it in StopTime.
TimeElapsed = StopTime – StartTime distance = (TimeElapsed * 34300) / 2 return distance Now you have the time when the echo pin went high and the time it went low.
You can find the elapsed time by doing subtraction StopTime – StartTime and store it in TimeElapsed.
You can calculate the distance by using the time taken by sound wave multiplied by speed of light and divide it by 2 in order to get the distance of the oneway.
Interfacing with OLED Display:.
Now we are done with the basic interfacing, to make this application independant of the putty or console, we will interface this with the OLED display and display the distance there.
I have a tutorial on how to interface OLED display with Raspberry Pi.
The connection looks like shown below Connection:.
Apart from the below line which prints to the console.
print (“ Measured Distance = %.1f cm“ % dist) The additional line draw.text((10 , 40 ), “ Distance = %.1f cm“ % dist, fill = “ white“ ) prints the distances information to the OLED Display. As mentioned earlier refer to my tutorial on how to setup OLED with Raspberry Pi for more details.
Now having extended the code to display in OLED display.
The next step is to do some application oriented projects.
Some ideas are Taking a photo when you come closer to the Ultrasonic sensor
Or Ultrasonic vehicle parking system
I will provide some basics gist of the latter one here Ultrasonic vehicle parking system: While you ever you reverse a car and when it nearing an object may it be car or a wall t it generates a tone and the frequency increases as you go closer to the object.
This can be implemented in Raspberry Pi.
Below is the example code.
It works using Pyaudio and you need to install a package before running it.
sudo apt-get install python-pyaudio Code:.
I think this covers up the basic usage of ultrasonic sensor.
If you have any comments or feedback please use the comments section below.
Same way you can also checkout my other tutorials on , , and ESP8266/ESP32.
← How to setup OLED display with Raspberry Pi.
Rotary encoder with Raspberry Pi – OLED Menu →.
You May Also Like.
How to setup 2 Axis analog joystick with Arduino.
June 15, 2017 4 Blink LEDs using Orange Pi Zero GPIO and Python.
May 28, 2017 10 How to flash Attiny85 using Arduino.
November 24, 2016 0 2 thoughts on “Ultrasonic Sensor with Raspberry Pi ”.
Solanke Jyoti Tanaji February 7, 2019 at 2:21 pm Permalink This is a very useful information for mi about the connectivity of ultrasonic sensor and the raspberry pi.
John August 20, 2019 at 1:14 pm Permalink I would like to trigger an event(calling a script) when there is not an obstable in a particular range 0-100cm.
If further then do nothing.
When the obstacle comes within this range, then call the script.
Could you help me modify the script please.
Leave a Reply Cancel reply.
Your email address will not be published.
Required fields are marked * Comment Name * Email * Website Notify me of follow-up comments by email.
Notify me of new posts by email.