Skip to content

ProgrammingPython on a Raspberry Pi

Decisions from Sensors

if, elif and else turn readings into actions; the order of the tests matters.

Not started Jump to practice

A sensor reading is just a number. A program turns that number into a choice.

Key idea

Use if, elif and else. Python checks the tests in order and runs only the first one that is true. Put narrow tests before broad ones.

Worked example: Order matters

if d < 50:
    action = 'slow'
elif d < 15:
    action = 'stop'
else:
    action = 'go'

What happens at d = 10?
  1. d < 50 is true, so action = 'slow'.
  2. The elif is never checked. The robot never stops!

Answer: 'slow'. Fix it by testing d < 15 first.

Worked example: Two sensors

A line follower has left and right sensors that read True on the line. Left True, right False: which way should it steer?
  1. The line is under the left sensor, so the line is to the left.
  2. Steer left to center it.

Answer: Left.

Why it works

Most robot behavior is a stack of decisions like these, run many times a second. Getting the order right is the difference between a robot that stops at the wall and one that hits it.

Common mistake

Writing an early, broad test that hides a later, narrow one. Test the most specific case first.

Hands-on: a night-light robot

Put a light sensor in a voltage divider on an analog pin. Print the reading every half second while you cover and uncover it. Pick a threshold halfway between dark and bright, and turn an LED on below it. Then add a second threshold for "very dark" and blink.

Practice

Pass with 3 right answers, the last 2 in a row. Each right answer earns 2 XP.

Loading practice…

Builds on

Leads to

Sources and further reading