๐Ÿ“š Alvik lessons

Lesson 8 of 9 ยท about 30 minutes

๐Ÿ™€ Teach it a trick

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.

๐Ÿงฐ You need

โ–ถ๏ธ Read one first

  1. On the ๐Ÿ”ง Update the robot page, add ๐Ÿ• Follow me and update.
  2. Pick yellow, press โœ“, and lead it with your hand.
  3. Here is the whole program:
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).

๐Ÿ” How a sketch works

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.

โœ๏ธ Write the scaredy cat

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.

Put it on the robot

It must end up at /sketches/scaredy_cat/ on the robot:

Then pick cyan, โœ“, and bring your hand to its nose.

๐Ÿงช Try this

โœ๏ธ Make your own

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.