Lists of readings
Lists, len, min and max, slices and looping over the 64 readings of the depth grid.
Do this lesson in the simulatorPrint it: worksheet (PDF) · answers (PDF) · as a web page
distance() is one number: what is straight ahead. The robot's depth sensor sees far more than that, and it hands it over as a list.
A list
from bugbot import *
connect()
# a list is several values in one name, in order
speeds = [20, 40, 60]
print(speeds)
print("the first one is", speeds[0])
print("how many:", len(speeds))
Counting starts at 0, so speeds[0] is the first and speeds[2] is the last of three. len() says how many there are.
The depth grid
from bugbot import *
connect()
grid = tof_grid()
print("readings:", len(grid))
print("nearest thing:", round(min(grid), 1), "cm")
print("furthest:", round(max(grid), 1), "cm")
tof_grid() gives 64 readings: an 8 by 8 square of distances in whole centimetres, left to right, top to bottom. min() and max() pick out the smallest and largest of any list.
With nothing on the mat this says the nearest is 8 cm and the furthest 400 cm. The sensor's bottom rows look down at the mat just in front of the robot, so they always see something close. The top rows look up over everything, and 400 is the most it ever reports: it means nothing there.
Going through a list
from bugbot import *
connect()
grid = tof_grid()
# row 3 (the fourth row), which looks straight ahead
row = grid[24:32]
for value in row:
print(round(value, 1))
for value in row: runs the indented lines once for each reading, with value being that reading. grid[24:32] is a slice: the readings from 24 up to but not including 32. On the empty mat they run 85, 83, 81, 81, 81, 81, 83, 85: the edge of the mat ahead, a little further away at the sides because those readings look across at an angle.
Counting how many readings meet a test is the same pattern with an if inside.
from bugbot import *
connect()
close = 0
for value in tof_grid():
if value < 40:
close = close + 1
print(close, "of the 64 readings are under 40 cm")
On the empty mat that prints 32: the four bottom rows, all looking at the mat.
Task: how near is the nearest
There is a box on the mat in front of the robot. Print one line saying how far away it is, like nearest: 27, worked out with min() from tof_grid() rather than from distance(). The smallest of all 64 readings is the mat under the robot's nose, 8 cm, so only look at the rows that see straight ahead.
from bugbot import *
connect()
grid = tof_grid()
# your line here
Challenges
- Print the furthest reading as well, on its own line.
- Print how many readings are under 30 cm.
- Turn the robot 45 degrees, take the readings again, and see which way is clearest.
Where next
That is the Python this club needs. Module 1 starts on the robot itself: driving well, driving exactly, and why it never goes quite straight.