---
title: "Sensors, Actuators and Control Programs"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 10
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/10-sensors-actuators-and-control-programs
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 10 — Sensors, 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).

![A temperature sensor sealed in a steel tube at the end of its cable, ready to be dipped in water or buried in a wall; the computer at the other end reads its temperature as a number. Photograph: Leonardo Postay, CC BY-SA 4.0.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-sensors-actuators-control/img-d496fce43028.jpg)

*A temperature [sensor](#def-g10-sensors-actuators-control-sensor) sealed in a steel tube at the end of its cable, ready to be dipped in water or buried in a wall; the computer at the other end reads its temperature as a number. Photograph: Leonardo Postay, CC BY-SA 4.0.*

**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](#def-g10-sensors-actuators-control-sensor), decide, command the [actuators](#def-g10-sensors-actuators-control-sensor), wait until the next period.

![The control loop of a thermostat. The program never sees the room, only numbers; its decisions change the room, which changes the next numbers.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-sensors-actuators-control/fig-3c7a4dc9ba97.svg)

*The [control loop](#def-g10-sensors-actuators-control-control-loop) of a thermostat. The program never sees the room, only numbers; its decisions change the room, which changes the next numbers.*

## 10.2 Measured values turned into numbers

The simulated thermometer of the chapter gives a whole number from $0$ to $1023$, on $10$ bits, where $0$ means $-20$ °C and $1023$ means $60$ °C. Turning it into degrees takes an offset and a scale.

```python
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")
```

***Listing 10.1.** From a $10$-bit reading to degrees. code/grade-10/10-sensors-actuators-control/listings/convert.py*

```
$ 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
```

***Output 10.1.** A step of the reading is $80/1023 \approx 0.078$ degree: the [sensor](#def-g10-sensors-actuators-control-sensor) cannot tell apart two temperatures closer than that.*

A real measurement also wobbles from one reading to the next: electrical noise, air moving past the [sensor](#def-g10-sensors-actuators-control-sensor). The simulated [sensor](#def-g10-sensors-actuators-control-sensor) adds a random error of about $0.3$ degree. Averaging the last few readings smooths it out, at the price of reacting a little later.

```python
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))
```

***Listing 10.2.** A moving average of five readings. code/grade-10/10-sensors-actuators-control/listings/smooth.py*

```
$ 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
```

***Output 10.2.** The true value is $20.0$ °C: averaging divides the spread of the readings by almost three.*

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](#def-g10-sensors-actuators-control-state-machine). The gap between the two thresholds is the *band*.

```python
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}")
```

***Listing 10.3.** Two thermostats for the same room. code/grade-10/10-sensors-actuators-control/listings/thermostat.py*

```
$ 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
```

***Output 10.3.** Six simulated hours: the band of one degree cuts the switching by almost three, for a temperature that moves a little more.*

The function `room` of the chapter’s `sensor.py` simulates the room minute by minute: it loses heat towards the $8$ °C outside, gains heat when the heater is on, and asks the controller each minute what to do with a fresh noisy reading.

![Two hours of the simulated room. The plain thermostat keeps the temperature close to 20 but switches almost every minute; with hysteresis the temperature rises and falls through the band in long, regular swings.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-sensors-actuators-control/fig-779cdcfb7511.svg)

*Two hours of the simulated room. The plain thermostat keeps the temperature close to $20$ but switches almost every minute; with [hysteresis](#def-g10-sensors-actuators-control-hysteresis) the temperature rises and falls through the band in long, regular swings.*

## 10.3 A controller as a state machine

A thermostat has two [states](#def-g10-sensors-actuators-control-state-machine), heating or not. A traffic light or a lift has more, and what it does with an [event](#def-g10-sensors-actuators-control-state-machine), a button pressed, a floor reached, depends on the [state](#def-g10-sensors-actuators-control-state-machine) it is in.

![A pedestrian crossing with its button: pressing it is an event, and what the light does next depends on its state.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-sensors-actuators-control/img-0f4c96d3cc16.jpg)

*A pedestrian crossing with its button: pressing it is an [event](#def-g10-sensors-actuators-control-state-machine), and what the light does next depends on its [state](#def-g10-sensors-actuators-control-state-machine).*

**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](#def-g10-sensors-actuators-control-state-machine) table is a dictionary from ([state](#def-g10-sensors-actuators-control-state-machine), [event](#def-g10-sensors-actuators-control-state-machine)) to the next [state](#def-g10-sensors-actuators-control-state-machine). 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.

![The crossing as a state machine. A tick is the end of a timed period. The pairs not drawn, such as amber with button, leave the state unchanged.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-sensors-actuators-control/fig-0e8a464ad98c.svg)

*The crossing as a [state machine](#def-g10-sensors-actuators-control-state-machine). A *tick* is the end of a timed period. The pairs not drawn, such as amber with *button*, leave the [state](#def-g10-sensors-actuators-control-state-machine) unchanged.*

```python
# 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
```

***Listing 10.4.** A table-driven traffic light. code/grade-10/10-sensors-actuators-control/listings/traffic_light.py*

```
$ 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
```

***Output 10.4.** A trace of seven [events](#def-g10-sensors-actuators-control-state-machine). The second press changes nothing: a red light is already on its way.*

**Method 10.6 (Writing a controller as a state machine).**

1. List the [states](#def-g10-sensors-actuators-control-state-machine) , and say what each [actuator](#def-g10-sensors-actuators-control-sensor) does in each of them.
2. List the [events](#def-g10-sensors-actuators-control-state-machine) : readings that cross a threshold, buttons, timers.
3. For every pair ( [state](#def-g10-sensors-actuators-control-state-machine) , [event](#def-g10-sensors-actuators-control-state-machine) ), decide the next [state](#def-g10-sensors-actuators-control-state-machine) , including “no change”; a table must have no hole.
4. Write the property that must never fail, as a test on a [state](#def-g10-sensors-actuators-control-state-machine) , and check it on every [state](#def-g10-sensors-actuators-control-state-machine) the machine can reach.

## 10.4 The lift

The lift of the town hall serves floors $0$, $1$ and $2$. Its [state](#def-g10-sensors-actuators-control-state-machine) 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](#def-g10-sensors-actuators-control-state-machine) are a call to a floor, a request to open or close the door, and the signal *arrive* that a [sensor](#def-g10-sensors-actuators-control-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](#def-g10-sensors-actuators-control-state-machine), but few kinds of rules.

```python
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)}")
```

***Listing 10.5.** The lift’s [transitions](#def-g10-sensors-actuators-control-state-machine), and the safety property. code/grade-10/10-sensors-actuators-control/listings/lift.py*

```
$ 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
```

***Output 10.5.** The first call is refused while the door is open, and the request to open is refused while the cabin moves.*

![The lift’s states. Each moving state stands for three states, with their floor and target; the orange arrows are arrive at the target, which stops the motor and opens the door in one transition; the black arrows are open (downwards) and close (upwards). Calls start the motor only from a closed state.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-sensors-actuators-control/fig-09787401f7dd.svg)

*The lift’s [states](#def-g10-sensors-actuators-control-state-machine). Each moving [state](#def-g10-sensors-actuators-control-state-machine) stands for three [states](#def-g10-sensors-actuators-control-state-machine), with their floor and target; the orange arrows are *arrive* at the target, which stops the motor and opens the door in one [transition](#def-g10-sensors-actuators-control-state-machine); the black arrows are *open* (downwards) and *close* (upwards). Calls start the motor only from a closed [state](#def-g10-sensors-actuators-control-state-machine).*

A person does not send [events](#def-g10-sensors-actuators-control-state-machine) by hand; a panel of buttons does. A small text interface plays the panel: it reads a command, checks it, sends the [event](#def-g10-sensors-actuators-control-state-machine) and shows the new [state](#def-g10-sensors-actuators-control-state-machine).

```python
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)
```

***Listing 10.6.** A text panel for the lift. code/grade-10/10-sensors-actuators-control/listings/lift_menu.py*

```
$ 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
```

***Output 10.6.** A session: typing errors are refused, and every [state](#def-g10-sensors-actuators-control-state-machine) reached is checked.*

Checking the [states](#def-g10-sensors-actuators-control-state-machine) 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](#def-g10-sensors-actuators-control-state-machine) 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](#def-g10-sensors-actuators-control-state-machine), 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](#def-g10-sensors-actuators-control-sensor) reads $300$, then $700$. Convert both to degrees. Which reading corresponds to $0$ °C most closely?

**Solution of Exercise 10.1.**

$-20 + 300 \times 80/1023 \approx 3.46$ °C and $-20 + 700 \times 80/1023 \approx 34.74$ °C. $0$ °C would be $20 \times 1023/80 \approx 255.8$: the reading $256$ ($0.02$ °C) is closest, nearer than $255$ ($-0.06$ °C).

**Exercise 10.2 ★.**

In the traffic light’s table, what is the next [state](#def-g10-sensors-actuators-control-state-machine) of *amber* on *button*, and of *red* on *tick*? Starting from *green*, which [events](#def-g10-sensors-actuators-control-state-machine) lead to *red* fastest?

**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 $5$ of the readings $20.1$, $19.7$, $20.4$, $19.9$, $20.3$, $19.6$, $20.0$.

**Solution of Exercise 10.3.**

Three windows of five: $100.4/5 = 20.08$, $99.9/5 = 19.98$ and $100.2/5 = 20.04$. The readings spread over $0.8$ degree, the averages over $0.1$.

**Exercise 10.4 ★.**

A machine has $6$ [states](#def-g10-sensors-actuators-control-state-machine) and $4$ [events](#def-g10-sensors-actuators-control-state-machine). How many entries does a complete [transition](#def-g10-sensors-actuators-control-state-machine) table have? How many does the traffic light’s table have, and is it complete?

**Solution of Exercise 10.4.**

$6 \times 4 = 24$ entries, one per pair ([state](#def-g10-sensors-actuators-control-state-machine), [event](#def-g10-sensors-actuators-control-state-machine)). The traffic light has $4$ [states](#def-g10-sensors-actuators-control-state-machine) and $2$ [events](#def-g10-sensors-actuators-control-state-machine): its table has $8$ entries, all present, so it is complete.

**Exercise 10.5 ★.**

Write `to_celsius(raw)` for a [sensor](#def-g10-sensors-actuators-control-sensor) whose $10$-bit readings span $-40$ °C to $85$ °C. What is its step?

**Solution of Exercise 10.5.**

`return -40 + raw * 125 / 1023` (the range is $85 - (-40) = 125$ degrees). The step is $125/1023 \approx 0.122$ 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 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 $8$ pairs.

**Exercise 10.7 ★★.**

Write a thermostat for a greenhouse to this specification: the heater goes on when the temperature falls below $18$ °C, off when it rises above $21$ °C, and keeps its [state](#def-g10-sensors-actuators-control-state-machine) in between.

**Solution of Exercise 10.7.**

`if t < 18: return True`, `if t > 21: return False`, else `return heater`: the function receives the current [state](#def-g10-sensors-actuators-control-state-machine) of the heater and returns the new one (`exercises/controllers.py`).

**Exercise 10.8 ★★.**

The readings are $19.6$, $19.4$, $19.6$, $19.3$, $19.7$, $17.8$, $19.8$, $21.2$, $19.4$, $19.6$, and the heater is off at the start. How many times does a plain thermostat at $19.5$ switch? And the greenhouse thermostat of the previous exercise?

**Solution of Exercise 10.8.**

The plain thermostat switches at every crossing of $19.5$: on at $19.4$, off at $19.6$, on at $19.3$, off at $19.7$, on at $17.8$, off at $19.8$, on at $19.4$, off at $19.6$: $8$ times. The greenhouse thermostat switches on at $17.8$ and off at $21.2$: $2$ times. The tests check both counts.

**Exercise 10.9 ★★.**

Give the trace of the traffic light, from *green*, for the [events](#def-g10-sensors-actuators-control-state-machine) *button*, *tick*, *button*, *tick*, *tick*, *button*, *tick*. How many ticks do cars wait at red?

**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 $0$, which [event](#def-g10-sensors-actuators-control-state-machine) leads to an unsafe [state](#def-g10-sensors-actuators-control-state-machine)? Show it with the function `safe`.

**Solution of Exercise 10.10.**

*call1* (or *call2*): the new version gives $(0, \text{open}, \text{up}, 1)$, 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](#def-g10-sensors-actuators-control-state-machine), [event](#def-g10-sensors-actuators-control-state-machine)) that leads from a safe [state](#def-g10-sensors-actuators-control-state-machine) to an unsafe one. Run it on the lift and on the version of the previous exercise.

**Solution of Exercise 10.11.**

Two nested loops over the [states](#def-g10-sensors-actuators-control-state-machine) and the [events](#def-g10-sensors-actuators-control-state-machine), keeping the pairs with `safe(s)` true and `safe(step(s, e))` false (`exercises/controllers.py`). On the lift’s $12$ reachable [states](#def-g10-sensors-actuators-control-state-machine) the list is empty. With the new version it has $6$ pairs: an open door at any floor, with a call to either other floor.

**Exercise 10.12 ★★★.**

Prove that a thermostat with [hysteresis](#def-g10-sensors-actuators-control-hysteresis), thresholds $a < b$, switches on only when the reading is below $a$, and switches off only when it is above $b$. Deduce that between two switchings on, the readings have gone above $b$ once: the heater switches at most once each time the readings cross the whole band.

**Solution of Exercise 10.12.**

The controller returns `True` only in its first branch, which needs a reading below $a$, and `False` only in its second, which needs a reading above $b$; otherwise it returns the current [state](#def-g10-sensors-actuators-control-state-machine). So an off-to-on switch happens only at a reading below $a$ and an on-to-off switch only at a reading above $b$. Between two switchings on there is a switching off, so some reading in between was above $b$, and the next switching on needs a reading below $a$ again: the readings crossed the whole band, from below $a$ to above $b$ and back.

**Exercise 10.13 ★★★.**

A car park with $3$ 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 of Exercise 10.13.**

The [state](#def-g10-sensors-actuators-control-state-machine) is (cars inside, barrier position). On *car at entry*, if there are fewer than $3$ 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 $1$, $2$, $3$, $3$ (the fourth car is refused), and one departure gives $2$.

**Exercise 10.14 ★★★.**

A smaller lift serves only floors $0$ and $1$. List by hand all its reachable [states](#def-g10-sensors-actuators-control-state-machine), starting from floor $0$ with the door closed, and check the safety property on each.

**Solution of Exercise 10.14.**

From $(0, \text{closed}, \text{stop}, \text{None})$: $(0, \text{open}, \text{stop}, \text{None})$ by *open* or *call0*; $(0, \text{closed}, \text{up}, 1)$ by *call1*; then $(1, \text{open}, \text{stop},
\text{None})$ by *arrive*; $(1, \text{closed}, \text{stop}, \text{None})$ by *close*; and $(1, \text{closed}, \text{down}, 0)$ by *call0*, whose *arrive* leads back to floor $0$ with the door open. Six [states](#def-g10-sensors-actuators-control-state-machine); the open ones all have the motor stopped, so all are safe.

**Exercise 10.15 ★★★.**

A [control loop](#def-g10-sensors-actuators-control-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 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](#def-g10-sensors-actuators-control-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 $0$ with the door closed, tries every [event](#def-g10-sensors-actuators-control-state-machine) in every [state](#def-g10-sensors-actuators-control-state-machine) it finds, and stops when no new [state](#def-g10-sensors-actuators-control-state-machine) appears. It then serves a list of calls and counts the [events](#def-g10-sensors-actuators-control-state-machine) each one needs.

**Part I — States and events.**

1. How many values can each of the four parts of the lift’s [state](#def-g10-sensors-actuators-control-state-machine) take? How many tuples is that at most?
2. List the six [events](#def-g10-sensors-actuators-control-state-machine) .
3. Why can the target be `None` , and when is it?
4. Which [states](#def-g10-sensors-actuators-control-state-machine) , among those tuples, would be unsafe?

**Part II — The transitions.**

5. From $(0, \text{closed}, \text{stop}, \text{None})$ , give the next [state](#def-g10-sensors-actuators-control-state-machine) for each of the six [events](#def-g10-sensors-actuators-control-state-machine) .
6. From $(1, \text{closed}, \text{up}, 2)$ , give the next [state](#def-g10-sensors-actuators-control-state-machine) for each of the six [events](#def-g10-sensors-actuators-control-state-machine) .
7. Which [transitions](#def-g10-sensors-actuators-control-state-machine) open the door? Check that each leaves the motor stopped.
8. Which [transitions](#def-g10-sensors-actuators-control-state-machine) start the motor? Check that each requires the door closed.

**Part III — Every reachable state.**

9. Run the program. How many [states](#def-g10-sensors-actuators-control-state-machine) are reachable?
10. List them: the stopped ones, then the moving ones with their targets.
11. Why is $(1, \text{closed}, \text{up}, 1)$ never reached?
12. The program finds no unsafe [state](#def-g10-sensors-actuators-control-state-machine) . Why does that prove that the lift is never unsafe, whatever [events](#def-g10-sensors-actuators-control-state-machine) arrive, in whatever order?
13. Does the proof still hold if the lift starts with its door open at floor $0$ ?

**Part IV — Serving calls.**

14. For the calls $2$ , $0$ , $1$ , $2$ , $1$ , the program counts the [events](#def-g10-sensors-actuators-control-state-machine) each needs. Explain the $3$ and the $4$ .
15. What is the mean number of [events](#def-g10-sensors-actuators-control-state-machine) per call?
16. Find a list of five calls with a larger mean, and one with a smaller mean.
17. A real lift would serve a call at floor $1$ on its way from $0$ to $2$ . Which part of the [state](#def-g10-sensors-actuators-control-state-machine) would that change?
18. Why would checking every [state](#def-g10-sensors-actuators-control-state-machine) be harder for a lift of $20$ floors, and still possible?
19. [State](#def-g10-sensors-actuators-control-state-machine) the result: the number of reachable [states](#def-g10-sensors-actuators-control-state-machine) , and why the door is never open while the cabin moves.

**Solution of Problem 10.1.**

**1.** Floor $3$, door $2$, motor $3$, target $4$ ($0$, $1$, $2$ or `None`): at most $3 \times 2 \times 3 \times 4 = 72$ 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: $3 \times 2 \times 4 = 24$ of them.

**5.** *call0* and *open*: $(0, \text{open}, \text{stop}, \text{None})$; *call1*: $(0, \text{closed}, \text{up}, 1)$; *call2*: $(0, \text{closed}, \text{up}, 2)$; *close* and *arrive*: no change.

**6.** *arrive* gives $(2, \text{open}, \text{stop}, \text{None})$; 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](#def-g10-sensors-actuators-control-state-machine). Each leaves the motor stopped.

**8.** Only a call to another floor, which requires the door closed and the motor stopped.

**9.** $12$.

**10.** Stopped: each floor with the door open or closed, $6$ [states](#def-g10-sensors-actuators-control-state-machine). Moving: up from $0$ to $1$, up from $0$ to $2$, up from $1$ to $2$, down from $2$ to $1$, down from $2$ to $0$, down from $1$ to $0$: $6$ [states](#def-g10-sensors-actuators-control-state-machine).

**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](#def-g10-sensors-actuators-control-state-machine) applied to any of its [states](#def-g10-sensors-actuators-control-state-machine) gives a [state](#def-g10-sensors-actuators-control-state-machine) of the set: whatever the sequence of [events](#def-g10-sensors-actuators-control-state-machine), the lift moves from [state](#def-g10-sensors-actuators-control-state-machine) to [state](#def-g10-sensors-actuators-control-state-machine) inside the set, and every [state](#def-g10-sensors-actuators-control-state-machine) of the set is safe.

**13.** Yes: $(0, \text{open}, \text{stop}, \text{None})$ is in the set, so everything reachable from it is in the set too.

**14.** Call $2$ from floor $0$, door closed: the call and two *arrive*, $3$ [events](#def-g10-sensors-actuators-control-state-machine). Call $0$ from floor $2$, door open: *close*, the call and two *arrive*, $4$ [events](#def-g10-sensors-actuators-control-state-machine).

**15.** $(3 + 4 + 3 + 3 + 3)/5 = 3.2$.

**16.** $2, 0, 2, 0, 2$ needs $3, 4, 4, 4, 4$ [events](#def-g10-sensors-actuators-control-state-machine), a mean of $3.8$. $1, 1, 1, 1, 1$ needs $2$ each, a mean of $2$.

**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](#def-g10-sensors-actuators-control-state-machine) 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 $12$ reachable [states](#def-g10-sensors-actuators-control-state-machine) among $72$ possible tuples, and none has the door open with the motor running: the door opens only in [transitions](#def-g10-sensors-actuators-control-state-machine) that leave the motor stopped, and the motor starts only from a [state](#def-g10-sensors-actuators-control-state-machine) with the door closed. Since every [event](#def-g10-sensors-actuators-control-state-machine) leads from a reachable [state](#def-g10-sensors-actuators-control-state-machine) to a reachable [state](#def-g10-sensors-actuators-control-state-machine), this check of all $12$ proves that the door is never open while the cabin moves.
