Lesson 2-1 · The Reflectance Sensor
Lesson 2-1 · The Reflectance Sensor
Teacher mode is on — the gray boxes are yours only. Flip the switch (bottom-right) to preview the student view.
In Module 1 the robot only ever did what you told it, step by step. Now it gets to sense the world. This lesson introduces the XRP's reflectance sensors — the "eyes" it uses to tell a white surface from a black line — and you'll record the readings you'll rely on for the rest of the module.
Learning Objectives
By the end of this lesson you will be able to:
- Explain how a reflectance sensor tells light surfaces from dark ones
- Read the left and right sensors with
get_left()andget_right() - Start
robot.py, the one program file you'll build on for the rest of the course, and write your first two functions in it - Interpret sensor values (roughly
0.0on white to1.0on black) - Pick a threshold that separates "on the line" from "off the line"
- Record calibration data for your own robot and tape
How the robot "sees" a line
Flip an XRP over and you'll find two small reflectance sensors underneath. Each one is a pair of parts sitting side by side: an LED that shines light down at the surface, and a phototransistor right next to it that measures how much of that light comes back.
Nothing in there measures color. The sensor only knows how much light came back, which is why anything dark reads like a line and anything light reads like the floor.
- White surface → most light bounces back → a low value (around
0.1–0.3). - Black line → light is absorbed → a high value (around
0.7–0.9).
The XRP has a left and a right sensor, each with its own reading — which is how the robot can tell which side of a line it's on.
Your sensor reads 0.8. What is it most likely over?
Read the sensors in Python
Reading a sensor is just importing its class and calling a method:
from XRPLib.reflectance import Reflectance
from XRPLib.board import Board
reflectance = Reflectance.get_default_reflectance()
board = Board.get_default_board()
board.wait_for_button()
left = reflectance.get_left()
right = reflectance.get_right()
print("Left sensor:", left)
print("Right sensor:", right)
Run it and you get two numbers. Then the program ends.
That's worth sitting with for a second, because it's the first thing that will
frustrate you. Those two get_left() and get_right() calls happen once, at
the instant you press the button — they are a snapshot, not a live feed. Python
reaches the bottom of the file and the program is over, so sliding the robot across
the tape afterwards changes nothing on screen. The numbers you're looking at are
from wherever the robot was sitting when you pressed the button, and they'll stay
that way until you press RUN again.
Which is a problem, because what you actually want to know is how the readings change as the robot moves. To see that, the reading has to happen over and over — so it goes in a loop. Before you write that loop, though, there's one new tool you'll need.
Pausing a program with time.sleep()
A loop with nothing slowing it down runs fast. Fifty sensor readings would print in a fraction of a second — long before you could move the robot — and then the loop would be over. You need the program to take a short breath between readings.
Python comes with a built-in module called time for exactly this. It isn't part
of XRPLib; it ships with Python itself (and with MicroPython, the version of Python
running on the XRP). Like any module, you bring it into your program with an
import at the top:
import time
That one line gives you access to everything in the module. The piece you want is
sleep(), and you reach it with a dot — time.sleep() means "the sleep
function that lives in the time module," the same way reflectance.get_left()
means "the get_left method that belongs to the reflectance sensor."
time.sleep() takes one number: how many seconds to pause. Whole numbers and
decimals both work:
time.sleep(1)— wait one secondtime.sleep(0.5)— wait half a secondtime.sleep(0.1)— wait a tenth of a second
While it's sleeping, your program simply stops at that line and does nothing until the time is up; then it carries on with the next line. (Anything already in motion keeps going, though — if the motors were running when the program went to sleep, they're still running.)
One file, for the rest of the course
The loop you're about to write is the first piece of code you'll keep. Until now
every lesson started a new program. From here on you have one file, and each
lesson adds to it: the sensor functions through this module, the driving functions,
grid driving in Module 3, and so on to the end. Create it now — call it robot.py —
and paste in this start:
from XRPLib.reflectance import Reflectance
from XRPLib.differential_drive import DifferentialDrive
from XRPLib.board import Board
import time
reflectance = Reflectance.get_default_reflectance()
drivetrain = DifferentialDrive.get_default_differential_drive()
board = Board.get_default_board()
# ===== RUN =====
board.wait_for_button()
# call ONE test function here
Two rules keep it working all year. New code goes above the RUN block, never
below it. Python runs a file top to bottom, so the run block has to be the last
thing, and everything it calls has to be defined above it. Each lesson gives you a
skeleton to paste in there: a banner comment naming the section, a few lines
saying what the section does, the settings it needs, the outlines of the functions
you're going to write, and a test function that exercises them. Then the one
line under RUN calls whichever test you're working on. One test at a time —
change the call, don't stack them. If you ever lose the file or join partway
through, the robot.py templates page has it as it stands after
every lesson, skeletons pasted and nothing written.
Your first two functions
Here is this lesson's skeleton. Paste it above RUN.
# ===== LINE SENSOR =====
# Reads the two reflectance sensors and answers questions
# about them. Starts here with the two raw readings; over this
# module it grows to answer "how far off the line am I?" and
# "am I on a line? on a cross?" Nothing in here drives.
# Everything that drives asks these functions instead of the
# hardware.
def get_left():
# return the left reflectance reading
pass
def get_right():
# return the right reflectance reading
pass
def test_sensors():
# prints both readings 50 times, a tenth of a second apart
for i in range(50):
print("Left:", get_left(), " Right:", get_right())
time.sleep(0.1)
get_left() and get_right() are one line each: they return the reading from
reflectance. You wrote functions with return in Lesson 1-11, and the only new
thing here is that these use reflectance without being handed it — it was created at
the top of the file, outside any function, so every function below can see it, the
same way polygon() used drivetrain in Module 1.
Where the returned value goes. Think of a function call as a question and return
as its answer. When test_sensors() reaches its print line, Python stops at
get_left(), runs your function, and the value after its return takes the place of
the call. By the time print runs, it is as if you had typed the number itself,
say 0.23, where get_left() was. Every program from here on
works that way: you ask get_left(), and you get a number back to print, compare or
do arithmetic with.
Two things with the same name. Your get_left() reads the sensor with
reflectance.get_left(), and that second one is not your function calling itself.
The reflectance. in front makes it the sensor's own method, the one you met above.
Yours is a plain function in your file that asks the sensor and passes its answer on.
If it prints None, the return is missing. A body that reads the sensor but
doesn't return the reading takes the reading and throws it away. A function that
ends without a return hands back None, which is Python's word for "nothing", so
test_sensors() prints Left: None Right: None however you move the robot. The
sensor is fine; the number just never left the function.
test_sensors() prints Left: None Right: None every time, even while you slide the robot across the tape. What is the most likely cause?
Why wrap one line in a function? Because from now on every program you write
asks for a sensor reading by this name, and only this one place knows how the
hardware is read. In six lessons these two will be the bottom of a toolkit of
functions, and they will not have changed. pass means "nothing here yet" — it holds
the place of the body so the file runs before you've written one; delete it when the
real line goes in.
Write the two bodies, set the run line to test_sensors(), and run. Same two
readings as before; they just happen fifty times now, a tenth of a second apart,
which gives you about five seconds to slide the robot across the tape and watch the
numbers follow it. That shift — from read it once to keep reading — is the whole
idea behind the while loop in the next lesson, where the robot reads its sensors for
as long as it's driving.
Activity · Calibrate and pick a threshold
Every surface and every roll of tape is a little different, so you calibrate —
measure your own values — instead of trusting a textbook number. Run
test_sensors() and record readings in three positions: both sensors on white, both
on the black line, and one on the edge.
Then pick a threshold halfway between your highest white reading and your lowest black reading. That's the number your programs will use to decide "on the line" vs. "off."
threshold = (highest white value + lowest black value) ÷ 2
Your 'off line' (white) values average 0.2 and your 'on line' (black) values average 0.8. What threshold should you choose?
Why does the XRP have two reflectance sensors instead of one?
Real-world connections
Reflectance sensing shows up all over the automated world:
Barcode scanners
Scanners read the pattern of light and dark bars exactly the way your sensor reads tape.
Line-following AGVs
Automated guided vehicles follow lines taped or painted on warehouse floors.
Ambient light sensors
Your phone dims its screen using the same idea — measuring reflected/available light.
Wrap-up
- Does a higher reading mean lighter or darker? (Darker — less light bounced back.)
- What is a threshold, and how do you pick one? (The cutoff between line and white; halfway between your calibrated values.)
- Why two sensors? (To tell which side of the line the robot is on.)