5. API DI-Sensors - Basic

5.1. EasyDistanceSensor

class di_sensors.easy_distance_sensor.EasyDistanceSensor(port='I2C', use_mutex=False)[source]

Bases: di_sensors.distance_sensor.DistanceSensor

Class for the Distance Sensor device.

This class compared to DistanceSensor uses mutexes that allows a given object to be accessed simultaneously from multiple threads/processes. Apart from this difference, there may also be functions that are more user-friendly than the latter.

__init__(port='I2C', use_mutex=False)[source]

Creates a EasyDistanceSensor object which can be used for interfacing with a distance sensor.

Parameters
  • bus = "I2C" (string) – the bus for the sensor. For the GoPiGo3, options also include "GPG3_AD1" and "GPG3_AD2".

  • use_mutex = False (bool) – When using multiple threads/processes that access the same resource/device, mutexes should be enabled. Check the hardware specs for more information about the ports.

Raises

OSError – When the distance sensor is not connected to the designated bus/port, where in this case it must be "I2C". Most probably, this means the distance sensor is not connected at all.

To see where the ports are located on the GoPiGo3 robot, please take a look at the following diagram: Hardware Ports.

read_mm()[source]

Reads the distance in millimeters.

Returns

Distance from target in millimeters.

Return type

int

Note

  1. Sensor’s range is 5-2300 millimeters.

  2. When the values are out of the range, it returns 3000.

read()[source]

Reads the distance in centimeters.

Returns

Distance from target in centimeters.

Return type

int

Note

  1. Sensor’s range is 0-230 centimeters.

  2. When the values are out of the range, it returns 300.

read_inches()[source]

Reads the distance in inches.

Returns

Distance from target in inches.

Return type

float with one decimal

Note

  1. Sensor’s range is 0-90 inches.

  2. Anything that’s bigger than 90 inches is returned when the sensor can’t detect any target/surface.

5.2. EasyLightColorSensor

class di_sensors.easy_light_color_sensor.EasyLightColorSensor(port='I2C', led_state=False, use_mutex=False)[source]

Bases: di_sensors.light_color_sensor.LightColorSensor

Class for interfacing with the Light Color Sensor. This class compared to LightColorSensor uses mutexes that allows a given object to be accessed simultaneously from multiple threads/processes. Apart from this difference, there may also be functions that are more user-friendly than the latter.

known_colors = {'black': (0, 0, 0), 'blue': (0, 0, 255), 'cyan': (0, 255, 255), 'fuchsia': (255, 0, 255), 'green': (0, 255, 0), 'red': (255, 0, 0), 'white': (255, 255, 255), 'yellow': (255, 255, 0)}

The 8 colors that guess_color_hsv() method may return upon reading and interpreting a new set of color values.

__init__(port='I2C', led_state=False, use_mutex=False)[source]

Constructor for initializing a link to the Light Color Sensor.

Parameters
  • port = "I2C" (str) – The port to which the distance sensor is connected to. Can also be connected to ports "AD1" or "AD2" of the GoPiGo3. If you’re passing an invalid port, then the sensor resorts to an "I2C" connection. Check the hardware specs for more information about the ports.

  • led_state = False (bool) – The LED state. If it’s set to True, then the LED will turn on, otherwise the LED will stay off. By default, the LED is turned off.

  • use_mutex = False (bool) – When using multiple threads/processes that access the same resource/device, mutexes should be enabled.

Raises
  • OSError – When the Light Color Sensor is not reachable.

  • RuntimeError – When the chip ID is incorrect. This happens when we have a device pointing to the same address, but it’s not a Light Color Sensor.

translate_to_hsv(in_color)[source]

Standard algorithm to switch from one color system (RGB) to another (HSV).

Parameters

in_color (tuple(float,float,float)) – The RGB tuple list that gets translated to HSV system. The values of each element of the tuple is between 0 and 1.

Returns

The translated HSV tuple list. Returned values are H(0-360), S(0-100), V(0-100).

Return type

tuple(int, int, int)

Important

For finding out the differences between RGB (Red, Green, Blue) color scheme and HSV (Hue, Saturation, Value) please check out this link.

safe_raw_colors()[source]

Returns the color as read by the Light Color Sensor. The colors detected vary depending on the lighting conditions of the nearby environment.

Returns

The RGBA values from the sensor. RGBA = Red, Green, Blue, Alpha (or Clear). Range of each element is between 0 and 1. -1 means an error occured.

Return type

tuple(float,float,float,float)

safe_rgb()[source]

Detect the RGB color off of the Light Color Sensor.

Returns

The RGB color in 8-bit format.

