Ultrasonic Distance Sensor Implementation
Ultrasonic Distance Sensor Implementation
Here, we provide two approaches for sensor implementation. The first approach is useful and takes less effort when we integrate a single sensor directly to the MQTT broker by assigning pins and the measurement block. In the second approach, we define an abstract class in order to aggregate the common features of the sensors, which is an efficient way when we need to implement many sensors and connect them to an MQTT broker. The structure of the code is divided in two blocks, namely sensor implementation and MQTT connection.
Sensor Implementation – Simple Approach
First, download the
repository for this example:
git clone https://github.com/GT-ARC/CC-IoT/
The above command will create a local copy of all codes required in this batch of training modules (from IOT-1 to IOT-10). For the current training module, browse to the directory “CC+IoT/1-2- 3/Task_1/Part_A/” in your local repository and open the file named distance_sensor_simple.py. Alternatively, you can directly download the file from this URL:
If you have not downloaded the file
from the repository, you may also create an empty file with this name and paste
the content in Listing 1. The code in Listing 1 can be used for testing the
sensor and getting experience with the sensors.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
PIN_TRIGGER = 7
PIN_ECHO = 11
GPIO.setup(PIN_TRIGGER, GPIO.OUT)
GPIO.setup(PIN_ECHO, GPIO.IN)
while True:
GPIO.output(PIN_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(PIN_TRIGGER, False)
startTime = time.time()
stopTime = time.time()
while GPIO.input(PIN_ECHO) == 0:
pass
startTime = time.time()
while GPIO.input(PIN_ECHO) == 1:
pass
stopTime = time.time()
# time difference between start and arrival
TimeElapsed = stopTime - startTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
print ("Distance: %.1f cm" % distance)
time.sleep(1)
Listing 1: Simple ultrasonic distance sensor implementation
It is recommended to check whether python is installed on the working environment with typing python –version to the terminal. If you see the installed version, then you can run the above code simply by calling the following command:
python distance_sensor_simple.py