3.6. Measuring Distance

3.6.1. Our goal

In this tutorial, we are using a Distance Sensor for measuring the distance to a target with the GoPiGo3 robot. We are going to print the values on a terminal.

3.6.2. The code we analyse

The code we’re analyzing in this tutorial is the following one.

# import the GoPiGo3 drivers
import time
import easygopigo3 as easy

# This example shows how to read values from the Distance Sensor

# Create an instance of the GoPiGo3 class.
# GPG will be the GoPiGo3 object.
gpg = easy.EasyGoPiGo3()

# Create an instance of the Distance Sensor class.
# I2C1 and I2C2 are just labels used for identifyng the port on the GoPiGo3 board.
# But technically, I2C1 and I2C2 are the same thing, so we don't have to pass any port to the constructor.
my_distance_sensor = gpg.init_distance_sensor()

while True:
    # Directly print the values of the sensor.
    print("Distance Sensor Reading (mm): " + str(my_distance_sensor.read_mm()))

The source code for this example program can be found here on github.

3.6.3. The modules

Start by importing 2 important modules:

import time
import easygopigo3 as easy

The easygopigo3 module is used for interacting with the GoPiGo3 robot, whilst the time module is generally used for delaying actions, commands, setting timers etc.

3.6.4. The objects

For interfacing with the Distance Sensor we need to instantiate an object of the easygopigo3.EasyGoPiGo3 class so in return, we can instantiate an object of the di_sensors.easy_distance_sensor.EasyDistanceSensor class. We do it like in the following code snippet.

gpg = easy.EasyGoPiGo3() # this is an EasyGoPiGo3 object
my_distance_sensor = gpg.init_distance_sensor() # this is a DistanceSensor object

Important

Notice that in order for this to work, we also need to have the DI-Sensors library installed. Follow the instructions on that documentation on how to install the required package.

3.6.5. Main part

There’s a single while loop in the entire script. The loop is for printing the values that we’re reading repeatedly. We will be using the read_mm() method for reading the distance in millimeters to the target.

while True:

    # Directly print the values of the sensor.
    print("Distance Sensor Reading (mm): " + str(my_distance_sensor.read_mm()))

See also

Check out di_sensors.easy_distance_sensor.EasyDistanceSensor’s API for more details.

3.6.6. Running it

Connect the Distance Sensor to any of the 2 "I2C" ports on the GoPiGo3 robot. After the sensor is connected, on your Raspberry Pi, open up a terminal and type in the following 2 commands.

cd ~/Desktop/GoPiGo3/Software/Python/Examples
python easy_Distance_Sensor.py
../_images/dist_sensor.gif

Note

See the following graphical representation as a reference to where the ports are.