Return type

tuple(int,int,int)

calibrate(color)[source]

Replace the HSV centroid for a given color with the sensor reading obtained from an example of that color in the current lighting environment <color> can be one of black | white | red | green | blue | yellow | cyan | fuschia

guess_color_hsv(in_color)[source]

Determines which color in_color parameter is closest to in the known_colors list. This method uses the euclidean algorithm for detecting the nearest center to it out of known_colors list. It does work exactly the same as KNN (K-Nearest-Neighbors) algorithm, where K = 1.

Parameters

in_color (tuple(float,float,float,float)) – A 4-element tuple list for the Red, Green, Blue and Alpha channels. The elements are all valued between 0 and 1.

Returns

The detected color in string format and then a 3-element tuple describing the color in RGB format. The values of the RGB tuple are between 0 and 1.

Return type

tuple(str,(float,float,float))

Important

For finding out the differences between RGB (Red, Green, Blue) color scheme and HSV (Hue, Saturation, Value) please check out this link.

5.3. EasyIMUSensor

class di_sensors.easy_inertial_measurement_unit.EasyIMUSensor(port='AD1', use_mutex=False)[source]

Bases: di_sensors.inertial_measurement_unit.InertialMeasurementUnit

Class for interfacing with the InertialMeasurementUnit Sensor.

This class compared to InertialMeasurementUnit uses mutexes that allows a given object to be accessed simultaneously from multiple threads/processes. Apart from this difference, there may also be functions that are more user-friendly than the latter.

__init__(port='AD1', use_mutex=False)[source]

Constructor for initializing link with the InertialMeasurementUnit Sensor.

Parameters
  • port = "AD1" (str) – The port to which the IMU sensor gets connected to. Can also be connected to port "AD2" of a GoPiGo3 robot or to any "I2C" port of any of our platforms. If you’re passing an invalid port, then the sensor resorts to an "I2C" connection. Check the hardware specs for more information about the ports.

  • use_mutex = False (bool) – When using multiple threads/processes that access the same resource/device, mutexes should be enabled.

Raises
reconfig_bus()[source]

Use this method when the InertialMeasurementUnit Sensor becomes unresponsive but it’s still plugged into the board. There will be times when due to improper electrical contacts, the link between the sensor and the board gets disrupted - using this method restablishes the connection.

Note

Sometimes the sensor won’t work just by calling this method - in this case, switching the port will do the job. This is something that happens very rarely, so there’s no need to worry much about this scenario.

safe_calibrate()[source]

Once called, the method returns when the magnetometer of the InertialMeasurementUnit Sensor gets fully calibrated. Rotate the sensor in the air to help the sensor calibrate faster.

Note

Also, this method is not used to trigger the process of calibrating the sensor (the IMU does that automatically), but its purpose is to block a given script until the sensor reports it has fully calibrated.

If you wish to block your code until the sensor calibrates and still have control over your script, use safe_calibration_status() method along with a while loop to continuously check it.

safe_calibration_status()[source]

Returns the calibration level of the magnetometer of the InertialMeasurementUnit Sensor.

Returns

Calibration level of the magnetometer. Range is 0-3 and -1 is returned when the sensor can’t be accessed.

Return type

int

convert_heading(in_heading)[source]

This method takes in a heading in degrees and return the name of the corresponding heading. :param float in_heading: the value in degree that needs to be converted to a string.

Returns

The heading of the sensor as a string.

Return type

str

The possible strings that can be returned are: "North", "North East", "East", "South East", "South", "South West", "West", "North West", "North".

Note

First use safe_calibrate() or safe_calibration_status() methods to determine if the magnetometer sensor is fully calibrated.

safe_read_euler()[source]

Read the absolute orientation.

Returns

Tuple of euler angles in degrees of heading, roll and pitch.

Return type

(float,float,float)

Raises

OSError – When the sensor is not reachable.

safe_read_accelerometer()[source]

Read the acceleration in 3 axes.

Returns

Tuple of x,y,z axes.

Return type

(float,float,float)

Raises

OSError – When the sensor is not reachable.

safe_read_magnetometer()[source]

Read the magnetometer values.

Returns

Tuple containing X, Y, Z values in micro-Teslas units. You can check the X, Y, Z axes on the sensor itself.

Return type

(float,float,float)

Note

In case of an exception occurring within this method, a tuple of 3 elements where all values are set to 0 is returned.

safe_read_gyroscope()[source]

Read the angular velocity of the gyroscope.

Returns

The angular velocity as a tuple of X, Y, Z values in degrees/s. You can check the X, Y, Z axes on the sensor itself.

