Lesson 8 of 9 ยท about 30 minutes
A sketch is a small program that becomes a new colour in the robot's menu. Read one, then write a scaredy cat that backs away when something comes close.
def run(alvik):
readings = alvik.get_distance() # cm, or None if a sensor has no reading yet
readings = [SEE_CM + 1 if d is None else d for d in readings]
closest = min(readings)
where = readings.index(closest) # 0 = far left ... 2 = middle ... 4 = far right
if closest > SEE_CM:
lights(alvik, WAITING)
alvik.brake()
else:
lights(alvik, FOLLOWING)
speed = max(-MAX_SPEED, min(MAX_SPEED, closest - NEAR_CM)) # too far: forward, too close: back up
turn = (2 - where) * TURN # positive = turn left
alvik.drive(speed, turn)
sleep_ms(50)
return 1
Find the closest reading, turn toward it, and drive forward or back to keep a set distance.
alvik.drive(speed, turn) takes cm/s (negative = backwards) and degrees per second (positive = left).
A sketch is a folder with a program (scaredy_cat.py, with a run(alvik)
function), a label (sketch.json) and a README.md.
The menu calls run(alvik) over and over until โ. So do one small step each time;
never loop forever inside it. If it crashes, the lights flash red and the menu comes back.
Make a folder scaredy_cat with these two files.
scaredy_cat.py
from time import sleep_ms
TOO_CLOSE_CM = 15 # closer than this is scary
BACK_SPEED = 8 # cm/s
CALM = (0, 1, 0)
SCARED = (1, 0, 0)
def lights(alvik, rgb):
alvik.left_led.set_color(*rgb)
alvik.right_led.set_color(*rgb)
def run(alvik):
middle = alvik.get_distance()[2] # cm to whatever is straight ahead, or None for nothing
if middle is not None and middle < TOO_CLOSE_CM:
lights(alvik, SCARED)
alvik.drive(-BACK_SPEED, 0) # backwards, without turning
else:
lights(alvik, CALM)
alvik.brake()
sleep_ms(50)
sketch.json
{
"title": "Scaredy cat",
"emoji": "๐",
"description": "Sits still until something comes close, then backs away from it.",
"color": [0, 1, 1],
"hardware": ["distance sensors", "wheels", "lights"],
"entry": "scaredy_cat"
}
[0, 1, 1] is cyan. "entry" is the .py file's name.
It must end up at /sketches/scaredy_cat/ on the robot:
sketches/scaredy_cat on the robot, save both files there, restart.mpremote fs mkdir :sketches
mpremote fs cp -r scaredy_cat :sketches/ + resetThen pick cyan, โ, and bring your hand to its nose.
TOO_CLOSE_CM to 20 on an empty floor. Why does it back away? (Lesson 5.)alvik.drive(0, 90).Useful commands: drive, brake, get_distance,
get_line_sensors, get_color, left_led.set_color,
get_touch_ok. Full list: Arduino's Alvik guide.
Sharing rules: the README.