本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
10Sensors, Actuators and Control Programs
The town hall’s lift carries people between three floors many times a day. Nobody watches it, and yet it never moves with its door open, not once in years. That is not luck, and not the care of a person: a small program decides, many times a second, what the motor and the door may do, and it was written so that the dangerous combination cannot happen.
Such programs run in lifts, washing machines, cars, traffic lights and heating systems. They read measurements, decide, and act, for ever. This chapter writes three of them, a thermostat, a traffic light and a lift, against simulated devices, and then proves something about the lift by checking every case.
You already know
A measured signal becomes a list of numbers by sampling and quantisation (the chapter on images and sound). A while loop repeats its body as long as its condition holds (Book 1, grade 6).
10.1 A computer inside an object
Definition 10.1 (Embedded system)
An embedded system is a computer built into an object to control it: it has no keyboard or screen of its own, or only small ones, and it runs one program from the moment the object is switched on.
Definition 10.2 (Sensor, actuator)
A sensor measures a quantity of the world (a temperature, a position, a press on a button) and gives it to the computer as a number. An actuator turns a decision of the computer into an action on the world (a motor, a heater, a lamp, a lock).
Definition 10.3 (Control loop)
A control loop is the loop that an embedded program repeats for as long as the object runs: read the sensors, decide, command the actuators, wait until the next period.
10.2 Measured values turned into numbers
The simulated thermometer of the chapter gives a whole number from to , on bits, where means °C and means °C. Turning it into degrees takes an offset and a scale.
LOW, HIGH, LEVELS = -20.0, 60.0, 1024 # the sensor's range, on 10 bits
def to_celsius(raw):
"""Turn a reading 0..1023 into degrees: an offset and a scale."""
return LOW + raw * (HIGH - LOW) / (LEVELS - 1)
if __name__ == "__main__":
for raw in (0, 255, 511, 512, 1023):
print(f"raw {raw:4} -> {to_celsius(raw):7.3f} degrees")
print("one step is", round((HIGH - LOW) / (LEVELS - 1), 4), "degrees")
$ python convert.py
raw 0 -> -20.000 degrees
raw 255 -> -0.059 degrees
raw 511 -> 19.961 degrees
raw 512 -> 20.039 degrees
raw 1023 -> 60.000 degrees
one step is 0.0782 degrees
A real measurement also wobbles from one reading to the next: electrical noise, air moving past the sensor. The simulated sensor adds a random error of about degree. Averaging the last few readings smooths it out, at the price of reacting a little later.
import random
from convert import to_celsius
from sensor import to_raw
rng = random.Random(10)
values = [to_celsius(to_raw(20.0, rng)) for _ in range(30)] # the true value is 20.0
def moving_average(xs, width):
"""The mean of each window of `width` consecutive values."""
return [sum(xs[i - width + 1:i + 1]) / width for i in range(width - 1, len(xs))]
smooth = moving_average(values, 5)
print("raw: ", [round(v, 1) for v in values[:8]])
print("smoothed:", [round(v, 1) for v in smooth[:8]])
print("spread raw", round(max(values) - min(values), 2),
" smoothed", round(max(smooth) - min(smooth), 2))
$ python smooth.py
raw: [19.7, 19.9, 19.8, 19.9, 20.2, 19.5, 19.9, 19.9]
smoothed: [19.9, 19.9, 19.9, 19.9, 19.8, 19.8, 19.9, 20.1]
spread raw 1.33 smoothed 0.48
The simplest thermostat switches the heater on below the target and off above it. With noisy readings near the target, it flips the heater on and off at every reading, which wears the switch out.
Definition 10.4 (Hysteresis)
A controller with hysteresis uses two thresholds instead of one: it switches on below the lower one and off above the higher one, and between them it keeps its current state. The gap between the two thresholds is the band.
import random
from convert import to_celsius
from sensor import room
TARGET = 20.0
def plain(raw, heater):
"""On below the target, off above it."""
return to_celsius(raw) < TARGET
def hysteresis(raw, heater, half_band=0.5):
"""On below target - half_band, off above target + half_band; else keep it."""
t = to_celsius(raw)
if t < TARGET - half_band:
return True
if t > TARGET + half_band:
return False
return heater
if __name__ == "__main__":
for name, controller in (("plain", plain), ("hysteresis", hysteresis)):
trace = room(360, controller, random.Random(4))
switches = sum(1 for a, b in zip(trace, trace[1:]) if a[1] != b[1])
late = [t for t, _ in trace[120:]]
print(f"{name:10}: {switches:3} switches in 6 hours,"
f" temperature {min(late):.2f} to {max(late):.2f}")
$ python thermostat.py
plain : 214 switches in 6 hours, temperature 19.39 to 20.57
hysteresis: 77 switches in 6 hours, temperature 18.92 to 20.86
The function room of the chapter’s sensor.py simulates the room minute by minute: it loses heat towards the °C outside, gains heat when the heater is on, and asks the controller each minute what to do with a fresh noisy reading.
10.3 A controller as a state machine
A thermostat has two states, heating or not. A traffic light or a lift has more, and what it does with an event, a button pressed, a floor reached, depends on the state it is in.
Definition 10.5 (State machine)
A state machine is made of a set of states, one of which is the current one, a set of events, and transitions: for a state and an event, the next state. The machine starts in an initial state, and each event moves it along one transition.
A transition table is a dictionary from (state, event) to the next state. Here is the light that the cars see at a pedestrian crossing: a press on the button does not stop the cars at once, it schedules a red light.
# A pedestrian crossing: the cars' light, and a button for pedestrians.
TABLE = {
("green", "tick"): "green", # cars keep going
("green", "button"): "green wait", # a pedestrian asked
("green wait", "tick"): "amber",
("green wait", "button"): "green wait",
("amber", "tick"): "red",
("amber", "button"): "amber",
("red", "tick"): "green", # pedestrians crossed
("red", "button"): "red",
}
CARS_MAY_GO = {"green", "green wait", "amber"}
state = "green"
for event in ["tick", "button", "button", "tick", "tick", "tick", "tick"]:
new = TABLE[(state, event)]
cars = "go" if new in CARS_MAY_GO else "stop"
print(f"{state:10} --{event:6}--> {new:10} cars {cars}")
state = new
$ python traffic_light.py
green --tick --> green cars go
green --button--> green wait cars go
green wait --button--> green wait cars go
green wait --tick --> amber cars go
amber --tick --> red cars stop
red --tick --> green cars go
green --tick --> green cars go
Method 10.6 (Writing a controller as a state machine)
- List the states, and say what each actuator does in each of them.
- List the events: readings that cross a threshold, buttons, timers.
- For every pair (state, event), decide the next state, including “no change”; a table must have no hole.
- Write the property that must never fail, as a test on a state, and check it on every state the machine can reach.
10.4 The lift
The lift of the town hall serves floors , and . Its state is a tuple: the floor, the door (open or closed), the motor (stopped, going up, going down) and the floor it is going to. Its events are a call to a floor, a request to open or close the door, and the signal arrive that a sensor in the shaft sends when the cabin reaches a floor. The rules are written as a function instead of a table: there are many states, but few kinds of rules.
def step(state, event):
"""The next state of the lift; an event that does not apply changes nothing."""
floor, door, motor, target = state
if event == "close" and door == "open":
return (floor, "closed", motor, target)
if event == "open" and motor == "stop":
return (floor, "open", motor, target)
if event.startswith("call") and door == "closed" and motor == "stop":
k = int(event[4:])
if k == floor:
return (floor, "open", "stop", None)
return (floor, "closed", "up" if k > floor else "down", k)
if event == "arrive" and motor != "stop":
floor += 1 if motor == "up" else -1
if floor == target:
return (floor, "open", "stop", None) # stop first, then open
return (floor, door, motor, target)
return state
def safe(state):
floor, door, motor, target = state
return not (door == "open" and motor != "stop")
if __name__ == "__main__":
state = (0, "open", "stop", None)
events = ["call2", "close", "call2", "arrive", "open", "arrive", "close", "call0"]
for event in events:
state = step(state, event)
print(f"{event:7} -> floor {state[0]}, door {state[1]:6}, motor {state[2]:4}"
f" safe: {safe(state)}")
$ python lift.py
call2 -> floor 0, door open , motor stop safe: True
close -> floor 0, door closed, motor stop safe: True
call2 -> floor 0, door closed, motor up safe: True
arrive -> floor 1, door closed, motor up safe: True
open -> floor 1, door closed, motor up safe: True
arrive -> floor 2, door open , motor stop safe: True
close -> floor 2, door closed, motor stop safe: True
call0 -> floor 2, door closed, motor down safe: True
A person does not send events by hand; a panel of buttons does. A small text interface plays the panel: it reads a command, checks it, sends the event and shows the new state.
from lift import safe, step
state = (0, "closed", "stop", None)
print("Commands: call0 call1 call2 open close arrive quit")
while True:
command = input("lift> ").strip()
if command == "quit":
break
if command not in {"call0", "call1", "call2", "open", "close", "arrive"}:
print(" unknown command:", command)
continue
state = step(state, command)
floor, door, motor, target = state
print(f" floor {floor}, door {door}, motor {motor}, going to {target}")
assert safe(state)
$ python lift_menu.py
Commands: call0 call1 call2 open close arrive quit
lift> call2
floor 0, door closed, motor up, going to 2
lift> arrive
floor 1, door closed, motor up, going to 2
lift> open
floor 1, door closed, motor up, going to 2
lift> arrive
floor 2, door open, motor stop, going to None
lift> close
floor 2, door closed, motor stop, going to None
lift> jump
unknown command: jump
lift> call0
floor 2, door closed, motor down, going to 0
lift> arrive
floor 1, door closed, motor down, going to 0
lift> arrive
floor 0, door open, motor stop, going to None
lift> quit
Checking the states of a few sessions shows that the lift was safe in those sessions. To be sure for every session, the weekend problem checks every state the lift can ever reach: there are few of them, so all can be listed.
Safe use
Never test a control program on the real device first. Simulate it, check its states, then try it on the device with the power limited and a person at the emergency switch. Real lifts, machines and vehicles also have safety devices that do not depend on the program: a door contact that cuts the motor’s power whatever the computer says.
10.5 Exercises
Exercise 10.1 ★
The sensor reads , then . Convert both to degrees. Which reading corresponds to °C most closely?
Solution
Solution of Exercise 10.1.
°C and °C. °C would be : the reading ( °C) is closest, nearer than ( °C).
Exercise 10.2 ★
In the traffic light’s table, what is the next state of amber on button, and of red on tick? Starting from green, which events lead to red fastest?
Solution
Solution of Exercise 10.2.
amber stays amber; red becomes green. The fastest way to red is button, tick, tick, tick: green, green wait, amber, red.
Exercise 10.3 ★
Compute by hand the moving averages of width of the readings , , , , , , .
Solution
Solution of Exercise 10.3.
Three windows of five: , and . The readings spread over degree, the averages over .
Exercise 10.4 ★
A machine has states and events. How many entries does a complete transition table have? How many does the traffic light’s table have, and is it complete?
Exercise 10.5 ★
Write to_celsius(raw) for a sensor whose -bit readings span °C to °C. What is its step?
Solution
Solution of Exercise 10.5.
return -40 + raw * 125 / 1023 (the range is degrees). The step is degree. exercises/controllers.py has the same function with the range as parameters.
Exercise 10.6 ★★
A student removes the line ("amber", "button"): "amber" from the table, and a pedestrian presses the button during the amber light. What happens to the program, and why is it dangerous in a real crossing? Write a next_state(table, state, event) that cannot fail this way.
Solution
Solution of Exercise 10.6.
TABLE[("amber", "button")] raises a KeyError and the program stops: the controller is dead, and the light stays as it was, or goes dark, while cars and pedestrians rely on it. The function next_state of the exercise file returns table.get((state, event), state), so that a missing pair means “no change”. Better still, a test checks that the table has all pairs.
Exercise 10.7 ★★
Write a thermostat for a greenhouse to this specification: the heater goes on when the temperature falls below °C, off when it rises above °C, and keeps its state in between.
Solution
Solution of Exercise 10.7.
if t < 18: return True, if t > 21: return False, else return heater: the function receives the current state of the heater and returns the new one (exercises/controllers.py).
Exercise 10.8 ★★
The readings are , , , , , , , , , , and the heater is off at the start. How many times does a plain thermostat at switch? And the greenhouse thermostat of the previous exercise?
Solution
Solution of Exercise 10.8.
The plain thermostat switches at every crossing of : on at , off at , on at , off at , on at , off at , on at , off at : times. The greenhouse thermostat switches on at and off at : times. The tests check both counts.
Exercise 10.9 ★★
Give the trace of the traffic light, from green, for the events button, tick, button, tick, tick, button, tick. How many ticks do cars wait at red?
Solution
Solution of Exercise 10.9.
green, green wait, amber, amber (the button changes nothing), red, green, green wait, amber. The cars wait one tick at red, the time given to the pedestrians.
Exercise 10.10 ★★
A new version of the lift accepts a call whenever the motor is stopped, without looking at the door. Starting with the door open at floor , which event leads to an unsafe state? Show it with the function safe.
Solution
Solution of Exercise 10.10.
call1 (or call2): the new version gives , and safe returns False: the cabin would leave with its door open.
Exercise 10.11 ★★
Write check_safe(states, events, step, safe), which returns every pair (state, event) that leads from a safe state to an unsafe one. Run it on the lift and on the version of the previous exercise.
Solution
Solution of Exercise 10.11.
Two nested loops over the states and the events, keeping the pairs with safe(s) true and safe(step(s, e)) false (exercises/controllers.py). On the lift’s reachable states the list is empty. With the new version it has pairs: an open door at any floor, with a call to either other floor.
Exercise 10.12 ★★★
Prove that a thermostat with hysteresis, thresholds , switches on only when the reading is below , and switches off only when it is above . Deduce that between two switchings on, the readings have gone above once: the heater switches at most once each time the readings cross the whole band.
Solution
Solution of Exercise 10.12.
The controller returns True only in its first branch, which needs a reading below , and False only in its second, which needs a reading above ; otherwise it returns the current state. So an off-to-on switch happens only at a reading below and an on-to-off switch only at a reading above . Between two switchings on there is a switching off, so some reading in between was above , and the next switching on needs a reading below again: the readings crossed the whole band, from below to above and back.
Exercise 10.13 ★★★
A car park with spaces has a barrier at the entry. Its controller counts the cars inside: it lets a car in only if there is room, and counts it out when it leaves. Write it as a function barrier(state, event) and test it with four cars arriving and one leaving.
Solution
Solution of Exercise 10.13.
The state is (cars inside, barrier position). On car at entry, if there are fewer than cars, the count goes up by one; on car at exit, if there is a car, it goes down by one (exercises/controllers.py). Four arrivals give , , , (the fourth car is refused), and one departure gives .
Exercise 10.14 ★★★
A smaller lift serves only floors and . List by hand all its reachable states, starting from floor with the door closed, and check the safety property on each.
Solution
Solution of Exercise 10.14.
From : by open or call0; by call1; then by arrive; by close; and by call0, whose arrive leads back to floor with the door open. Six states; the open ones all have the motor stopped, so all are safe.
Exercise 10.15 ★★★
A control loop reads a command with input() at each turn, then reads the thermometer and drives the heater. What happens to the heating while nobody types anything? Propose a structure in which the loop never waits for a person.
Solution
Solution of Exercise 10.15.
input() waits until a line is typed: while nobody types, the loop is stuck, the thermometer is not read and the heater stays as it was, perhaps on for hours. The loop must never wait for a person: at each turn it checks whether a command has arrived (a button is a sensor too, read like the others), handles it if there is one, and goes on with its readings either way.
10.6 Problem: The Lift of the Town Hall
Problem 10.1
Weekend problem — proving the lift safe by checking every state
The program exercises/lift_check.py starts from floor with the door closed, tries every event in every state it finds, and stops when no new state appears. It then serves a list of calls and counts the events each one needs.
Part I — States and events.
- How many values can each of the four parts of the lift’s state take? How many tuples is that at most?
- List the six events.
- Why can the target be
None, and when is it? - Which states, among those tuples, would be unsafe?
Part II — The transitions.
- From , give the next state for each of the six events.
- From , give the next state for each of the six events.
- Which transitions open the door? Check that each leaves the motor stopped.
- Which transitions start the motor? Check that each requires the door closed.
Part III — Every reachable state.
- Run the program. How many states are reachable?
- List them: the stopped ones, then the moving ones with their targets.
- Why is never reached?
- The program finds no unsafe state. Why does that prove that the lift is never unsafe, whatever events arrive, in whatever order?
- Does the proof still hold if the lift starts with its door open at floor ?
Part IV — Serving calls.
- For the calls , , , , , the program counts the events each needs. Explain the and the .
- What is the mean number of events per call?
- Find a list of five calls with a larger mean, and one with a smaller mean.
- A real lift would serve a call at floor on its way from to . Which part of the state would that change?
- Why would checking every state be harder for a lift of floors, and still possible?
- State the result: the number of reachable states, and why the door is never open while the cabin moves.
Solution
Solution of Problem 10.1.
1. Floor , door , motor , target (, , or None): at most tuples.
2. call0, call1, call2, open, close, arrive.
3. The target is the floor the cabin is going to; when it is stopped it is going nowhere, and the target is None.
4. Those with the door open and the motor going up or down: of them.
5. call0 and open: ; call1: ; call2: ; close and arrive: no change.
6. arrive gives ; the five others change nothing, since the motor is running.
7. open (only with the motor stopped), a call to the current floor (only with the motor stopped), and arrive at the target, which stops the motor in the same transition. Each leaves the motor stopped.
8. Only a call to another floor, which requires the door closed and the motor stopped.
9. .
10. Stopped: each floor with the door open or closed, states. Moving: up from to , up from to , up from to , down from to , down from to , down from to : states.
11. A call to the floor where the cabin is opens the door instead of starting the motor, and arrive at the target stops the motor: the cabin never moves towards the floor it is on.
12. The set found contains the start, and every event applied to any of its states gives a state of the set: whatever the sequence of events, the lift moves from state to state inside the set, and every state of the set is safe.
13. Yes: is in the set, so everything reachable from it is in the set too.
14. Call from floor , door closed: the call and two arrive, events. Call from floor , door open: close, the call and two arrive, events.
15. .
16. needs events, a mean of . needs each, a mean of .
17. The target: it would become a set of floors still to serve, and arrive would stop at any floor in that set.
18. The number of states grows with the floors and the targets, to a few hundred for one target, and much more with a set of calls; a program still lists them all in a fraction of a second, which is why such checks are done by computer.
19. The lift has reachable states among possible tuples, and none has the door open with the motor running: the door opens only in transitions that leave the motor stopped, and the motor starts only from a state with the door closed. Since every event leads from a reachable state to a reachable state, this check of all proves that the door is never open while the cabin moves.