Return type

(float,float,float)

Note

In case of an exception occurring within this method, a tuple of 3 elements where all values are set to 0 is returned.

safe_north_point()[source]

Determines the heading of the north point. This function doesn’t take into account the declination.

Returns

The heading of the north point measured in degrees. The north point is found at 0 degrees.

Return type

int

Note

In case of an exception occurring within this method, 0 is returned.

5.4. EasyTHPSsensor

class di_sensors.easy_temp_hum_press.EasyTHPSensor(port='I2C', use_mutex=False)[source]

Bases: di_sensors.temp_hum_press.TempHumPress

Class for interfacing with the Temperature Humidity Pressure Sensor.

This class compared to TempHumPress uses mutexes that allows a given object to be accessed simultaneously from multiple threads/processes. Apart from this difference, there may also be functions that are more user-friendly than the latter.

__init__(port='I2C', use_mutex=False)[source]

Constructor for initializing link with the Temperature Humidity Pressure Sensor.

Parameters
  • port = "I2C" (str) – The port to which the THP sensor is connected to. Can also be connected to ports "AD1" or "AD2" of the GoPiGo3. If you’re passing an invalid port, then the sensor resorts to an "I2C" connection. Check the hardware specs for more information about the ports.

  • use_mutex = False (bool) – When using multiple threads/processes that access the same resource/device, mutexes should be enabled.

Raises

OSError – When the sensor cannot be reached.

safe_celsius()[source]

Read temperature in Celsius degrees.

Returns

Temperature in Celsius degrees.

Return type

float

Raises

OSError – When the sensor cannot be reached.

safe_fahrenheit()[source]

Read temperature in Fahrenheit degrees.

Returns

Temperature in Fahrenheit degrees.

Return type

float

Raises

OSError – When the sensor cannot be reached.

safe_pressure()[source]

Read the air pressure in pascals.

Returns

The air pressure in pascals.

Return type

float

Raises

OSError – When the sensor cannot be reached.

safe_humidity()[source]

Read the relative humidity as a percentage.

Returns

Percentage of the relative humidity.

Return type

float

Raises

OSError – When the sensor cannot be reached.

5.5. EasyLineFollower

class di_sensors.easy_line_follower.EasyLineFollower(port='I2C', sensor_id=-1, calib_dir='/home/pi/Dexter/', white_file='white_line.txt', black_file='black_line.txt', use_mutex=True)[source]

Bases: object

Higher-level of abstraction class for either the LineFollower or LineFollowerRed.

__init__(port='I2C', sensor_id=-1, calib_dir='/home/pi/Dexter/', white_file='white_line.txt', black_file='black_line.txt', use_mutex=True)[source]

Initialize a class to interface with either the LineFollower or the LineFollowerRed.

Parameters
  • port = "I2C" (str) – The port to which the line follower is connected. The "I2C" port corresponds to "RPI_1SW" bus. Can also choose port "AD1"/"AD2" only if it’s connected to the GoPiGo3 and the line follower sensor (black board) is used. To find out more, check the hardware specs for more information about the ports.

  • sensor_id = -1 (int) – -1 to automatically detect the connected line follower - this is the default value. It can also set to 1 to only use it with the line follower (red board) (LineFollowerRed) or to 2 for the line follower (black board) (LineFollower) 1.

  • calib_dir = "/home/pi/Dexter/" (str) – Directory where the calibration files are saved. It already has a default value set.

  • white_file = "white_line.txt" (str) – The name of the calibration file for the white line.

  • black_file = "black_line.txt" (str) – The name of the calibration file for the black line.

  • use_mutex = True (bool) – Whether to use a mutex on the sensor or not. Recommended when the same sensor is called from multiple threads/processes. It’s meant for the I2C line and does not protect the file I/O in multi-threaded applications.

Upon instantiating an object of this class, after detecting the line follower, the calibration values are read and if they are not compatible with those required for the given line follower, default/generic calibration values will be set for both colors computed by taking the average of the 2 extremes.

Important to keep in mind is that both line followers’ calibration files are incompatible, because one uses 5 sensors and the other one 6 - there are also, more factors to consider, such as the kind of sensors used in the line follower, but for the most part, the incompatibility comes from the different number of sensors.

1

To see what module has been detected, check _sensor_id attribute. If it’s set to 0, then no line follower has been detected.

set_calibration(color, inplace=True)[source]

Calibrate the sensor for the given color and save the values to file.

Parameters
  • color (str) – Either "white" for calibrating white or "black" for black.

  • inplace = True (bool) – Apply the calibration values to this instantiated object too. Use white_calibration and black_calibration attributes to access the calibration values.

