Skip to content
Snippets Groups Projects
Commit 3108263b authored by jhierck laptop's avatar jhierck laptop
Browse files

Added ultrasound sensor script

parent 596e5ea5
No related branches found
No related tags found
No related merge requests found
# Libraries
import RPi.GPIO as GPIO
import time
# GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
print(GPIO.VERSION)
class UltrasoundSensor:
SONIC_SPEED = 343 # Speed of sound in m/s
def __init__(self, name, trigger_pin: int, echo_pin: int):
self.name = name
self.trigger_pin = trigger_pin
self.echo_pin = echo_pin
# Setup GPIO pins
GPIO.setup(self.trigger_pin, GPIO.OUT)
GPIO.setup(self.echo_pin, GPIO.IN)
def get_distance(self) -> float:
GPIO.output(self.trigger_pin, True) # Fire ultrasound pulse
# Store initial time
pulse_sent = time.time()
pulse_received = time.time()
time.sleep(0.00001) # Wait for a very small time
GPIO.output(self.trigger_pin, False) # Stop firing the pulse
while GPIO.input(self.echo_pin) == 0: # Record the exact time the pulse was sent
pulse_sent = time.time()
while GPIO.input(self.echo_pin) == 1: # Record the exact time the pulse was received
pulse_received = time.time()
time_elapsed = pulse_received - pulse_sent # time difference between sending and receiving pulse
return (time_elapsed * self.SONIC_SPEED) / 2 # We divide by two because of the reflection of the wave
def print_distance(self, unit='cm') -> None:
if unit == 'm':
dist = self.get_distance()
print("%12s measured %0.3f m" % (self.name, dist))
else: # Unit is cm or not recognised
dist = self.get_distance() * 100.0
print("%12s measured %0.1f cm" % (self.name, dist))
if __name__ == '__main__':
try:
sensor1 = UltrasoundSensor(name="sensor1", trigger_pin=17, echo_pin=16)
sensor2 = UltrasoundSensor(name="sensor2", trigger_pin=27, echo_pin=20)
sensor3 = UltrasoundSensor(name="sensor3", trigger_pin=22, echo_pin=21)
while True:
sensor1.print_distance(unit='cm')
sensor2.print_distance(unit='cm')
sensor3.print_distance(unit='cm')
time.sleep(1)
except KeyboardInterrupt: # Exit by pressing CTRL + C
print("Measurement stopped by User")
finally: # Always clean up the pins
GPIO.cleanup()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment