Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 7 Next »

The BenchBot is equipped with 8 ultrasonic sensors that cover a range of 360 degrees of the system. These sensors are used in the feedback of the BenchBot, as an obstacle avoidance algorithm.

The bot currently is equipped with HCSRF04 ultrasonic sensors, that have a range from 2 cm to 300 cm. The sensor has a resolution of 0.3 cm and works on +5V DC. The data-sheet for the ultrasonic sensors can be found here

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.

import RPi.GPIO as GPIO
import time

Initialize the Trigger and Echo pins (ex. TRIGGER = 16 , ECHO = 18).

class UltrasonicInterface():

        def __init__(self,trig,echo):
                
                self.GPIO_TRIGGER = trig
                self.GPIO_ECHO = echo

Assign Raspberry pi pins to with the assigned number.

def setup_ultrasonic(self):
        
        GPIO.setup(self.GPIO_TRIGGER, GPIO.OUT)
        GPIO.setup(self.GPIO_ECHO, GPIO.IN)

Get distance from ultrasonic sensors.

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
        start_time = time.time()
        stop_time = time.time()
     
        while GPIO.input(self.GPIO_ECHO) == 0:
            start_time = time.time()
     
        # get stop time
        while GPIO.input(self.GPIO_ECHO) == 1:
            stop_time = time.time()
     
        # time difference between start and arrival
        time_occured = stop_time - start_time

        # sound speed (34300 cm/s)
        distance = (time_occured * 34300) / 2
        GPIO.cleanup()
        return distance

How to get data from the sensors?

Create an Ultrasonic Interface object and pass in the TRIG and ECHO pins as arguments.

ultrasonic_object = UltrasonicInterface(16,18)
dist = ultrasonic_object.distance()

Resources:

[1]. https://thepihut.com/blogs/raspberry-pi-tutorials/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi

  • No labels