...
A simple voltage divider circuit can be used to work with the ultrasonic sensors, the recommended resistor values are R1 = 1k Ω and R2 = 2k Ω .
How to use the sensor with raspberry pi?
Initialize the Raspberry pi and required libraries.
Code Block |
---|
import RPi.GPIO as GPIO
import time |
Initialize the Trigger and Echo pins (ex. TRIGGER = 16 , ECHO = 18).
Code Block |
---|
class UltrasonicInterface():
def __init__(self,trig,echo):
self.GPIO_TRIGGER = trig
self.GPIO_ECHO = echo |
Assign Raspberry pi pins to with the assigned number.
Code Block |
---|
def setup_ultrasonic(self):
GPIO.setup(self.GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(self.GPIO_ECHO, GPIO.IN) |
Get distance from ultrasonic sensors.
Code Block |
---|
def distance(self): GPIO.setmode(GPIO.BCM) # setting GPIO pins self.setup_ultrasonic() # set Trigger to HIGH GPIO.output(self.GPIO_TRIGGER, True) # set a small delay and change Trigger to LOW/False time.sleep(0.00001) GPIO.output(self.GPIO_TRIGGER, False) # get the start time StartTime = time.time() StopTime = time.time() while GPIO.input(self.GPIO_ECHO) == 0: StartTime = time.time() # get stop time while GPIO.input(self.GPIO_ECHO) == 1: StopTime = time.time() # time difference between start and arrival TimeElapsed = StopTime - StartTime # sound speed (34300 cm/s) distance = (TimeElapsed * 34300) / 2 GPIO.cleanup() return distance |
How to get data from the sensors?
Create an object.
Code Block |
---|
ultrasonic_object = UltrasonicInterface(16,18)
dist = ultrasonic_object.distance() |
Resources:
...