Learn 2: Build and Calibrate
5. Testing the sensors
Let’s write some basic code to test that everything is set up correctly and works as expected and also learn a little about using the color sensor. To do this, we will write a couple of simple functions that we will trigger from button presses in the Interactive Control Code cell.
- Create a new code cell immediately below the Sensor Setup Code cell.
- Type the following function definition code into this cell.
- Declare these functions by clicking on Run Selected Cell in the notebook menu.
def test_line_follower():
global line_follower
print(f"POSITION OF LINE = {line_follower.position()}")
def test_color_sensor():
global color_sensor
(red, green, blue, clear) = color_sensor.safe_raw_colors()
print(f"R={red:.2f}, G={green:.2f}, B={blue:.2f}, C={clear:.2f}")
We have used function calls like these before when testing the line follower in the Robot Operations Manager mission. To recap, all we are doing here is reading sensor values and writing them into our notebook. The use of f-strings allows you to place function calls and variables directly inside the string so their values can be printed as part of the string.
We’ll skip over the line follower test function as you should be familiar with that from the previous mission.
Let’s look at the color sensor test function. The safe_raw_colors()
function is a color sensor class library function. This reads the sensor and returns a list of values, in the range 0-1, that tell us how red, green, blue and clear (intense) the color is that the color sensor is facing. The higher the number, the more pronounced that color or intensity is.
We read the sensor values into a set of variables and then write those variables into the notebook.
The :.2f
after every variable is simply a formatting instruction that says “print this value as a float to 2 decimal places”.