[EN] Raspberry Pi & Ultrasonic Sensor

This article discusses how to use an ultrasonic module with a Raspberry Pi board (the previous article applies to the ESP8266) in Python to show the distance from the sensor to the closest object found.

(Figure. 1 VisionRobo with Ultrasonic Sensor)


The experimental instruments in this article consist of

  1. Raspberry Pi 3 or 4
  2. Ultrasonic Sensor


The connection of the Ultrasonic Sensor module to the Raspberry Pi board is shown in the following table.

Raspberry PiUltrasonic Sensor
(Figure. 2 Connection between Ultrasonic Sensor and GPIO of Raspberry Pi)

Example Code

Example code25-1 defines  GPIO20 as a Trig pin to emit the sound signal and  GPIO21 as an Echo pin to wait for the reflected sound signal. The movement timing of the reflected sound uses the commands time.monotonic() then calculate the distance in centimeters and report the result as shown in Figure 3.

from time import time
from time import monotonic
from time import sleep
import RPi.GPIO as GPIO

pinTrig = 20
pinEcho = 21
mps = 343 # Metre per second (Sound speed)
GPIO.setup(pinTrig, GPIO.OUT)
GPIO.setup(pinEcho, GPIO.IN)

GPIO.output(pinTrig, False)
GPIO.output(pinTrig, True)
GPIO.output(pinTrig, False)

# send trig
GPIO.output(pinTrig, True)
GPIO.output(pinTrig, False)
# start count
t0 = monotonic()
while GPIO.input(pinEcho) == 0:
    # wait for echo
while GPIO.input(pinEcho) == 1:
    # wait for end echo
t1 = monotonic()
echoTime = t1-t0
distance = (echoTime*mps*100)/2
print("{} cm.".format(distance))
(Figure. 3 result of code25-1)


From this article, you will find that the working principle and how to write a program in Python to use the Ultrasonic Sensor module to measure the distance between the sensor and the nearest object found using the same writing principle as the ESP8266 board. But the few differences are steps in differentiating GPIO and different libraries, because MicroPython is only part of a small board-based Python interpreter, it needs to be reduced and optimized. But the Python language on the Raspberry Pi board is the same as that used on the PC, so it is compatible. And therefore writing in Python is ideal for programmers who focus on usability and speed of testing. But when the speed performance of development is needed, programmers may choose to use lower-level languages ​​such as C/C++ and Assembly.

Finally, we hope this article will be useful to everyone and have fun with programming

(C) 2020, By Jarut Busarathid and Danai Jedsadathitikul
Updated 2021-09-14