Lists of readings
Lists, len, min and max, slices and looping over the 64 readings of the depth grid.
Do this lesson in the simulatordistance() 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, left to right, top to bottom. min() and max() pick out the smallest and largest of any list.
Going through a list
from bugbot import *
connect()
grid = tof_grid()
# the middle row of the eight
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.
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")
Task: how near is the nearest
Print one line saying how far away the nearest thing is, like nearest: 27.4, worked out from tof_grid() rather than from distance().
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.