get_calibration(color, inplace=True)[source]

Read the calibration values from the disk for the given color.

Parameters
  • color (str) – Either "white" for reading the calibration values for white or "black" for black.

  • inplace = True (bool) – Apply the read values to this instantiated object too. Use white_calibration black_calibration to access the calibration values.

Return type

5/6-element list depending on which line follower is used.

Returns

The calibrated values for the given color.

Raises

ValueError – When the read file is incompatible with what the line follower expects. This can happen if a line follower has been calibrated and then switched with another one of a different type (like going from the black -> red board or vice-versa).

read(representation='raw')[source]

Read the sensors’ values from either line follower.

Parameters

representation="raw" (str) – It’s set by-default to "raw" , but it can also be "bivariate", "bivariate-str" or "weighted-avg".

Raises

OSError – If the line follower sensor is not reachable.

Each of the line followers’ order of the sensors’ values is the same as the one in each read method of them both: di_sensors.line_follower.LineFollower.read_sensors() and di_sensors.line_follower.LineFollowerRed.read_sensors().

For representation="raw"

For this, raw values are returned from the line follower sensor. Values range between 0 and 1 and there can be 5 or 6 values returned depending on what line follower sensor is used.

For representation="bivariate"

In this case, a list with the length equal to the number of sensors present on the given line follower is returned. Values are either 0 (for black) or 1 (for white). In order to get good results, make sure the line follower is properly calibrated.

For representation="bivariate-str"

Same as "bivariate" except that 0 is replaced with letter b (for black) and 1 with w (for white).

For representation="weighted-avg"

Returns a 2-element tuple. The first element is an estimated position of the line.

The estimate is computed using a weighted average of each sensor value (regardless of which line follower sensor is used), so that if the black line is on the left of the line follower, the returned value will be in the 0.0-0.5 range and if it’s on the right, it’s in the 0.5-1.0 range, thus making 0.5 the center point of the black line. Keep in mind that the sensor’s orientation is determined by the order of the returned sensor values and not by how the sensor is positioned on the robot. Check read_sensors() and read_sensors() methods to see how the values are returned.

If the line follower sensor ends up on a surface with an homogeneous color (or shade of grey), the returned value will circle around 0.5.

The 2nd element is an integer taking 3 values: 1 if the line follower only detects black, 2 if it only detects white and 0 for the rest of cases.

position_01()[source]

Same as calling read() method like read("bivariate").

Return type

list(int)

Returns

A list of 0s and 1s for each sensor of the line follower.

Raises

Check read().

position_bw()[source]

Same as calling read() method like read("bivariate-str").

Return type

str

Returns

A string with a bunch of "w" (for white) and "b" (for black) representing the detected color on each sensor.

Raises

Check read().

position()[source]

Returns a string telling to which side the black line that we’re following is located.

Returns

String that’s indicating the location of the black line.

Return type

str

Raises

Check read().

Important

It is assumed that with this method, the line follower is properly oriented on the GoPiGo. For the red line follower, when looking forward, the left marking on the board is on the left and vice-versa for the right marking. As for the black line follower, the wiggly white arrow on the board is pointed forward.

The strings this method can return are the following:
  • "center" - when the line is found in the middle.

  • "black" - when the line follower sensor only detects black surfaces.

  • "white" - when the line follower sensor only detects white surfaces.

  • "left" - when the black line is located on the left of the sensor.

  • "right" - when the black line is located on the right of the sensor.

position_val()[source]

Same as calling read() method like read("weighted-avg").

Return type

int

Returns

Range is between 0 and 30. When following a line the values will be between 0 and 10. For values smaller than 5, the black line is on the left of the robot, and for values bigger than 5 but no more than 10 the line is to the right. 5 suggests the black line is in the middle. It can also return 20 if it’s all black, or 30 for all white.

Raises

Check read().

Warning

The Line Follower class was originally held in easysensors module of the GoPiGo3 library, but has been moved here. The easygopigo3.EasyGoPiGo3.init_line_follower() method now returns an object of the EasyLineFollower class instead of instantiating the original Line Follower class from easysensors module.

In order to prevent breaking others’ code, we kept the support for the older methods that are soon-to-be-deprecated in EasyLineFollower class. The mapping between the old methods and the new ones is as follows:

  1. read_raw_sensors() <=> read()

  2. read_binary() <=> position_01()

  3. read_position() <=> position()

  4. read_position_str() <=> position_bw()

  5. get_white_calibration() <=> set_calibration() ("white")

  6. get_black_calibration() <=> set_calibration() ("black")