Adding collision detection capability to our robot
In this post we will be adding the capability of collision detection to our Raspberry PI based robot. A lot of the information that is shared here is derived from the following guide: https://circuitdigest.com/microcontroller-projects/raspberry-pi-obstacle-avoiding-robot
The data sheet of the sensor module that we are using is available here: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
We will be using the distance sensor APIs provided in the GPIO zero package https://gpiozero.readthedocs.io/en/stable/recipes.html#distance-sensor
While the VCC of 5V and GND can be shared with the existing circuit, we will need a couple of new GPIOs for the distance sensor. We need one line for the trigger and one line for the echo.
We are using GPIO17 (Trigger) and GPIO27(Echo)
from gpiozero import DistanceSensor from time import sleep sensor = DistanceSensor(17, 27) while True: print('Distance to nearest object is', sensor.distance, 'm') sleep(1)
========================= RESTART ========================= >>> %Run test_ultrasound_sensor.py Distance to nearest object is 0.447670080721598 m Distance to nearest object is 0.44841220883714866 m Distance to nearest object is 0.4475628119743078 m Distance to nearest object is 0.44842988673531864 m Distance to nearest object is 0.3191705281076008 m Distance to nearest object is 0.44960091821184506 m Distance to nearest object is 0.44661507110784215 m Distance to nearest object is 0.46784553048264 m Distance to nearest object is 0.44570337255045617 m
This is a fairly easy exercise. Since our ultrasonic distance sensor is only present in the front of the robot chassis, we add a check for the distance before executing the forward movement.
$ cat cgi-bin/forward.py #!/usr/bin/pythonRoot print "Content-type:text/html\n" ##print "<h1>This is the Home Page</h1>" import cgi,cgitb cgitb.enable() #for debugging from gpiozero import Robot from time import sleep from gpiozero import DistanceSensor sensor = DistanceSensor(17,27) if ( sensor.distance*100 < 20): print "Distance is less than 20 cm, cannot proceed with command\n" raise SystemExit robby = Robot (left=(6,13), right=(26,19)) robby.forward() sleep(.5) # for < ~1 ft distance robby.stop()
All the code is available in Bitbucket. Use the following command to download the repo:
git clone https://firstname.lastname@example.org/boseontherocks/projects_1.git
The code used in this post is available in the folder robot_3.
It also includes a test script for the ultrasound distance sensor.