Level 2 Building Machines That Respond · Term 3: Embedded Intelligence
How a small computer reads the world through sensors, decides with state machines and acts through actuators, and how feedback lets a machine correct itself. Week 22 opens the signals thread: amplitude, frequency, sampling, quantisation and noise, with real numbers. Everything runs in the browser: a virtual pin panel, a sensor-to-number pipeline, a signal lab, a state-machine runner, a PWM motor, a timing scrubber and a thermostat, plus the Playground labs and Builds.
In this file: 26 lessons across weeks 19–27, with 134 practice questions (questions only, no answers).
Program, analyse and test simple machines that sense their surroundings, make decisions and change their behaviour, all in simulation. Levels describe what you can do, not your age. About About 3 hours a week: roughly 1–1.5 hours of lessons, 1 hour of lab or coding practice and 30 minutes of notebook writing..
Week 19: Microcontroller concepts
This week you will
- Name the main parts of a microcontroller (CPU, flash, RAM, clock, peripherals) and what each does.
- Estimate how many instructions fit into a given time from the clock rate.
- Describe the setup-then-loop structure of embedded firmware.
A whole computer on one chip
Your washing machine, your bike light and a Mars rover's wheel all hide the same kind of tiny computer. What is inside it?
Why it matters
There are far more microcontrollers in the world than laptops and phones put together: one in every remote control, toaster, car window and toy robot. Each one is a complete computer squeezed onto a chip that costs about the same as a chocolate bar and runs on a trickle of power. If you can program one, you can make almost any object respond to the world.
Goals
- Name the main parts of a microcontroller: CPU, flash memory, RAM, clock and peripherals.
- Explain what each part does using an everyday machine as the example.
- Explain why a machine uses a microcontroller rather than a laptop-style computer.
Predict
A microcontroller loses power and then switches back on. Its program is still there. Where was the program kept?
- In RAM, which forgets nothing
- In flash memory, which keeps data without power
- It downloads the program again from the internet
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open Level 4 of the Virtual Computer and step through a program one instruction at a time. Each step is one fetch–execute cycle: notice where the instruction comes from (memory), where the working number lives (a register) and what decides which instruction comes next.
What the interactive shows, in words
The Virtual Computer activity can be followed as a list: the program counter points to an instruction in memory; the CPU fetches it, decodes it and executes it (for example LOAD a number into a register or ADD); then the program counter moves on, or jumps if the instruction says so. Repeat until HALT.
Understand
Five parts, one chip
A microcontroller (MCU) packs a whole computer onto one chip. The CPU follows instructions one at a time. Flash memory stores the program, even with the power off. RAM holds the variables while it runs. The clock is a steady tick that keeps everything in step. Peripherals are small helper circuits for the outside world: pins that read buttons and drive LEDs, an ADC that measures voltages, timers that count time, and serial ports that talk to other chips.
Microcontroller or laptop?
A laptop processor is fast and general: it runs many programs, needs lots of separate memory chips and uses tens of watts. A microcontroller is small, cheap and dedicated: it runs one program forever, starts in a fraction of a second and can run for months on a coin cell. It is slower, but a washing machine does not need to edit video; it needs to read a door switch reliably, millions of times.
Following the instructions
The CPU repeats one cycle: fetch the next instruction from flash, decode what it means, execute it (add, compare, read a pin), then move on. A special register called the program counter remembers where it is. A jump instruction changes the program counter, which is how loops and decisions work underneath your code.
Explain it another way: intuitive
Think of a microcontroller as a tiny kitchen. The recipe book is flash, the worktop is RAM, the cook is the CPU, the kitchen timer is the clock and the oven, tap and scales are the peripherals.
Explain it another way: technical
Typical small MCUs have tens to hundreds of kilobytes of flash and a few to a few hundred kilobytes of RAM, run at roughly 1–250 MHz and include GPIO, ADC, timers and serial peripherals (UART, I²C, SPI). Peripherals are controlled by writing numbers into special memory locations called registers.
Explain it another way: applied
A digital kitchen scale: a load sensor feeds the ADC peripheral, the CPU turns counts into grams, a timer blanks the display after a minute and the program sits in flash. The whole thing runs for a year on two AAA batteries.
Try these examples
Example 1
A bike light flashes, reads a button and dims when the battery is low. Which microcontroller parts are involved?
The worked solution is in the online lesson.
Common mix-ups
A microcontroller is just a slow, cheap laptop chip.
✓ It is designed differently: memory, clock and peripherals are built in, so one chip can run a machine by itself.RAM and flash are the same thing.
✓ Flash keeps the program with the power off; RAM is fast working memory that forgets on power-down.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A variable counting button presses is lost every time the device is switched off. Which memory is it stored in?
- Flash
- RAM
- The clock
2. Which peripheral turns a sensor voltage such as 1.2 V into a number the program can use?
- A timer
- The ADC (analog-to-digital converter)
- A serial port
- Flash memory
3. Why does a TV remote use a microcontroller rather than a laptop processor?
- Microcontrollers are faster
- It needs one small, cheap, low-power computer running one program
- Laptop processors cannot read buttons
4. What does the CPU do over and over while the program runs?
- Fetch an instruction, decode it, execute it
- Download, install, restart
- Measure, sleep, forget
5. A microcontroller's clock runs at 160 MHz. How long is one clock period, in nanoseconds?
Answer: ns
Apply it
Pick a machine at home (microwave, kettle, toy, alarm clock). Draw a box for the microcontroller with its five parts, then draw arrows to every button, sensor, light and motor you think it uses. Label which peripheral each arrow connects to.
Reflect
Which part of the microcontroller surprised you most, and what would a machine lose without it?
Counting in nanoseconds
A 16 MHz chip ticks sixteen million times a second. Is that fast enough to catch a button, run a motor or record music?
Why it matters
Engineers ask 'is the chip fast enough?' before they choose one. The answer is simple arithmetic with the clock rate, and getting it right early stops a project discovering, weeks later, that its loop is too slow to catch a fast sensor.
Goals
- Convert a clock frequency in MHz into a clock period in nanoseconds.
- Estimate how many instructions fit into a time window from the clock rate and cycles per instruction.
- Decide whether a loop can meet a deadline, with units shown.
Predict
You double a microcontroller's clock from 16 MHz to 32 MHz. What happens to the length of one clock tick?
- It doubles
- It halves
- It stays the same
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose the 1,000-times-a-second motor deadline. Find the smallest clock that lets a 2,000-instruction loop fit. Then switch to the audio deadline and see what it would take.
What the interactive shows, in words
The budget calculator takes a clock frequency, cycles per instruction and loop size. It shows the clock period (1 ÷ frequency), instructions per millisecond, the time for one loop pass (instructions × cycles ÷ frequency) and compares it with a chosen deadline, saying whether it fits and what fraction of the deadline it uses.
Understand
Frequency and period are flip sides
The clock frequency is how many ticks happen each second, in hertz (Hz). Mega means million, so 16 MHz is 16,000,000 ticks a second. The period is how long one tick lasts: 1 ÷ 16,000,000 s = 62.5 nanoseconds. Light travels only about 19 metres in that time.
Instructions cost cycles
Simple instructions on many small chips take one clock cycle; others (dividing, reading slow memory) take several. Engineers use an average cycles per instruction to estimate. A 16 MHz chip at 1 cycle per instruction runs about 16 million instructions a second, which is 16,000 every millisecond.
Budgets and deadlines
Machines have deadlines: check the button every 10 ms, update the motor every 1 ms, take an audio sample every 22.7 µs. Divide the time per loop pass by the deadline to see how much of the budget you use. Leave a margin: real code has surprises, and a loop at 95% of its budget will overrun one day.
Explain it another way: intuitive
A clock is a drummer. A faster drummer gives more beats per second, and each beat is shorter. Each instruction needs one or a few beats, so more beats means more instructions.
Explain it another way: technical
N = f·t/CPI. Memory wait states, interrupts and peripheral access add cycles, so measured execution time is often longer than the estimate; real-time engineers measure the worst case with a spare pin and an oscilloscope, or a timer.
Explain it another way: mathematical
T = 1/f. With f in MHz, T in µs is 1/f and in ns is 1000/f. Loop time τ = n·CPI/f; deadline met when τ ≤ D, i.e. f ≥ n·CPI/D.
Explain it another way: applied
A drone's flight controller updates its motors hundreds of times a second. Its designers check that the whole sense–compute–act loop fits inside that period with time to spare, or the drone wobbles.
Derivation: From MHz to an instruction budget
Frequency f counts ticks per second; 1 MHz = 1,000,000 ticks per second.
One tick lasts the period T = 1 ÷ f. At 16 MHz: T = 1 ÷ 16,000,000 s = 0.0000000625 s = 62.5 ns (1 ns = 0.000000001 s).
If each instruction needs c clock cycles on average, the chip runs f ÷ c instructions per second.
In a time window t, it runs N = f × t ÷ c instructions. At 16 MHz, c = 1, t = 1 ms: N = 16,000,000 × 0.001 ÷ 1 = 16,000.
A loop of n instructions takes n × c ÷ f seconds per pass. It meets a deadline D only if n × c ÷ f ≤ D, and wise engineers keep it well under.
Try these examples
Example 1
A 48 MHz chip averages 2 cycles per instruction. Can a 30,000-instruction loop run 1,000 times a second?
The worked solution is in the online lesson.
Common mix-ups
A 100 MHz chip runs 100 million lines of my program every second.
✓ One line of Python or C becomes many instructions, and instructions can take several cycles each.Higher frequency means a longer period.
✓ Period = 1 ÷ frequency: they move in opposite directions.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A microcontroller's clock runs at 100 MHz. How long is one clock period, in nanoseconds?
Answer: ns
2. A 16 MHz microcontroller needs about 4 clock cycles per instruction on average. Roughly how many instructions can it run in 1 ms?
Answer: instructions
3. A 16 MHz chip at 1 cycle per instruction runs a loop of 4,000 instructions. How many times can the loop run each second?
Answer: loops per second
4. A loop needs 5,000 instructions at 1 cycle each and must finish within 0.1 ms. What is the slowest clock that just meets the deadline, in MHz?
Answer: MHz
5. Your loop uses 97% of its 1 ms deadline in testing. What should you conclude?
- Perfect: it fits
- Risky: real code meets slower paths and interrupts, so keep a margin
- It must be broken
Apply it
A greenhouse controller must read four sensors, do 2,000 instructions of maths and update a display, all ten times a second. Estimate the instructions per pass (assume 500 per sensor read and 3,000 for the display), choose a clock from 1, 16 or 48 MHz at 2 cycles per instruction, and show your margin.
Reflect
Where in a machine you know would a slow loop actually cause a problem someone could notice?
Set up once, loop forever
Your laptop's programs start and stop. A microcontroller's program never ends. How do you write a program that runs forever, on purpose?
Why it matters
Nearly every small machine you will program has the same skeleton: prepare the hardware once, then go round a loop that reads sensors, decides and acts, forever. Learn this pattern and every later idea in this term (state machines, timers, feedback) slots straight into it.
Goals
- Describe the setup-then-loop structure of embedded firmware.
- Write a read–decide–act loop in Python-style pseudocode for a simple machine.
- Explain why a long delay inside the loop makes a machine slow to respond.
Predict
A loop reads a button, then waits 500 ms, then repeats. You tap the button for 0.1 s. What happens?
- It is always noticed
- It might be missed, because the loop spends most of its time waiting
- The chip crashes
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose 'Blocking: delay(500)'. Scrub the time from 0 to 2,000 ms and watch when each job in the loop runs. Did the loop notice the two button presses? Now switch to the non-blocking loop and compare.
What the interactive shows, in words
The timing scrubber shows three jobs (toggle an LED, read a sensor, read a button) on a 0–2,000 ms timeline. With a blocking delay of 500 ms, every job runs only once every 500 ms, and two short button presses (70 ms and 50 ms long) fall between reads and are missed. With a non-blocking loop, the button is read every 20 ms and both presses are seen.
Understand
Two parts: setup and loop
Embedded programs have a setup part that runs once at power-on (set pin modes, start the ADC, set variables) and a loop that runs forever. In Python-style code:
setup_pins()
while True:
temp = read_temperature()
if temp < 18:
heater_on()
else:
heater_off()There is no 'end of program': if the loop ever stopped, the machine would stop responding.
Read, decide, act
Each pass of the loop is one turn of sense–think–act: read the inputs, decide with ifs and comparisons, then set the outputs. Keep each pass short. A greenhouse loop that takes 5 ms reacts within 5 ms; one that sleeps for a minute is blind for a minute.
Why delays hurt
A delay(500) freezes the CPU for half a second. Nothing else runs: no buttons, no sensors, no safety checks. One delay is fine for blinking a single LED, but a machine doing several jobs needs a loop that never waits. You will build that in week 25 with timers.
Explain it another way: intuitive
A lighthouse keeper's routine: wake up once and prepare the lamp, then forever: look at the sea, decide, act, and look again.
Explain it another way: technical
This is the 'super-loop' architecture: setup() once, then loop() called endlessly (as in Arduino), or while True: in MicroPython. Interrupts can break in for urgent events, and an RTOS can schedule several loops, but small machines often need only one well-written loop.
Explain it another way: applied
A microwave's firmware loops thousands of times a second: read the keypad, check the door switch, update the countdown, set the magnetron and the display. Opening the door is noticed within a few milliseconds because the loop never waits long.
Try these examples
Example 1
Write pseudocode for a night light: an LED should be on when a light sensor reads below 300 counts.
The worked solution is in the online lesson.
Common mix-ups
A program that never ends has a bug.
✓ On a laptop, maybe. In a machine, the endless loop is the design: it keeps sensing for as long as the power is on.Adding delays makes a program more reliable.
✓ Long delays make the machine blind while it waits. Short loop passes make it responsive.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Where should 'set pin 3 as an output' go?
- In setup, once
- Inside the loop, every pass
- After the loop ends
2. In the heater loop (heater on if temp < 18, otherwise off), the readings on three passes are 17.5, 18.0 and 18.4. What does the heater do on each pass?
- on, on, off
- on, off, off
- off, off, on
3. A loop with no delay takes 2 ms per pass. How many times does it run each second?
Answer: passes
4. A learner writes the heater program without `while True:`. The heater works once at power-on, then never changes. Why?
- The sensor broke
- The program read, decided and acted once, then reached the end
- Python is too slow
5. A 100 MHz microcontroller needs about 2 clock cycles per instruction on average. Roughly how many instructions can it run in 1 ms?
Answer: instructions
Apply it
Write the setup and loop for a fridge-door alarm in Python-style pseudocode: a door switch on one pin, a buzzer on another. The buzzer sounds if the door is open. Then add a second sensor (a thermometer) without adding any delay, and trace your loop for three passes with made-up readings.
Reflect
Name a machine that would be dangerous if its loop stopped for one second. What would go wrong?
Week 20: Inputs and outputs
This week you will
- Configure a pin as an input or output and predict its voltage level.
- Size an LED resistor and a pull-up resistor with Ohm's law.
- Explain why a button needs a pull-up resistor and how debouncing works.
Pins: high, low and in between
One tiny metal leg on a chip can light an LED, read a button or wreck itself. What decides which?
Why it matters
Every button press and every LED in an embedded project passes through a GPIO (general-purpose input/output) pin. Getting the pin mode and the resistor right is the difference between a project that works for years and a chip that dies on day one.
Goals
- Configure a pin as an input or an output and predict its voltage level.
- Calculate the series resistor an LED needs on an output pin using Ohm's law.
- Explain why driving an output into a shorted button can damage a pin.
Safety: Simulation only. On real hardware, never connect a pin directly to a supply or to ground, and stay within the datasheet's current limits.
Predict
A 3.3 V microcontroller sets a pin as an output and writes HIGH. Roughly what voltage appears on the pin?
- 0 V
- About 3.3 V
- 5 V
- It depends on the program's mood
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Light the LED on GP3, then lower its resistor until the panel warns you. Next set GP2 to Output, write HIGH and hold its button. Finally set GP5 to plain Input and press 'Read all pins again' a few times.
What the interactive shows, in words
The pin panel lists four pins. Each can be set to Input, Input with pull-up or Output. Outputs write HIGH (3.3 V) or LOW (0 V); GP3 lights an LED whose current is (3.3 − 2.0) ÷ R. Buttons on GP2 and GP4 pull their pin to 0 V when held. A plain input with nothing connected reads unpredictable values. A HIGH output with its button held is reported as a short circuit. Two registers show the pin directions and the input readings as 4-bit numbers.
Understand
Output: the pin pushes
As an output, a pin is connected inside the chip either to the supply (HIGH, logic 1) or to 0 V (LOW, logic 0). It can supply a small current, often around 10–20 mA depending on the chip. That lights an LED but cannot run a motor.
Input: the pin listens
As an input, a pin draws almost no current. It reports 1 if its voltage is near the supply and 0 if near 0 V. If nothing connects it to either, it is floating and reads noise: the pin panel shows the same pin giving different answers on each read. Next lesson fixes that with a pull-up resistor.
Registers: pins as bits
The chip stores pin settings as bits in registers. If GP5…GP2 have directions 0, 1, 1, 0 (1 = output), the direction register holds 0110 = 6. Reading all inputs at once gives another 4-bit number. That is why binary from Level 1 matters: firmware sets pins by writing numbers.
Never fight an output
If an output drives HIGH while a button connects that same pin to 0 V, the pin is shorted: a large current flows and the pin can be damaged. Buttons belong on inputs, and every LED needs a series resistor.
Explain it another way: intuitive
An output pin is a tap you turn fully on or fully off. An input pin is a pressure gauge that only says 'high pressure' or 'low pressure'. A floating input is a gauge connected to nothing, guessing.
Explain it another way: technical
GPIO pins have direction, output and input registers. Logic thresholds are typically around 30% and 70% of the supply; voltages between are undefined. Datasheets give the maximum current per pin and per chip, and absolute maximum voltages that must never be exceeded.
Explain it another way: mathematical
R = (V_pin − V_f) ÷ I. Register value = Σ bit_k × 2^k, so bits b3 b2 b1 b0 = 0110 give 0×8 + 1×4 + 1×2 + 0×1 = 6.
Explain it another way: applied
Microwave keypads, car-door switches and the status LED on a router all connect to GPIO pins configured exactly like the panel: inputs with resistors for switches, outputs with series resistors for lights.
Derivation: Sizing an LED resistor
The pin gives V_pin (3.3 V). The LED takes a nearly fixed drop V_f (about 2.0 V for a red LED).
The resistor gets whatever is left: V_R = V_pin − V_f = 3.3 − 2.0 = 1.3 V.
Ohm's law, rearranged: R = V_R ÷ I. For I = 10 mA = 0.010 A: R = 1.3 ÷ 0.010 = 130 Ω.
Round up to the next standard value (150 Ω) so the current is a little less, never more.
Check: I = 1.3 ÷ 150 ≈ 8.7 mA, comfortably under a typical pin limit.
Try these examples
Example 1
A 5 V pin drives a green LED (V_f = 2.2 V) at 15 mA. What resistor?
The worked solution is in the online lesson.
Common mix-ups
An input pin with nothing connected reads 0.
✓ It floats and reads noise. Inputs need a pull-up or pull-down to have a defined level.An LED can go straight on a pin; the pin limits the current.
✓ Without a series resistor the current can exceed the pin's limit. Always calculate R = (V_pin − V_f) ÷ I.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A pin is set as a plain input with nothing connected. What does it read?
- Always 0
- Always 1
- Unpredictable values: it is floating
- The last value written
2. A 3.3 V output pin drives an LED that drops 2.2 V. What series resistor gives a current of 5 mA? Answer in ohms.
Answer: Ω
3. A 3.3 V output pin drives an LED that drops 2 V. What series resistor gives a current of 10 mA? Answer in ohms.
Answer: Ω
4. Pins GP5, GP4, GP3, GP2 are set to output, input, output, output (1 = output). Written as a 4-bit binary number in that order, what is the direction register in decimal?
Answer:
5. Why is it dangerous to set a button's pin as an output and write HIGH?
- The button gets bored
- Pressing the button connects a HIGH output straight to 0 V: a short circuit
- The LED will be too dim
Apply it
Design the pins for a two-button, three-LED game controller on a 3.3 V chip: list each pin's mode, the resistor for each LED at 8 mA (V_f = 2.0 V), and the direction register as a binary number. Check your design in the pin panel.
Reflect
Which mistake from today could you most easily make on a real board, and how would you check for it before powering up?
Pull-ups: giving a button a resting voltage
A button only connects two wires. So why does every microcontroller button also need a resistor?
Why it matters
Floating inputs cause some of the strangest bugs in electronics: a machine that switches on when you wave your hand near it. A single resistor fixes it, and choosing its value is your first real electrical design trade-off.
Goals
- Explain why a button needs a pull-up resistor and what 'active low' means.
- Calculate the current through a pull-up while the button is pressed.
- Choose between a strong and a weak pull-up and justify the trade-off.
Predict
A pin has a resistor to 3.3 V, and a button from the pin to 0 V. What does the pin read when the button is NOT pressed?
- 0
- 1
- It floats
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Build a voltage divider: R1 is the pull-up (10 kΩ). For R2, try a very small resistance (a pressed button) and then a very large one (an open button plus the pin's huge input resistance). Watch where Vout goes each time.
What the interactive shows, in words
In the circuits lab, a voltage divider has R1 (the pull-up) on top and R2 (the button) underneath, with Vout = Vin × R2 ÷ (R1 + R2). A tiny R2 (pressed button) gives Vout near 0 V; a huge R2 (open button) gives Vout near Vin. That is why a pull-up input reads 1 when released and 0 when pressed.
Understand
The pull-up idea
A pull-up resistor connects the input to the supply. With the button open, almost no current flows (the pin barely draws any), so there is almost no voltage across the resistor and the pin sits at the supply: reads 1. Pressing the button connects the pin straight to 0 V: reads 0. The resistor stops that press from being a short circuit.
It is a voltage divider
Treat the pull-up as R1 and the button as R2 in a divider: Vout = Vin × R2 ÷ (R1 + R2). Open button: R2 is enormous, so Vout ≈ Vin. Pressed: R2 ≈ 0, so Vout ≈ 0 V. A pull-down is the mirror image: resistor to 0 V, button to the supply, so pressed = 1.
Strong or weak?
While pressed, the pull-up carries I = V ÷ R. A 10 kΩ pull-up at 3.3 V wastes 0.33 mA; a 1 kΩ one wastes 3.3 mA, which matters on a battery. But a very weak pull-up (say 1 MΩ) is easily disturbed by noise and long wires. Typical choices sit between about 4.7 kΩ and 47 kΩ, and many chips have a built-in pull-up you can switch on.
Explain it another way: intuitive
A pull-up is a gentle spring holding a gate shut. The button is your hand pushing it open: much stronger than the spring, so you win, but the spring always returns it to a known position.
Explain it another way: technical
Internal pull-ups are typically tens of kilohms. In active-low logic, firmware tests if read(pin) == 0: for 'pressed'. Long cables add capacitance, so stronger pull-ups give faster, cleaner edges at the cost of current.
Explain it another way: mathematical
Pressed: I = V ÷ R. Open: V_pin = V × R_in ÷ (R + R_in), where R_in (often > 1 MΩ) ≫ R, so V_pin ≈ V. Power wasted while pressed: P = V² ÷ R.
Explain it another way: applied
Keyboard matrices, car-door switches and the reset button on most boards use pull-ups. Engineers prefer active low partly because a broken wire then reads 'not pressed' rather than 'pressed'.
Try these examples
Example 1
A 5 V system uses a 4.7 kΩ pull-up. How much current flows while the button is held, and how much power is wasted?
The worked solution is in the online lesson.
Common mix-ups
The pull-up resistor is there to limit the button's current only.
✓ It also gives the pin a defined resting voltage. Without it the input floats.Pressed always reads 1.
✓ With a pull-up, pressed reads 0 (active low). Check the wiring before writing the if statement.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. With a pull-up and a button to 0 V, which line of code means 'button pressed'?
- if read(pin) == 1:
- if read(pin) == 0:
- if read(pin) == 3.3:
2. A button connects a pin to 0 V. The pin has a 4.7 kΩ pull-up resistor to 5 V. While the button is held, how much current flows through the pull-up, in milliamps?
Answer: mA
3. A button connects a pin to 0 V. The pin has a 10 kΩ pull-up resistor to 5 V. While the button is held, how much current flows through the pull-up, in milliamps?
Answer: mA
4. A pull-down resistor connects the pin to 0 V and the button connects it to 3.3 V. What does a press read?
- 0
- 1
- It floats
5. Why not use a 10 MΩ pull-up to save even more current?
- It would short the supply
- It is so weak that noise and leakage can drag the pin away from 1
- Resistors that big do not exist
Apply it
A battery-powered doorbell button may be held for a long time by a child. Compare 1 kΩ, 10 kΩ and 100 kΩ pull-ups at 3.3 V: current while held, and how robust each is to noise on a 5 m cable. Recommend one in two sentences.
Reflect
Why do you think engineers often prefer that a broken wire reads 'not pressed'?
Debouncing: one press, one count
You press a button once. Your program counts seven presses. Is the code wrong, or is the button lying?
Why it matters
Bounce is a real, physical effect in every mechanical switch. It causes lifts that skip floors in a game, keypads that type '111' and counters that jump. Debouncing is the classic first example of firmware cleaning up a messy physical signal.
Goals
- Explain contact bounce and why a fast loop sees one press as many.
- Design a counting debouncer by choosing a reading interval and a number of identical readings.
- Calculate how many readings fall inside a bounce window and the delay a debouncer adds.
Predict
The metal contacts in a button hit each other and spring apart a few times before settling. Your loop reads the pin every 0.5 ms. What will it see?
- One clean change
- Several rapid changes, which look like several presses
- Nothing at all
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start with 1 identical reading needed (no debouncing) and count the 'presses'. Raise the readings needed until you get exactly one press. Then try a 5 ms reading interval: how few readings can you get away with, and how late is the press accepted?
What the interactive shows, in words
The debounce diagram shows a raw button signal over 40 ms: released (1) until 5 ms, chattering between 0 and 1 until 11 ms, pressed (0) until 30 ms, chattering again until 33 ms, then released. You choose the time between readings and how many identical readings are needed. With 1 reading needed, the chatter counts as several presses. With enough readings, exactly one press is counted, accepted a few milliseconds after the bouncing ends.
Understand
Why buttons bounce
Inside a push button, a springy metal contact slams onto another. It bounces apart and back a few times, like a dropped ball, before staying shut. For a millisecond or more the pin flickers between 0 and 1. Humans never notice; a loop reading thousands of times a second sees every flicker.
A counting debouncer
Keep the accepted state. Each reading, if the pin disagrees with it, count how many readings in a row have disagreed. Only when the count reaches N do you accept the new state. In Python-style code:
if raw == last: run += 1
else: run = 1
last = raw
if raw != state and run >= N:
state = rawThe price is delay
Waiting for N readings every p ms means a press is accepted about N × p ms after the bouncing stops. 4 readings every 0.5 ms adds about 2 ms: fine. 6 readings every 5 ms adds 30 ms, which starts to feel sluggish and can miss very short presses entirely. Engineers pick values from how long their switches bounce.
Explain it another way: intuitive
Like waiting for a wobbly table to stop rocking before you decide whether it leans left or right.
Explain it another way: technical
Debouncing can be done in hardware (an RC filter plus a Schmitt-trigger input) or in software (counting, timing or shift-register filters). Software debouncing should run from a regular timer tick so its timing is predictable.
Explain it another way: mathematical
Readings in a bounce window = window ÷ interval. Added latency ≈ N × interval. To reject bounces up to b ms, need N × interval > b.
Explain it another way: applied
Keyboards, lift-call buttons and rotary knobs on cookers all debounce their switches, usually in firmware, with a few to a few tens of milliseconds of filtering.
Try these examples
Example 1
A switch bounces for up to 8 ms. Your loop reads every 2 ms. How many identical readings should the debouncer require?
The worked solution is in the online lesson.
Common mix-ups
Bouncing means the button is faulty.
✓ Every mechanical switch bounces a little. Firmware or a small filter circuit must allow for it.More debouncing is always safer.
✓ Too much filtering makes buttons feel slow and can miss short presses. Match it to the switch.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A button can bounce for 30 ms after it is pressed. Your loop reads the pin once every 1 ms. How many readings fall inside that bounce window?
Answer: readings
2. A debouncer needs 5 identical readings taken every 2 ms. Roughly how long after the bouncing stops is the press accepted, in ms?
Answer: ms
3. Without debouncing, a lift-call button sometimes registers three presses. Why?
- The passenger pressed three times
- The contacts bounced and the fast loop saw each flicker as a press
- The lift motor is noisy
4. You set a debouncer to need 20 readings every 5 ms. A quick 50 ms tap is ignored. Why?
- 50 ms is shorter than the 100 ms of steady readings it demands
- The button is broken
- Debouncers ignore all short presses
5. A button can bounce for 40 ms after it is pressed. Your loop reads the pin once every 2 ms. How many readings fall inside that bounce window?
Answer: readings
Apply it
Write the counting debouncer in Python-style pseudocode as a function update(raw) that returns the accepted state. Trace it by hand on the readings 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0 with N = 3, and count the presses it reports.
Reflect
Debouncing trades speed for certainty. Where else have you seen a machine wait to be sure before acting?
Week 21: Sensor measurements
This week you will
- Describe a sensor's range, resolution, accuracy and precision.
- Turn a reading into a physical quantity using a datasheet's offset and slope.
- Convert a raw reading to a physical quantity with a two-point calibration.
Range, resolution, accuracy, precision
A thermometer shows 21.37 °C. Does all that detail mean it is right?
Why it matters
Choosing a sensor means reading a datasheet full of these four words. Mix them up and you buy a sensor that shows lots of decimal places but is two degrees wrong, or one that is accurate on average but too jumpy to control a heater.
Goals
- Define a sensor's range, resolution, accuracy and precision with an example of each.
- Tell an accuracy problem (a consistent offset) from a precision problem (scatter).
- Calculate how many distinct values a sensor can report from its range and resolution.
Predict
Sensor A reads 20.0, 20.1, 19.9 °C when the true value is 22.0 °C. Sensor B reads 21.0, 23.1, 21.9 °C. Which is more precise?
- A
- B
- Neither
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Make one sensor much noisier than the other and watch how widely its readings scatter around the true position. That scatter is a precision problem. Then ask: could a sensor with tiny scatter still be wrong every time?
What the interactive shows, in words
In the fusion lab two simulated sensors measure the same position with different amounts of random noise. A noisier sensor's readings scatter more widely around the true value: lower precision. The lesson adds that a sensor can have very little scatter and still be wrong by the same amount every time: an accuracy problem.
Understand
Range and resolution
Range is the span a sensor can measure, such as −40 to 125 °C. Outside it, readings are wrong or clipped. Resolution is the smallest change it can report, such as 0.5 °C. A 0–100 °C sensor with 0.5 °C resolution can report 100 ÷ 0.5 + 1 = 201 different values.
Accuracy and precision
Accuracy is how close readings are to the true value. Precision is how close repeated readings are to each other. Picture darts: a tight cluster off-centre is precise but inaccurate; a loose spread around the bullseye is accurate on average but imprecise. Calibration fixes consistent offsets; averaging reduces scatter.
Decimal places are not truth
A display showing 21.37 °C has fine resolution, but if the datasheet says ±2 °C accuracy, the true value could be anywhere from about 19.4 to 23.4 °C. Always report a measurement with an honest uncertainty, and never trust digits beyond what the datasheet promises.
Explain it another way: intuitive
Range: how big a ruler. Resolution: how fine the marks. Accuracy: whether the ruler starts at zero. Precision: whether your hand shakes.
Explain it another way: technical
Datasheets give range, resolution, accuracy (often ±x over a temperature range), repeatability and noise (often as a standard deviation). Systematic error (bias) shifts every reading; random error (noise) scatters them.
Explain it another way: mathematical
Distinct values = range ÷ resolution + 1. Averaging N independent noisy readings reduces random scatter by about √N; it does nothing to a fixed bias.
Explain it another way: applied
A greenhouse controller needs good precision (stable readings so the heater does not chatter) and adequate accuracy (±1 °C is fine for seedlings). A medical thermometer needs both much tighter.
Try these examples
Example 1
A distance sensor measures 2 cm to 400 cm with 1 cm resolution and ±3 cm accuracy. It reports 150 cm. What can you honestly say?
The worked solution is in the online lesson.
Common mix-ups
More decimal places means a more accurate sensor.
✓ Decimal places show resolution. Accuracy is a separate figure on the datasheet.Accuracy and precision are the same thing.
✓ Precision is agreement between readings; accuracy is closeness to the truth.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Every reading from a scale is exactly 200 g too heavy. What kind of problem is that?
- Poor precision
- Poor accuracy (a consistent offset)
- Poor range
2. A sensor covers 0 to 50 °C with a resolution of 0.25 °C. How many distinct values can it report?
Answer:
3. A sensor with ±1.5 °C accuracy reads 18.0 °C. What is the lowest temperature the true value could be, in °C?
Answer: °C
4. Which problem does averaging many readings reduce?
- A constant offset
- Random scatter (noise)
- A sensor used outside its range
5. You need to measure a freezer at −18 °C. Which sensor range should you rule out?
- −40 to 125 °C
- 0 to 100 °C
- −55 to 150 °C
Apply it
Find (or imagine) three readings from a kitchen or bathroom thermometer and a phone weather app for the same room. Decide which is more precise and which you think is more accurate, and what experiment would tell you for sure.
Reflect
Which matters more for the greenhouse project at the end of term: precision or accuracy? Why?
Reading the datasheet line
A temperature sensor says 750 mV. The datasheet has one line of maths. What is the temperature?
Why it matters
Many sensors are designed so their output is a straight line in the thing they measure. The datasheet gives you two numbers, an offset and a slope, and the firmware's job is one line of algebra. Get it wrong and your greenhouse thinks it is 50 °C in winter.
Goals
- Write a sensor's output as a straight line: output = offset + slope × quantity.
- Rearrange the line to turn a reading back into a physical quantity, with units.
- Check a conversion by putting the answer back into the original formula.
Predict
A sensor outputs 500 mV at 0 °C and rises by 10 mV for each 1 °C. It reads 750 mV. What is the temperature?
- 75 °C
- 25 °C
- 7.5 °C
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Focus on stages 1 and 2. Move the temperature and watch the sensor output change. Write down the millivolts at 0 °C, 10 °C and 20 °C. What is the pattern?
What the interactive shows, in words
The pipeline diagram starts with a temperature slider. Stage 2 shows the sensor output in millivolts using 500 mV + 10 mV per °C: 500 mV at 0 °C, 600 mV at 10 °C, 700 mV at 20 °C. The output rises by the same amount for every degree, so it is a straight line.
Understand
Offset and slope
A linear sensor's output is output = offset + slope × quantity. The offset is the output when the quantity is zero; the slope is how much the output changes per unit. A TMP36-style sensor has an offset of 500 mV (so it can show temperatures below 0 °C) and a slope of 10 mV per °C. An LM35-style sensor has 0 mV offset and 10 mV per °C.
Undo it in firmware
Firmware reads the output and needs the quantity, so it rearranges: quantity = (output − offset) ÷ slope. Subtract first, then divide. Doing it in the wrong order is one of the most common sensor bugs.
def temp_c(mv):
return (mv - 500) / 10Units are your safety net
Keep units on every number: (750 mV − 500 mV) ÷ (10 mV/°C) = 25 °C. The mV cancel, leaving °C. If the units come out as mV² or °C/mV, the formula is upside down.
Explain it another way: intuitive
It is like a taxi fare: a fixed starting charge plus a price per kilometre. To find the distance from the fare, first remove the starting charge, then divide by the price per kilometre.
Explain it another way: technical
Datasheet transfer functions are often linear over a stated range with a stated error. Real sensors may need a two-point or multi-point calibration (next lesson) to remove part-to-part offset and slope differences.
Explain it another way: mathematical
y = c + m·x ⇒ x = (y − c)/m. This is the straight-line equation with intercept c and gradient m.
Explain it another way: applied
Pressure sensors in car tyres, light sensors in phones and current sensors in chargers all specify a linear transfer function like this.
Derivation: Rearranging a sensor line
Datasheet form: V = V₀ + k × T, with V₀ the output at 0 °C and k the millivolts per °C.
Subtract V₀ from both sides: V − V₀ = k × T.
Divide both sides by k: T = (V − V₀) ÷ k.
Example (TMP36-style, V₀ = 500 mV, k = 10 mV/°C): V = 620 mV gives T = (620 − 500) ÷ 10 = 12 °C.
Check: 500 + 10 × 12 = 620 mV. ✓
Try these examples
Example 1
An MCP9700A-style sensor gives 400 mV at 0 °C and 19.5 mV per °C. It reads 790 mV. Temperature?
The worked solution is in the online lesson.
Common mix-ups
Divide the reading by the slope and you are done.
✓ Subtract the offset first. Only sensors with zero offset can skip that step.Every sensor of the same type has exactly the datasheet numbers.
✓ Datasheet values are typical. Individual parts differ slightly, which is why calibration exists.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A temperature sensor outputs 400 mV at 0 °C and rises by 19.5 mV for every 1 °C. It reads 205 mV. What temperature is it measuring, in °C?
Answer: °C
2. A temperature sensor outputs 500 mV at 0 °C and rises by 10 mV for every 1 °C. It reads 980 mV. What temperature is it measuring, in °C?
Answer: °C
3. A TMP36-style sensor (500 mV at 0 °C, +10 mV per °C) is at −15 °C. What does it output, in mV?
Answer: mV
4. Firmware computes `temp = mv / 10 - 500` for a 500 mV-offset, 10 mV/°C sensor. At 750 mV, what does it get, and what is wrong?
- 25: nothing is wrong
- −425: it divides before subtracting the offset
- 75: it ignores the offset
5. Which formula has units that work out to °C?
- (mV − mV) × (mV/°C)
- (mV − mV) ÷ (mV/°C)
- (mV/°C) ÷ (mV − mV)
Apply it
Write a Python function for each of the three sensor types in this lesson (TMP36-style, MCP9700A-style, LM35-style) that converts millivolts to °C. Test each one with assert statements at two temperatures you work out by hand.
Reflect
How would you notice, from the readings alone, that firmware was using the wrong offset?
Two-point calibration
Your cheap sensor reads 118 in melting ice and 870 in boiling water. Can two cups of water turn it into a thermometer?
Why it matters
Real sensors differ from their datasheets and from each other. Calibration measures your actual sensor against things whose values you know, so your machine reports the truth. It is how scientific instruments, kitchen scales and weather stations are kept honest.
Goals
- Convert a raw reading to a physical quantity with a two-point calibration.
- Calculate the calibration's slope and offset from two reference points.
- Explain why calibration points should span the range you care about.
Safety: Simulation only. Boiling water scalds: in the apply challenge, use safe reference temperatures and a trusted thermometer instead.
Predict
A sensor reads 100 counts at 0 °C and 900 counts at 100 °C. It now reads 500. Assuming a straight line, what is the temperature?
- 50 °C
- 55.6 °C
- 62.5 °C
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Set the ice and boiling readings for your imaginary sensor, then move the new reading. Find the raw reading that means 18 °C. Then drag the new reading below the ice point: what does the readout warn you about?
What the interactive shows, in words
The calibration diagram plots raw count (0–1023) against temperature. Two green points mark the ice reading at 0 °C and the boiling reading at 100 °C; a straight blue line joins them and extends beyond. Moving the new-reading slider places an orange point on the line and states its temperature, using slope = 100 ÷ (boiling − ice) and T = (reading − ice) × slope. Readings outside the two points are flagged as extrapolation.
Understand
Two known points fix a line
If the sensor is linear, two readings at known values fix its line. Melting ice is close to 0 °C and boiling water about 100 °C at sea level (lower at altitude), which makes them handy references. The slope is the true change divided by the raw change; then any reading converts by T = T₀ + slope × (raw − raw₀).
Interpolate, don't extrapolate
Between the two points (interpolation) the line is usually trustworthy. Beyond them (extrapolation) small curvature in the real sensor grows into big errors. So choose reference points that bracket the range you care about: for a greenhouse, perhaps 5 °C and 35 °C rather than 0 and 100.
Calibration in firmware
Store the two raw readings, measured once per sensor, and convert every reading:
R0, R1 = 118, 870 # measured in ice and boiling water
def temp_c(raw):
return 100 * (raw - R0) / (R1 - R0)Record the date and method in your notebook: a calibration is evidence.
Explain it another way: intuitive
You know two places on a map exactly. Draw a straight road between them and you can locate anything along it.
Explain it another way: technical
Two-point calibration corrects offset and gain (slope) errors. Nonlinear sensors need multi-point calibration or a lookup table. Reference conditions (pressure for boiling point, purity of ice) set the calibration's own uncertainty.
Explain it another way: mathematical
T = T₀ + (T₁ − T₀)(r − r₀)/(r₁ − r₀). Rearranged into y = mx + c: m = (T₁ − T₀)/(r₁ − r₀), c = T₀ − m·r₀.
Explain it another way: applied
Kitchen scales calibrate with a known mass; pH meters with two buffer solutions; weather stations against a reference thermometer. Each stores numbers like R0 and R1 in memory.
Derivation: The line through two points
Reference points: raw r₀ at true T₀, raw r₁ at true T₁ (here T₀ = 0 °C, T₁ = 100 °C).
Slope: m = (T₁ − T₀) ÷ (r₁ − r₀) degrees per count. For r₀ = 118, r₁ = 870: m = 100 ÷ 752 ≈ 0.1330 °C per count.
Any reading: T = T₀ + m × (r − r₀).
Example: r = 450 → T = 0 + 0.1330 × (450 − 118) = 0.1330 × 332 ≈ 44.1 °C.
Check the ends: r = 118 gives 0 °C and r = 870 gives 100 °C, as they must.
Try these examples
Example 1
Ice reads 92 counts, boiling reads 868. A reading of 310: what temperature?
The worked solution is in the online lesson.
Common mix-ups
Calibration makes a sensor perfect.
✓ It removes offset and slope errors at the calibration points. Noise, drift and curvature remain.Water always boils at 100 °C.
✓ Only at sea-level air pressure. Up a mountain it boils at a lower temperature, which shifts your calibration.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. In ice water (0 °C) your sensor reads 118 counts; in boiling water (100 °C) it reads 820 counts. A new reading is 488 counts. Assuming a straight line, what temperature is that, in °C?
Answer: °C
2. In ice water (0 °C) your sensor reads 90 counts; in boiling water (100 °C) it reads 886 counts. A new reading is 256 counts. Assuming a straight line, what temperature is that, in °C?
Answer: °C
3. A sensor reads 100 counts at 0 °C and 900 counts at 100 °C. What raw reading means 18 °C?
Answer: counts
4. You calibrated at 0 °C and 100 °C. Which reading should you trust least?
- A reading meaning 40 °C
- A reading meaning 95 °C
- A reading meaning 160 °C
5. A greenhouse must be held at 16–24 °C. Which pair of calibration points is best?
- 0 °C and 100 °C
- 10 °C and 30 °C
- 50 °C and 60 °C
Apply it
Design a calibration procedure for the greenhouse sensor: which two reference temperatures, how you would produce them safely without boiling water (for example a fridge and a warm room measured with a trusted thermometer), how many readings you would average at each, and what you would write in your notebook.
Reflect
What would you check, a month later, to know whether your calibration had drifted?
Week 22: Signals: analog, digital, sampled
This week you will
- Distinguish continuous and discrete signals and read amplitude, period and frequency (f = 1 ÷ T).
- Choose a sample rate using samples per cycle and recognise aliasing.
- Convert ADC counts to volts and to a physical quantity, and explain quantisation and noise.
Signals: smooth waves and stored numbers
Your heartbeat, the hum of a fridge and a sensor wire all wiggle over time. How do engineers describe a wiggle with just a few numbers?
Why it matters
Signals are how machines hear, feel and see: every sensor produces one. This lesson starts a thread that runs through the rest of the school, from sampling here to filters, control and communication later. It all rests on three numbers you can read off any wave.
Goals
- Distinguish a continuous (analog) signal from a discrete (digital) one.
- Read amplitude, period and frequency from a repeating signal, using f = 1 ÷ T.
- Explain why digital signals resist noise better than analog ones.
Predict
UK mains electricity repeats 50 times every second. How long does one cycle take?
- 50 ms
- 20 ms
- 2 ms
- 0.5 s
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Set the sample rate to 60 Hz and the ADC to 8 bits so the dots hug the curve. Change the signal frequency from 1 Hz to 4 Hz: count the cycles in one second each time, and read the period from the slider label. Then untick 'Show the real analog signal'.
What the interactive shows, in words
The signal lab draws one second of a smooth wave centred on 1.65 V with an amplitude of 1.2 V. You choose its frequency (the number of full cycles in that second) and the period is shown as 1 ÷ frequency. Dots show the values a computer stores. Unticking the analog curve leaves only the stored dots and the step-shaped line they make.
Understand
Continuous and discrete
An analog (continuous) signal has a value at every instant and can take any value: the voltage from a microphone, the height of a wave at sea. A digital (discrete) signal is a list of numbers: values at separate moments, each rounded to one of a fixed set of levels. Computers can only store the digital kind, so every sensor reading must be turned into numbers.
Amplitude, period, frequency
For a repeating signal: the amplitude is how far it swings from its middle (a wave from 0.45 V to 2.85 V has a middle of 1.65 V and an amplitude of 1.2 V). The period T is the time for one cycle. The frequency f is cycles per second, in hertz: f = 1 ÷ T. Resting heart rate: about 72 beats a minute = 1.2 Hz, period ≈ 0.83 s. The note A above middle C: 440 Hz, period ≈ 2.27 ms.
Why digital resists noise
Every wire picks up noise: small, random wiggles. In an analog signal the noise becomes part of the value and cannot be told apart. A digital wire only has to be read as 'high' or 'low', so a wiggle of 0.2 V on a 3.3 V logic signal changes nothing. Once a value is stored as a number it can be copied a million times without getting worse.
Explain it another way: intuitive
Analog is a ramp; digital is a staircase. You can stand anywhere on a ramp, but only on the steps of a staircase, and a staircase is easier to describe exactly: 'step 7'.
Explain it another way: technical
A sinusoid is v(t) = offset + A·sin(2πft). Peak-to-peak value = 2A. Real signals are sums of many frequencies; their noise is often described by its typical size (standard deviation) in volts.
Explain it another way: mathematical
f = 1/T and T = 1/f. In useful units: f in Hz ↔ T in ms via T = 1000/f. Amplitude A = (max − min)/2; middle = (max + min)/2.
Explain it another way: applied
An ECG machine records the heart's electrical signal (about 1 mV in size) and must find its 1–2 Hz rhythm under 50 Hz mains hum and muscle noise. Engineers describe both the wanted signal and the noise by amplitude and frequency.
Try these examples
Example 1
A light sensor's voltage swings between 0.9 V and 2.1 V and repeats every 10 ms (a flickering lamp). Middle, amplitude and frequency?
The worked solution is in the online lesson.
Common mix-ups
Digital signals are always better.
✓ The world is analog. Digital is a way to store and copy measurements reliably, but sampling and rounding lose detail if done badly.Amplitude is the distance from the bottom to the top of the wave.
✓ That is the peak-to-peak value. Amplitude is half of it, measured from the middle.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. One full cycle of a signal takes 1 ms. What is its frequency, in hertz?
Answer: Hz
2. A signal has a frequency of 440 Hz. What is its period, in milliseconds?
Answer: ms
3. A signal swings between 0.45 V and 2.85 V. What is its amplitude (half the peak-to-peak swing), in volts?
Answer: V
4. Which of these is a digital signal?
- The voltage from a microphone
- A list of temperatures recorded every minute as whole tenths of a degree
- The height of the sea against a harbour wall
5. A 3.3 V logic wire picks up 0.2 V of noise. Why does the receiving chip usually still read the right bits?
- Noise cannot reach digital wires
- It only has to decide 'near 3.3 V' or 'near 0 V', and 0.2 V is far too small to flip that decision
- Digital chips delete noise automatically from analog signals too
Apply it
Find three repeating signals in your life (a heartbeat, a ticking clock, a washing machine's spin, a flashing bike light). For each estimate the period by timing ten cycles and dividing by ten, then calculate the frequency in hertz. Record your method and uncertainty.
Reflect
Which signal from your list would be hardest for a machine to measure, and why?
Sampling: how often is often enough?
In films, a fast car's wheels sometimes seem to spin backwards. What has that got to do with a temperature sensor?
Why it matters
A digital system only knows the world at the moments it takes samples. Sample too slowly and it does not just miss detail: it sees things that are not there. Choosing a sample rate is one of the first decisions in any sensing project.
Goals
- Convert between sample rate and sample period, and count samples in a recording.
- Calculate samples per cycle and explain why fewer than two per cycle cannot represent a wave.
- Describe aliasing with an everyday example and say how engineers avoid it.
Predict
A signal goes up and down 9 times a second. You sample it 10 times a second. What wave do your samples seem to show?
- A 9 Hz wave, just a bit rough
- A slow wave of about 1 Hz
- A flat line
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Set the signal to 9 Hz and the sample rate to 10 Hz. Untick the real signal: what do the dots show? Now raise the sample rate until the readout stops warning you. How many samples per cycle did that take?
What the interactive shows, in words
In the signal lab, a 9 Hz wave sampled 10 times a second gives dots that trace a slow 1 Hz wave: the readout warns that there are fewer than 2 samples per cycle. Raising the sample rate above 18 Hz removes the warning, and around 40–60 Hz the dots clearly follow the real wave's shape.
Understand
Rate and period
The sample rate fs is samples per second (Hz); the sample period is the time between samples, 1 ÷ fs. A greenhouse logger sampling at 0.1 Hz takes one reading every 10 s; an audio recorder at 44,100 Hz takes one every 22.7 µs. Samples recorded = rate × duration: 50 Hz for 60 s gives 3,000 samples.
Samples per cycle
Divide the sample rate by the signal frequency to get samples per cycle. Ten or more show the wave's shape clearly. Between two and about five catch the frequency but the shape looks rough. Fewer than two per cycle cannot represent the wave at all. So a signal with frequency f needs a sample rate of more than 2f: half the sample rate is the highest frequency you can capture.
Aliasing and how to avoid it
When a signal is too fast for the sample rate, its samples line up into a slower, false wave: an alias. A 9 Hz wiggle sampled at 10 Hz pretends to be 1 Hz, and no maths afterwards can tell the difference. Engineers prevent it by sampling fast enough for every frequency present and by filtering out faster wiggles (like mains hum) before the ADC.
Explain it another way: intuitive
Imagine photographing a spinning fan with a flash once a second. If it spins almost exactly once between flashes, each photo shows it nearly still, creeping slowly: your photos tell a lie about its speed.
Explain it another way: technical
The Nyquist–Shannon sampling theorem: a signal containing no frequencies at or above fs/2 can be reconstructed from its samples. Anti-aliasing filters (low-pass) remove content above fs/2 before conversion.
Explain it another way: mathematical
Sample period = 1/fs. Samples per cycle = fs/f; need fs/f > 2. A sine of frequency f sampled at fs appears at |f − k·fs| for the nearest whole number k: 9 Hz at 10 Hz → |9 − 10| = 1 Hz.
Explain it another way: applied
Music is sampled at 44.1 kHz because people hear up to about 20 kHz: 44.1 > 2 × 20. A motor vibration monitor sampling too slowly can report a slow wobble that is not really there.
Try these examples
Example 1
You want to measure 50 Hz mains hum on a sensor line. What is the slowest sample rate that could possibly capture it, and what would you actually choose?
The worked solution is in the online lesson.
Example 2
A logger samples at 250 Hz for 30 s. How many samples?
The worked solution is in the online lesson.
Common mix-ups
Sampling too slowly just makes the wave a bit rough.
✓ Below two samples per cycle the samples show a different, false frequency. That is worse than roughness: it is wrong information.You can fix aliasing later with clever software.
✓ Once aliased, the false wave looks exactly like a real slow one. Prevent it with a fast enough rate and a filter before sampling.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. You sample a 1 Hz signal at 10 Hz. How many samples land in each cycle of the signal?
Answer: samples
2. A data logger samples at 1000 Hz for 2 s. How many samples does it record?
Answer: samples
3. A sensor is sampled at 200 Hz. How long is the gap between samples, in milliseconds?
Answer: ms
4. A 48 Hz vibration is sampled at 50 Hz. What frequency do the samples seem to show, in Hz?
Answer: Hz
5. A heart-rate signal contains rhythms up to 3 Hz. Which sample rate is the smallest that could work?
- 2 Hz
- 5 Hz
- 10 Hz
Apply it
Pick sample rates for three sensors in the greenhouse: air temperature (changes over minutes), a fan's speed sensor (pulses up to 40 times a second) and a microphone listening for a failing pump bearing (sounds up to 5 kHz). Justify each with the 'more than twice' rule and a margin.
Reflect
Where have you seen aliasing in real life (screens, fans, wheels, strobe lights)? Explain it with samples per cycle.
ADC counts, quantisation and noise
A 10-bit ADC says 512. A 12-bit one says 2048. Are they measuring the same voltage?
Why it matters
Every analog sensor reading passes through an ADC, and most sensor bugs are really unit-conversion bugs. Two formulas and one idea (a step) let you read any ADC datasheet and know exactly how finely your machine can sense the world.
Goals
- Convert ADC counts to volts and volts to counts, given the reference and the number of bits.
- Calculate an ADC's step size and the resulting resolution in a physical unit.
- Explain quantisation error and why extra bits do not help when noise is bigger than a step.
Predict
A 10-bit ADC with a 3.3 V reference reads 512. Roughly what voltage is that?
- 0.512 V
- 1.65 V
- 3.3 V
- 512 V
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Hold the temperature at 21.5 °C and step the ADC from 4 to 12 bits. Watch the count, the binary lamps and the temperature the firmware recovers. At how many bits does the error drop below 0.5 °C?
What the interactive shows, in words
The pipeline diagram shows five stages: the real temperature; the sensor output (500 mV + 10 mV per °C); the ADC count, also shown as binary digits; the voltage firmware calculates back (count × reference ÷ 2^bits); and the temperature firmware calculates. Changing the bits from 4 to 12 makes the steps smaller, so the recovered temperature gets closer to the real one, always within one step.
Understand
Counts and steps
An ADC compares the input with a reference voltage and reports a whole number, a count. More bits give more counts and finer steps: 8 bits = 256 steps, 10 bits = 1,024, 12 bits = 4,096. With a 5 V reference, an 8-bit step is 5 ÷ 256 ≈ 19.5 mV; a 12-bit step is about 1.22 mV. Some datasheets divide by 2ⁿ − 1 instead; the difference is under one step, but check your chip.
Quantisation is rounding
The ADC cannot report 310.3; it reports 310. That rounding is quantisation: the staircase in the signal lab. Its error is always smaller than one step, and it is the same for every reading, so you can state it in advance: '±1 step, which is 0.32 °C for this sensor'.
When noise beats bits
Real signals carry noise. If the noise wiggles by 10 mV and your step is 0.8 mV, the last few bits just record the noise: extra resolution buys nothing. Then it is better to average several readings or filter the signal. Choose bits so the step is a little smaller than the noise and much smaller than the changes you care about.
Explain it another way: intuitive
An ADC is a ruler with marks. Bits decide how many marks; the reference decides how long the ruler is. A shaky hand (noise) makes very fine marks pointless.
Explain it another way: technical
Real ADCs add offset, gain and nonlinearity errors and have an effective number of bits (ENOB) lower than the nominal count because of noise. Firmware often converts in integer millivolts: multiply before dividing to keep precision.
Explain it another way: mathematical
step = Vref/2ⁿ; V = c·Vref/2ⁿ; c = ⌊V·2ⁿ/Vref⌋ (capped at 2ⁿ − 1); resolution in physical units = step ÷ sensor slope.
Explain it another way: applied
A battery monitor with a 12-bit ADC and a 3.3 V reference sees 0.8 mV steps, plenty to track a battery draining from 4.2 V to 3.0 V (through a voltage divider) over a day.
Derivation: ADC resolution and conversions
An n-bit ADC has 2ⁿ possible counts, from 0 to 2ⁿ − 1. 10 bits → 1,024 counts (0–1,023).
It shares the reference voltage between them, so one step (1 LSB) is step = Vref ÷ 2ⁿ. 3.3 V, 10 bits: 3.3 ÷ 1,024 ≈ 3.22 mV.
Count to volts: V = count × Vref ÷ 2ⁿ. Count 310 → 310 × 3.3 ÷ 1,024 ≈ 0.999 V.
Volts to count: count = floor(V ÷ Vref × 2ⁿ). 1.00 V → floor(310.3) = 310. Every voltage in the same step gives the same count.
So the stored value can be up to one step below the truth (this lesson's ADC rounds down): that is quantisation error.
In sensor units: with a 10 mV/°C sensor, one 3.22 mV step is 0.322 °C. Each extra bit halves the step.
Try these examples
Example 1
A TMP36-style sensor (500 mV + 10 mV/°C) feeds an 8-bit ADC with a 5 V reference. It reads 38. What temperature is that, and how finely can this system measure?
The worked solution is in the online lesson.
Common mix-ups
More bits always means more accurate measurements.
✓ More bits means finer steps. Accuracy also depends on the reference, the sensor and the noise.A 10-bit ADC's biggest count is 1,024.
✓ Counts run from 0 to 1,023: that is 1,024 different values.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. What voltage does one step (1 LSB) of a 10-bit ADC with a 3.3 V reference represent, in millivolts?
Answer: mV
2. A 8-bit ADC with a 5 V reference reads 53. Using volts = count × Vref ÷ 2^n, what voltage is that, in volts?
Answer: V
3. A 10-bit ADC with a 5 V reference measures 2.94 V. What count does it report? (count = V ÷ Vref × 2^n, rounded down)
Answer: counts
4. A 10 mV per °C sensor feeds a 12-bit ADC with a 3.3 V reference. What temperature change is one ADC step worth, in °C?
Answer: °C
5. A sensor signal has about 15 mV of noise. You are choosing between a 10-bit (3.2 mV steps) and a 16-bit (0.05 mV steps) ADC. What happens with the 16-bit one?
- It measures the true value 64 times more accurately
- Its extra bits mostly record the noise; averaging or filtering would help more
- It removes the noise
6. A 10-bit ADC reads 512 and a 12-bit ADC reads 2,048, both with a 3.3 V reference. Are they measuring the same voltage?
- Yes, both about 1.65 V
- No: the 12-bit one sees four times the voltage
- Impossible to say
Apply it
For the greenhouse project, choose an ADC (8, 10 or 12 bits) and reference (3.3 V or 5 V) for a TMP36-style sensor. Show the step size in °C, the count you expect at 16 °C and 24 °C, and the Python function that turns a count into °C. Check the function with one hand calculation.
Reflect
Which mattered more today, the number of bits or the noise? When would the answer flip?
Week 23: Simple state machines
This week you will
- Describe a machine's behaviour as states, events and transitions.
- Draw and trace a state diagram for a timed sequence such as traffic lights.
- Implement a state machine in Python-style code and test it with event lists.
States, events and transitions
An automatic door is closing when someone walks up. Should it keep closing? How would a machine even know what it is doing?
Why it matters
Doors, lifts, vending machines, washing machines and game characters all remember what they are doing and react differently to the same input depending on it. A state machine is the engineer's tool for making that behaviour clear, complete and testable.
Goals
- Describe a machine's behaviour as states, events and transitions.
- Trace a state machine through a sequence of events using a transition table.
- Spot missing transitions and stuck states, especially unsafe ones.
Predict
A door is open and someone presses 'person detected'. With rules 'closed + person → opening' and 'closing + person → opening', what happens?
- It starts opening
- Nothing: no rule covers 'open + person', so it stays open
- It closes
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose the automatic door. Walk it through a whole cycle: person detected, fully open, timer ended, fully closed. Then try to trap someone: while it is closing, fire 'person detected'. Which row of the table lit up?
What the interactive shows, in words
The door state machine has states 0 Closed, 1 Opening, 2 Open, 3 Closing and events 0 Person detected, 1 Fully open, 2 Timer ended, 3 Fully closed. Rules: Closed + person → Opening; Opening + fully open → Open; Open + timer ended → Closing; Closing + fully closed → Closed; Closing + person → Opening. Any other event leaves the state unchanged. The runner lists the current state, highlights the rule that matched and keeps a log of transitions.
Understand
Three ingredients
A state is what the machine is doing now (closed, opening, open, closing). An event is something that happens (a person is detected, a limit switch reports 'fully open', a timer ends). A transition is a rule: in state S, on event E, go to state S′. The machine is in exactly one state at a time.
Tables beat tangled ifs
Write every rule as a row: from, event, to. The door needs only five rows. Anything not in the table is ignored: the state stays the same. A table lets you check every state–event pair systematically: four states × four events = 16 pairs to think about.
Complete and safe
A good state machine has no stuck states (every state has a way out) and handles every safety event in every state where it matters. 'Closing + person → opening' is the rule that stops the door shutting on someone. Engineers number states (0, 1, 2, 3) so firmware can store the current state in one variable.
Explain it another way: intuitive
A board game: your counter is on one square (the state). The dice roll (the event) and the rules decide which square you move to. Some rolls on some squares do nothing.
Explain it another way: technical
This is a finite state machine (FSM). In code it is often state = table.get((state, event), state). Moore-style machines set outputs from the state (motor on while 'opening'); Mealy-style ones set outputs on transitions.
Explain it another way: applied
Lift controllers, traffic lights, ticket barriers and phone charging circuits are all specified as state machines, and safety reviewers read their tables row by row.
Try these examples
Example 1
Start: closed (0). Events: person, fully open, person, timer ended, person, fully open. Final state?
The worked solution is in the online lesson.
Common mix-ups
The machine reacts the same way to an event every time.
✓ The reaction depends on the current state. That memory is what makes it a state machine.If a case is not in the table, the program crashes.
✓ In a well-designed machine, unlisted events are deliberately ignored, and the designer has checked that ignoring them is safe.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. An automatic door has states 0 = closed, 1 = opening, 2 = open, 3 = closing. Its events are 0 = person detected, 1 = fully open, 2 = timer ended, 3 = fully closed. Rules: closed + person → opening; opening + fully open → open; open + timer ended → closing; closing + fully closed → closed; closing + person → opening. Any other event leaves the state unchanged. The door is in state 2 and event 0 happens. What state number comes next?
Answer: state
2. An automatic door has states 0 = closed, 1 = opening, 2 = open, 3 = closing. Its events are 0 = person detected, 1 = fully open, 2 = timer ended, 3 = fully closed. Rules: closed + person → opening; opening + fully open → open; open + timer ended → closing; closing + fully closed → closed; closing + person → opening. Any other event leaves the state unchanged. The door is in state 0 and event 3 happens. What state number comes next?
Answer: state
3. Using the door rules (0 closed, 1 opening, 2 open, 3 closing), start in state 0 and apply the events: person detected, fully open, timer ended, fully closed, timer ended. Which state number do you end in?
Answer: state
4. Someone deletes the row 'closing + person → opening'. What is the danger?
- None: the door still closes
- A person walking up during closing is ignored and the door keeps closing on them
- The door will never open again
5. A vending machine has states idle, paid, vending, empty. No rule ever leaves 'empty'. What kind of problem is that?
- A stuck state: once empty it can never recover, even after refilling
- Nothing: empty machines should stop
- A noise problem
Apply it
Design a state machine for a pedestrian crossing button: states, events (button pressed, timer ended) and a transition table. Check all state–event pairs and mark any you deliberately ignore, with a reason.
Reflect
Which state–event pair in the door did you nearly forget? What would have caught it?
Timed sequences: the traffic light
A traffic light has no buttons in its basic form. What makes it change, and how do you prove it is never green both ways?
Why it matters
Timed sequences run washing machines, crossings, production lines and theatre lighting. The traffic light is the classic example because getting it wrong is so obviously dangerous, which is exactly why engineers learn to check sequences rigorously.
Goals
- Draw and trace a state diagram for a timed sequence.
- Calculate a cycle time and work out which state is showing at a given moment.
- Explain why safety states such as all-red exist and check a cycle against safety rules.
Predict
A light shows red 30 s, red-and-amber 2 s, green 25 s, amber 3 s, then repeats. How long is one full cycle?
- 55 s
- 60 s
- 30 s
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Do Level 2 of the Traffic System build: make the junction's controller as a cycle of timed states, run it, and pass the safety audit. Read every audit failure carefully: each one names a missing state or transition.
What the interactive shows, in words
The Traffic System Level 2 editor lets you list timed states for a junction (for example north–south green, amber, all red, east–west green, amber, all red, walk, flashing don't walk, all red), run the cycle, and check it against a safety audit: no conflicting greens, amber after every green, all-red before every green and walk, and every road and the crossing served.
Understand
Time is an event too
In a timed sequence the main event is 'time in this state is up'. Each state has a duration. The controller remembers the current state and when it started; when the duration has passed, it moves to the next state. UK lights go red → red-and-amber → green → amber → red.
Where are we at time t?
Add the durations to get the cycle time C. To find the state at time t, first find how far into the current cycle you are (t minus whole cycles), then lay the states end to end. With red 30, red-amber 2, green 25, amber 3 (C = 60 s): t = 95 s is 35 s into a cycle, which falls in green (32–57 s).
Safety states
A junction has two directions. Between one road's amber and the other road's green, engineers add all-red for a couple of seconds so a car that just ran the amber can clear. A safety audit checks rules such as: never two conflicting greens, amber after every green, all-red before every green. These are checkable facts about the state list.
Explain it another way: intuitive
A recipe with timings: boil for 10 minutes, then drain, then fry for 3 minutes. The kitchen timer is the event that moves you on.
Explain it another way: technical
Timed FSMs store state and an entry timestamp; on each loop pass, if now - entered >= duration[state]: state = next[state]; entered = now. Using elapsed time (not counting loop passes) keeps timing correct even if the loop speed changes.
Explain it another way: mathematical
C = Σ durations. Position in cycle: x = t mod C. State k is showing when start_k ≤ x < start_k + duration_k, where start_k is the sum of the earlier durations.
Explain it another way: applied
Real junction controllers add sensors (cars waiting, pedestrian buttons) and emergency pre-emption on top of the timed cycle, but the timed state machine and its safety interlocks remain at the core.
Try these examples
Example 1
Red 20 s, red-amber 2 s, green 15 s, amber 3 s. Which state is showing at t = 77 s?
The worked solution is in the online lesson.
Common mix-ups
If each state looks right on its own, the sequence is safe.
✓ Safety lives in the transitions: what follows what, and what never happens at the same time. Audit the whole cycle, including the wrap-around.A traffic light only needs three states.
✓ UK lights use red-and-amber as a fourth state, and real junctions add all-red clearance states.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A traffic light cycles: state 0 red for 25 s, state 1 red-and-amber for 2 s, state 2 green for 15 s, state 3 amber for 3 s, then back to red. It enters red at t = 0 s. Which state number is showing at t = 47 s? (A state that starts at exactly t is already showing.)
Answer: state
2. A traffic light cycles: state 0 red for 20 s, state 1 red-and-amber for 2 s, state 2 green for 25 s, state 3 amber for 3 s, then back to red. It enters red at t = 0 s. Which state number is showing at t = 20 s? (A state that starts at exactly t is already showing.)
Answer: state
3. A junction cycle lasts 90 s. How many complete cycles happen in one hour?
Answer: cycles
4. Why do many junctions show all-red for 2 s between one road's amber and the other road's green?
- To save electricity
- To let a vehicle that entered on amber clear the junction before the crossing traffic moves
- Because lamps need to cool down
5. A controller counts loop passes to time its states ('1,000 passes = 1 s'). Someone adds more code to the loop. What goes wrong?
- Nothing
- Each pass now takes longer, so every state lasts longer than intended
- The lights change faster
Apply it
Write the full state list for a two-road junction with a pedestrian phase (use the Traffic System Level 2 answer as a check). Calculate the cycle time and the fraction of the cycle each road gets green.
Reflect
How would you convince a sceptical council officer that your timing plan can never show two greens at once?
A state machine in twelve lines
Can a whole automatic door fit in one variable and a handful of ifs?
Why it matters
Diagrams are for thinking; code is what runs. Turning a transition table into a short, readable function is a skill you will use in every embedded project, and it makes the behaviour easy to test with a list of events.
Goals
- Implement a state machine in Python-style code with one state variable and if/elif branches.
- Trace the code by hand through a sequence of events.
- Decide which outputs belong to each state.
Predict
In code, what is the simplest way to remember which state a door is in?
- A separate true/false variable for each state
- One variable holding the state number (0–3)
- Read the motor to guess
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Run the door through the events in the worked example below while reading the code. After each button, say which `if` branch would have run.
What the interactive shows, in words
The door runner in this lesson mirrors the code: each event button calls the same rules as the step function, highlights the matching row (one row per elif branch) and logs the change. Events with no matching row leave the state unchanged, like the final 'return state' line.
Understand
The pattern
CLOSED, OPENING, OPEN, CLOSING = 0, 1, 2, 3
state = CLOSED
def step(state, event):
if state == CLOSED and event == 'person':
return OPENING
elif state == OPENING and event == 'fully_open':
return OPEN
elif state == OPEN and event == 'timer':
return CLOSING
elif state == CLOSING and event == 'person':
return OPENING
elif state == CLOSING and event == 'fully_closed':
return CLOSED
return state # anything else: no changeOne line per row of the transition table, plus a default.
Outputs follow the state
In the main loop, after updating the state, set the outputs from it: motor forwards while OPENING, backwards while CLOSING, off otherwise; start the hold-open timer when entering OPEN. Keeping outputs tied to states means you can never forget to switch the motor off.
Test with event lists
Because step is a pure function, you can test it without hardware:
s = CLOSED
for e in ['person', 'fully_open', 'timer', 'person']:
s = step(s, e)
assert s == OPENINGWrite one test for every row, and a few for events that should be ignored.
Explain it another way: intuitive
The state variable is a bookmark: it says which page of the instructions you are on, so you always know which rules apply.
Explain it another way: technical
Alternatives include a dictionary keyed by (state, event) or a match statement. Enum types give states readable names. Keep transitions and outputs separate so each can be tested.
Explain it another way: applied
Firmware for lifts and medical devices is often generated from, or checked against, a state table, and test suites replay recorded event sequences against the step function.
Try these examples
Example 1
Trace step from CLOSED with events: timer, person, fully_open, person, timer, fully_closed.
The worked solution is in the online lesson.
Common mix-ups
State machines need a special library.
✓ One variable and some if/elif branches are enough for most small machines.If it works for the normal sequence, it is tested.
✓ Test the ignored events and the unusual orders too: that is where the safety bugs live.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. state is CLOSING and the event is 'person'. Which value does `step` return?
- CLOSING
- OPENING
- CLOSED
2. An automatic door has states 0 = closed, 1 = opening, 2 = open, 3 = closing. Its events are 0 = person detected, 1 = fully open, 2 = timer ended, 3 = fully closed. Rules: closed + person → opening; opening + fully open → open; open + timer ended → closing; closing + fully closed → closed; closing + person → opening. Any other event leaves the state unchanged. The door is in state 0 and event 3 happens. What state number comes next?
Answer: state
3. What would happen if you deleted the final `return state` line?
- Nothing
- For unmatched events the function would return None, and the door would lose track of its state
- The door would open
4. The door has 4 states and 4 events. How many state–event pairs should a thorough test suite consider?
Answer: pairs
5. A learner uses `opening = True` and `closing = True` flags instead of one state variable. What new bug becomes possible?
- None
- Both flags could be true at once, driving the motor both ways
- The door runs faster
Apply it
Write step(state, event) for the pedestrian crossing you designed last lesson, then write assert tests covering every row of your table and three events that should be ignored. Trace one test by hand.
Reflect
What is one advantage of writing the transition table before writing any code?
Week 24: Actuator concepts
This week you will
- Compare DC motors, servos and steppers by how they are controlled and what they are good at.
- Convert between servo pulse width and angle, and stepper steps and angle.
- Choose an actuator and a driver for a simple task and justify the choice.
DC motors, servos and steppers
A fan, a robot's elbow and a 3D printer's nozzle all move with motors. Why do they use three different kinds?
Why it matters
Picking the wrong actuator is one of the most common early design mistakes: a DC motor where you needed a precise angle, or a stepper where you needed speed. Knowing what each one does by itself saves a project from fighting its own hardware.
Goals
- Compare DC motors, servos and stepper motors by how they are controlled and what they are good at.
- Calculate a stepper's step angle and the steps needed for a given turn.
- Match an actuator to a task and justify the choice.
Predict
You power a plain DC motor for exactly 1 second. Does it always turn exactly the same angle?
- Yes, always
- No: load, friction and battery level change how far it turns
- It does not turn at all
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Move the arm's two joint angles and watch the tip. In a real arm, each joint must reach and hold an angle you choose. As you play, ask: which actuator could do that by itself, and which would need extra sensors?
What the interactive shows, in words
The kinematics lab shows a two-joint arm; changing each joint's angle moves the tip. The lesson uses it to ask which actuator can reach and hold a chosen joint angle: a servo can by itself, a stepper can by counting steps if it never skips, and a plain DC motor needs an added position sensor and feedback.
Understand
DC motor: speed from voltage
A DC motor spins when current flows: more voltage, more speed; reverse the voltage, reverse direction. It is cheap, fast and powerful for its size, which is why fans, drills and wheels use it. But it does not know its position. To control position it needs a sensor such as an encoder and a feedback loop.
Servo: an angle on command
A hobby servo packs a small DC motor, a gearbox, a position sensor and a control circuit into one box. You send it a pulse that means an angle (next lesson), and its built-in feedback turns to that angle and holds it. Great for robot joints, steering and flaps; most hobby servos only cover about 180°.
Stepper: counted steps
A stepper motor moves in fixed steps each time its coils are switched in order. A common type has 200 steps per revolution: 360° ÷ 200 = 1.8° per step. Count steps and you know the angle without a sensor, as long as it never skips (too much load or acceleration makes it skip silently). Printers and CNC machines use steppers.
Explain it another way: intuitive
DC motor: a runner told how hard to run. Servo: a runner told which flag to stand at. Stepper: a runner told how many exact paces to take.
Explain it another way: technical
DC motor speed ≈ proportional to voltage at no load; torque rises with current. Servos use internal proportional control on angle. Steppers are open-loop position devices; microstepping divides steps further for smoother motion.
Explain it another way: mathematical
Step angle = 360° ÷ steps per revolution. Steps for angle θ = θ ÷ step angle = θ × N ÷ 360.
Explain it another way: applied
A robot vacuum uses DC motors with encoders for its wheels, a small servo or stepper for a flap, and its brushes are plain DC motors because only speed matters.
Try these examples
Example 1
A 200-step stepper drives a dial. How many steps turn it through 54°?
The worked solution is in the online lesson.
Common mix-ups
A servo is a special kind of motor that spins.
✓ A hobby servo is a motor plus gears plus a position sensor plus control electronics, built to reach and hold angles.Steppers always know where they are.
✓ They know how many steps they were told to take. If they skip, nothing tells them.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which actuator suits a desk fan best?
- A DC motor
- A hobby servo
- A stepper motor
2. A stepper with 48 steps per revolution must turn 90°. How many full steps is that?
Answer: steps
3. A stepper with 200 steps per revolution must turn 180°. How many full steps is that?
Answer: steps
4. A stepper-driven printer head is pushed too hard and skips 10 steps. What does the firmware believe?
- It notices and corrects
- It still thinks the head is where it counted, so every later move is offset
- The motor stops forever
5. A small robot arm's elbow must point at 30°, then 75°, and hold still against gravity. Which is the simplest choice?
- A plain DC motor with no sensor
- A hobby servo
- Any motor with a timer
Apply it
For a smart greenhouse, choose an actuator for (1) a vent flap that opens to 0°, 45° or 90°, (2) a circulation fan, (3) a seed tray that must move along a rail to exact positions. Justify each choice in one sentence.
Reflect
Which actuator would you most like to try on real hardware, and what would you test first?
Talking to a servo in milliseconds
A servo has just one signal wire. How do you tell it 'turn to 135°' with a single wire that is only ever on or off?
Why it matters
Servo signals are the friendliest introduction to encoding information in time: the message is not the voltage but how long the voltage stays high. The same idea underlies PWM power control next week and many sensor outputs.
Goals
- Explain how a hobby servo reads an angle from the width of a pulse.
- Convert between pulse width and angle with a linear mapping.
- Calculate the duty cycle of a 50 Hz servo signal.
Predict
A servo treats a 1.0 ms pulse as 0° and a 2.0 ms pulse as 180°. What pulse width means 90°?
- 0.5 ms
- 1.5 ms
- 9 ms
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Set the PWM frequency to 50 Hz. Find the duty cycles that give a high time of 1.0 ms, 1.5 ms and 2.0 ms per period. (Ignore the motor readout here: a servo listens to pulse width, not average voltage.)
What the interactive shows, in words
The PWM visualiser shows a square wave whose high time is the duty cycle times the period. At 50 Hz the period is 20 ms, so 5% duty gives a 1.0 ms pulse, 7.5% gives 1.5 ms and 10% gives 2.0 ms: the pulse widths a hobby servo reads as 0°, 90° and 180° in the common mapping.
Understand
A pulse every 20 ms
A hobby servo expects a pulse about every 20 ms (50 times a second). The width of each pulse carries the command. A common mapping is 1.0 ms → 0°, 1.5 ms → 90°, 2.0 ms → 180°. The voltage of the pulse is just 'high'; the information is in the time.
A straight-line mapping
Between the ends, angle and pulse width are linked by a straight line: angle = (pulse − 1.0 ms) × 180° per ms, and pulse = 1.0 ms + angle ÷ 180° × 1 ms. So each 0.1 ms is worth 18°. In Python:
def pulse_ms(angle):
return 1.0 + angle / 180Duty cycle of a servo signal
The duty cycle is the fraction of each period spent high. A 1.5 ms pulse every 20 ms is 1.5 ÷ 20 = 7.5%. The whole servo range lives between 5% and 10% duty. Microcontrollers make this signal with a timer-driven PWM peripheral, which you meet in week 25.
Explain it another way: intuitive
Morse code with one long beep: the longer the beep, the further round the servo turns.
Explain it another way: technical
The servo's control circuit converts pulse width into a target angle and runs a proportional position loop using a potentiometer on the output shaft. End-point pulse widths vary between models (some use about 0.5–2.5 ms); driving beyond the mechanical stops makes the servo strain and heat up.
Explain it another way: mathematical
angle = 180 × (p − 1)/(2 − 1) for p in ms; duty = p ÷ T × 100% with T = 20 ms.
Explain it another way: applied
Radio-control planes steer their flaps, rudders and throttles with exactly these pulses. Small robot arms and pan-tilt camera mounts often do too.
Try these examples
Example 1
What pulse width sets 45°, and what duty cycle is that at 50 Hz?
The worked solution is in the online lesson.
Common mix-ups
A servo's angle is set by the voltage on its signal wire.
✓ It is set by the pulse width. The signal is always either high or low.All servos use exactly 1–2 ms.
✓ That is a common convention; real models vary, so check the datasheet and test the ends carefully.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A hobby servo is told 1.0 ms means 0° and 2.0 ms means 180°, in a straight line between. How long a pulse sets it to 0°, in milliseconds?
Answer: ms
2. A hobby servo is told 1.0 ms means 0° and 2.0 ms means 180°, in a straight line between. It receives a pulse 1.85 ms long. What angle does it turn to, in degrees?
Answer: °
3. A servo signal has a 20 ms period and a 1.8 ms pulse. What is the duty cycle, in percent?
Answer: %
4. What carries the angle command in a hobby servo signal?
- The voltage of the pulse
- How long each pulse stays high
- How many wires are connected
5. You send a 2.6 ms pulse to a servo whose range is 1.0–2.0 ms. What is the risk?
- None
- It may try to turn past its mechanical stop, straining and heating
- It will spin forever
Apply it
Write a Python function servo_pulse(angle) that clamps the angle to 0–180°, returns the pulse width in ms, and a second function that returns the duty cycle in % at 50 Hz. Test both at 0°, 90°, 180° and at −20° and 200°.
Reflect
Why might engineers prefer to send information as a pulse width rather than as a voltage level?
Choosing an actuator, and why pins need help
Your microcontroller pin can light an LED. Can it run a 6 W motor on its own?
Why it matters
Microcontrollers decide; drivers deliver. Understanding the gap between a pin's milliamps and a motor's amps keeps chips alive, and a quick trade-off comparison turns 'I like servos' into a decision you can defend.
Goals
- Calculate a motor's current from its power and voltage, and compare it with what a pin can supply.
- Explain why motors need a driver and a separate supply.
- Choose an actuator for a task using a simple trade-off comparison.
Safety: Simulation only. Real motors can pinch fingers and their supplies can deliver large currents; work with low-voltage kits under supervision.
Predict
A 6 V motor uses 6 W. A typical pin can supply about 0.012 A in this course's model. How does the motor's current compare?
- About the same
- About 80 times more
- Less than the pin can give
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Use the trade-offs lab as an actuator chooser: imagine the options are a DC motor, a servo and a stepper. Set what matters most for a greenhouse vent (precision, cost, power use, simplicity) and see whether the winner changes when you change your priorities.
What the interactive shows, in words
The trade-offs lab scores options against weighted criteria and ranks them, with must-haves checked first. In this lesson the options stand for a DC motor, a servo and a stepper, and the criteria for precision, cost, power use and simplicity. Changing the weights can change which actuator wins.
Understand
Power, voltage, current
Electrical power is P = V × I. Rearranged, I = P ÷ V. A 12 V, 18 W pump draws 1.5 A; a 5 V, 1.5 W fan draws 0.3 A. Small motors often draw several times their running current for a moment when starting or stalled, so drivers and supplies need extra headroom.
Pins command, drivers deliver
A pin can safely supply only milliamps. Motors need amps, and they make electrical noise and voltage spikes. So the pin sends a small logic signal to a driver (a transistor or a motor-driver chip), which switches a separate supply through the motor. A diode or the driver's built-in protection catches the spike when the motor is switched off. Servos and stepper drivers follow the same idea.
A fair comparison
List what the task needs (angle or speed? holding force? cost? power?) and score each actuator against it, as in the trade-offs lab. Write down the must-haves first: a vent that must hold 45° in wind rules out a plain DC motor without a sensor, however cheap it is.
Explain it another way: intuitive
The microcontroller is a manager who gives orders in a whisper; the driver is a foreman who shouts them to a team of heavy lifters (the motor's power supply).
Explain it another way: technical
Common drivers: a logic-level MOSFET for one-direction DC motors, an H-bridge for direction control, dedicated stepper drivers with current limiting. Grounds of the logic and motor supplies are joined so the control signal has a reference.
Explain it another way: mathematical
I = P ÷ V; ratio to pin limit = I ÷ I_pin. Energy for t hours: E = P × t (Wh).
Explain it another way: applied
Robot vacuums, drones and electric bikes all separate a small logic supply from a large motor supply, with driver chips between them.
Try these examples
Example 1
A 12 V greenhouse fan is rated 3 W. Its current, and how long can it run on a 12 V, 7 Ah battery?
The worked solution is in the online lesson.
Common mix-ups
If a motor is small, a pin can power it.
✓ Even small motors draw hundreds of milliamps and spike when switched. Always use a driver.The cheapest actuator is the best choice.
✓ Must-haves come first. A cheap actuator that cannot hold an angle fails the task.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A 9 V DC motor uses 1.5 W when running. How much current does it draw, in amps?
Answer: A
2. A 5 V DC motor uses 12 W when running. How much current does it draw, in amps?
Answer: A
3. A motor draws 0.6 A. A pin is limited to 0.012 A in this model. How many times the pin's limit is that?
Answer: times
4. Why does a motor connect through a driver with its own supply?
- Drivers make motors quieter
- Pins supply only milliamps, and motors need amps and produce voltage spikes
- Microcontrollers cannot make 0 and 1
5. A greenhouse vent must hold 0°, 45° or 90°, against gusts, and the budget is tight. Which actuator is the sensible first choice?
- A plain DC motor, no sensor
- A hobby-sized servo (or a geared servo for a larger vent)
- A 3D-printer stepper with no homing switch
Apply it
Draw a block diagram of a greenhouse fan controller: microcontroller pin → driver → fan, with a separate 12 V supply and a shared ground. Label every current and voltage you know, and calculate the fan's current from its power rating.
Reflect
Which must-have in today's decisions surprised you by ruling out an option you liked?
Week 25: Timing and control sequences
This week you will
- Use a timer and prescaler to count time, and PWM to produce variable power.
- Calculate PWM duty cycle and average voltage.
- Write a non-blocking timing pattern so several tasks share one loop.
Timers: hardware that counts for you
Your loop is busy reading sensors. Who is keeping track of the time?
Why it matters
Timers are the peripheral behind every blink, every PWM signal, every timeout and every 'millis()' clock. Knowing how they count lets you predict timing exactly instead of hoping your loop runs at the right speed.
Goals
- Explain what a hardware timer and its prescaler do.
- Calculate tick rates, ticks in a time window and the time until a counter overflows.
- Choose a prescaler for a required timing resolution and range.
Predict
A 16 MHz clock feeds a timer through a prescaler of 64. How many times a second does the timer count?
- 16,000,000
- 250,000
- 64
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Ignore the tasks for now and use the timer readout. Scrub to 1 ms, 100 ms and 1,000 ms with a prescaler of 64, then 1,024. When does the 16-bit counter overflow for each prescaler?
What the interactive shows, in words
The timing scrubber includes a timer readout: with a 16 MHz clock and the chosen prescaler (1, 8, 64, 256 or 1,024), it shows the tick rate (16,000,000 ÷ prescaler), the ticks counted by the scrubbed time, and how many times a 16-bit counter (65,536 values) has overflowed.
Understand
A counter in hardware
A timer is a peripheral that adds 1 to a counter on every tick, whatever the CPU is doing. Firmware reads the counter to know how much time has passed, or asks the timer to raise a flag (or an interrupt) when it reaches a value. Because it is hardware, its timing does not wobble when the loop gets busy.
The prescaler
Counting at the full 16 MHz would fill a 16-bit counter in about 4 ms. A prescaler divides the clock first: ÷8, ÷64, ÷256, ÷1,024 are common. Dividing by 64 gives 4 µs ticks and about 0.26 s before overflow; dividing by 1,024 gives 64 µs ticks and about 4.2 s.
Overflow and wrap-around
A 16-bit counter can only hold 65,536 values (0–65,535). One tick after 65,535 it wraps back to 0: an overflow. Firmware either counts overflows to extend the range, or measures intervals with subtraction that copes with wrap-around (week 25's non-blocking pattern does this with a 32-bit millisecond clock).
Explain it another way: intuitive
A timer is a turnstile clicker at a stadium gate: it counts by itself while the manager does other jobs. The prescaler is only clicking for every 64th person, so the clicker fills up more slowly.
Explain it another way: technical
Timers can count up to a compare value and reset (clear-on-compare), toggle a pin, capture the count when an input changes, or generate PWM. Arduino-style millis() uses a timer overflow interrupt to keep a 32-bit millisecond count.
Explain it another way: mathematical
ticks = f_clock·t/prescaler; t_overflow = 2^bits·prescaler/f_clock; resolution = prescaler/f_clock.
Explain it another way: applied
A washing machine's controller uses one timer for its motor PWM, another for its 1 ms system clock, and counts minutes for each wash stage from that clock.
Derivation: Ticks, prescalers and overflow
Tick rate: f_tick = f_clock ÷ prescaler. 16 MHz ÷ 64 = 250,000 ticks per second.
Ticks in a time t: ticks = f_tick × t. In 20 ms: 250,000 × 0.020 = 5,000 ticks.
Resolution (time per tick) = 1 ÷ f_tick = 4 µs.
A 16-bit counter holds 0 to 65,535 and then wraps to 0: it overflows every 65,536 ÷ f_tick seconds = 65,536 ÷ 250,000 ≈ 0.262 s.
Bigger prescaler: coarser ticks but a longer time before overflow. Choose the smallest prescaler whose range covers the longest interval you need.
Try these examples
Example 1
You need to time intervals up to 2 s with a 16-bit timer on a 16 MHz clock. Which prescaler from 1, 8, 64, 256, 1,024 should you choose?
The worked solution is in the online lesson.
Common mix-ups
The CPU has to count time itself in a loop.
✓ Timers are hardware: they count on their own and the CPU just reads them.Overflow means the timer broke.
✓ Overflow is normal wrap-around. Good firmware expects it and handles it.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A timer counts at 16 MHz divided by a prescaler of 1. How many ticks does it count in 20 ms?
Answer: ticks
2. A timer counts at 8 MHz divided by a prescaler of 1024. How many ticks does it count in 10 ms?
Answer: ticks
3. A 16-bit timer counts at 16 MHz ÷ 256. How long until it overflows, in seconds? (Give 3 decimal places.)
Answer: s
4. A timer counts at 8 MHz ÷ 8. How long is one tick, in microseconds?
Answer: µs
5. What do you gain and lose by increasing the prescaler?
- Gain finer timing, lose range
- Gain range before overflow, lose timing resolution
- Gain speed of the CPU
Apply it
Plan the timers for a greenhouse controller: a 1 ms system tick, a 20 kHz fan PWM and a 10-minute logging interval. For each, choose how you would make it (prescaler, counts, or counting ticks in firmware) and show the arithmetic.
Reflect
When would a 4 µs timing resolution matter, and when would 64 µs be plenty?
PWM: dimming with an on/off switch
A pin can only be fully on or fully off. So how does it dim an LED to 30% or run a motor at half speed?
Why it matters
Pulse-width modulation is how almost every digital system controls power: LED brightness, motor speed, heater power, even the sound in cheap speakers. It wastes very little energy because the switch is always fully on or fully off.
Goals
- Define duty cycle and calculate it from the high time and the period.
- Calculate the average voltage of a PWM signal from the duty cycle and the supply.
- Explain why the PWM frequency must be fast enough for the load.
Predict
A 12 V supply is switched on for 25% of every period and off for 75%. What average voltage does a motor feel?
- 12 V
- 9 V
- 3 V
- 0.25 V
Write down your guess and your reason. The reveal is in the online lesson.
Discover
With a 12 V supply, find the duty cycle that gives 6 V average, then 3 V. Watch the motor's model speed. Then drop to 50 Hz and read what happens to an LED and a motor.
What the interactive shows, in words
The PWM visualiser draws three periods of a square wave between 0 V and the chosen supply. The wave is high for the duty-cycle fraction of each period; a dashed line marks the average, duty × supply. A simplified motor's speed is proportional to that average (no movement below 0.8 V), and an LED swatch shows brightness rising with duty. At 50 Hz the readout warns of flicker; at 20 kHz it notes the switching is above most people's hearing.
Understand
Duty cycle
PWM switches an output on and off many times a second. The period is one on-plus-off cycle; the duty cycle is the fraction of the period spent on. 2 ms on in a 10 ms period is 20% duty. 0% is always off; 100% is always on.
Average voltage
Loads that respond slowly (a motor's spinning mass, an LED seen by your eye, a heater's thermal mass) react to the average: V_avg = duty × V_high. On a 5 V pin, 60% duty acts like 3 V. Because the switch is either fully on (tiny voltage across it) or fully off (no current), very little power is wasted as heat.
Fast enough, but not too fast
The PWM frequency must be fast compared with the load. At 50 Hz an LED flickers and a motor can judder. LEDs are typically driven at hundreds of hertz or more; motors at a few kilohertz to about 20 kHz, the upper end being above most people's hearing so the whine disappears. Too fast and the switching itself starts to waste energy in the driver.
Explain it another way: intuitive
Flick a light switch on and off very fast and the room looks dimmer. Keep it on longer in each flick and it looks brighter.
Explain it another way: technical
Timers generate PWM in hardware: the counter runs from 0 to TOP (setting the period) and the pin flips when it passes a compare value (setting the duty). Resolution is TOP + 1 steps of duty. Motor drivers add a freewheeling path so current keeps flowing smoothly during the off-time.
Explain it another way: mathematical
D = t_on/T; V_avg = D·V_high; f = 1/T. With a timer TOP of 255, duty steps are 1/256 ≈ 0.39%.
Explain it another way: applied
A drone's speed controllers, a laptop's screen backlight and an electric toothbrush all use PWM, at frequencies chosen so you neither see nor hear the switching.
Derivation: Average voltage of a PWM wave
In one period T, the output is V_high for the on-time t_on and 0 V for the rest.
Duty cycle D = t_on ÷ T (as a fraction, or × 100 as a percentage).
The average over a period is the area under the wave divided by the period: (V_high × t_on + 0 × (T − t_on)) ÷ T.
So V_avg = D × V_high. 40% of 12 V = 0.40 × 12 = 4.8 V.
The frequency f = 1 ÷ T does not appear: it changes how smooth the effect is, not the average.
Try these examples
Example 1
A 1 kHz PWM signal is high for 0.35 ms each period. Duty cycle and average on a 5 V pin?
The worked solution is in the online lesson.
Common mix-ups
PWM makes the pin output a lower voltage.
✓ The pin is always at 0 V or at the supply. Only the average, felt by a slow load, is lower.Higher PWM frequency gives a higher average voltage.
✓ Only the duty cycle sets the average. Frequency sets how smooth the effect is.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A PWM output switches between 0 V and 9 V with a duty cycle of 0%. What is the average voltage, in volts?
Answer: V
2. A PWM output switches between 0 V and 3.3 V with a duty cycle of 85%. What is the average voltage, in volts?
Answer: V
3. A PWM signal has a period of 2 ms and stays high for 1 ms each period. What is the duty cycle, as a percentage?
Answer: %
4. You want an average of 4.5 V from a 12 V supply. What duty cycle is needed, in percent?
Answer: %
5. An LED driven by PWM at 20 Hz visibly flickers. What is the fix?
- Lower the duty cycle
- Raise the PWM frequency well above what eyes notice
- Use a bigger resistor
Apply it
A greenhouse fan runs from 12 V and should have three speeds: 33%, 66% and 100% of full voltage. Give the duty cycles and the average voltages, choose a PWM frequency with a reason, and write a Python function duty_for(volts) with a check that clamps the result to 0–100%.
Reflect
Why is PWM more efficient than dropping the voltage across a resistor to slow a motor?
Doing several things at once (without waiting)
Blink an LED every half second, read a sensor ten times a second and never miss a button press. With one CPU and no waiting. How?
Why it matters
Real machines juggle: the washing machine watches the door, turns the drum and counts down the wash at the same time. The non-blocking pattern is the simple trick that lets one small CPU do all of it, and it is the backbone of your term project.
Goals
- Write a non-blocking timing pattern so several tasks share one loop.
- Calculate how many times a periodic task runs in a time window.
- Explain why delay() blocks other tasks and how elapsed-time checks avoid it.
Predict
A task should run every 100 ms, first at t = 0. How many times has it run by t = 1,000 ms, counting a run exactly at 1,000 ms?
- 10
- 11
- 100
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Compare the two loop styles across the full 2,000 ms. In the non-blocking loop, count the sensor reads by 1,000 ms and check the two button presses are noticed. Then explain, in one sentence, why the blocking loop misses them.
What the interactive shows, in words
The timing scrubber compares two loops over 2,000 ms. The blocking loop (toggle LED, read sensor, read button, delay 500 ms) runs every job only every 500 ms and misses two short button presses at 230–300 ms and 1,240–1,290 ms. The non-blocking loop runs the LED every 500 ms, the sensor every 100 ms and the button every 20 ms, so by 1,000 ms it has read the sensor 11 times and notices both presses.
Understand
Check the clock, don't wait for it
Instead of delay(500), each task remembers when it last ran. Every pass of the loop asks 'has enough time passed?' and only then does the work:
last_blink = 0
while True:
now = millis()
if now - last_blink >= 500:
last_blink += 500
toggle_led()
if now - last_read >= 100:
last_read += 100
read_sensor()
check_button() # every passWhy subtraction?
now - last >= period measures elapsed time, which keeps working even when the millisecond counter wraps around past its largest value (with unsigned integer maths in C). Adding the period to last (rather than setting last = now) stops small delays piling up, so a 500 ms blink stays at 500 ms on average.
Tasks are tiny state machines
Each task's 'last run time' is its memory, like a state. Longer jobs (a wash stage, a door opening) become state machines whose transitions fire on elapsed time or sensor events. Nothing ever waits, so every task gets a turn within a millisecond or two.
Explain it another way: intuitive
A chef with three pans does not stare at one pan for ten minutes. They glance at each pan's timer in turn and act only on the pan that is ready.
Explain it another way: technical
This is cooperative multitasking in a super-loop. It requires every task to return quickly. Jitter (lateness) equals at most one loop pass. For hard deadlines, timers and interrupts take over; for many tasks, an RTOS schedules them.
Explain it another way: mathematical
Runs of a task with period p in [0, T], starting at 0: ⌊T/p⌋ + 1. Worst-case lateness ≈ the longest loop pass.
Explain it another way: applied
A washing machine's firmware checks the door switch every pass, updates the motor PWM every millisecond, and ends each wash stage on elapsed minutes or a water-level reading, all without one delay.
Try these examples
Example 1
Tasks every 20 ms, 100 ms and 500 ms run from t = 0. How many total task runs by t = 1,000 ms?
The worked solution is in the online lesson.
Common mix-ups
To do two things at once you need two processors.
✓ One CPU can interleave many short tasks so quickly that they all appear simultaneous.Non-blocking code never runs late.
✓ A task can be late by up to one loop pass. Keep passes short and measure them.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A non-blocking loop runs a task every 250 ms, the first time at t = 0 ms. Counting that first run, how many times has the task run by t = 25 ms (including a run exactly at 25 ms, if one is due)?
Answer: runs
2. A non-blocking loop runs a task every 20 ms, the first time at t = 0 ms. Counting that first run, how many times has the task run by t = 825 ms (including a run exactly at 825 ms, if one is due)?
Answer: runs
3. A loop calls `delay(1000)` once per pass. What is the main problem when you add a safety button?
- The button is only checked once a second, so a short press can be missed
- delay uses too much memory
- The LED gets brighter
4. Why write `last += 500` instead of `last = now` when a task runs?
- It is shorter
- It keeps the long-run timing exact even if a run happens a little late
- It makes the loop faster
5. One loop pass takes at most 3 ms. A task is due at t = 400 ms and the loop checks at 399 ms. At the latest, by how many ms is the task late?
Answer: ms
Apply it
Do Level 2 of the Washing Machine build to choose how each stage ends. Then write the non-blocking main loop for its controller in Python-style pseudocode: check the door every pass, update the drum PWM every 1 ms, and end each stage on elapsed time or the sensor condition you chose.
Reflect
Which of your future project's tasks must run every pass, and which can wait their turn?
Week 26: Introduction to feedback
This week you will
- Distinguish open-loop from closed-loop control in real machines.
- Choose on/off thresholds with hysteresis for a noisy sensor.
- Apply the proportional rule (effort = gain × error) and predict the leftover error.
Open loop or closed loop?
A toaster with a timer and an oven with a thermostat both heat things up. Only one of them knows whether it worked. Which?
Why it matters
Feedback is the idea that turns a machine from following orders blindly into correcting itself. It keeps planes level, rooms warm and lifts stopping exactly at floors. Everything you have built this term (sensors, decisions, actuators, timing) comes together in a feedback loop.
Goals
- Distinguish open-loop from closed-loop control in real machines.
- Name the setpoint, measurement, error and actuator in a feedback loop.
- Explain what a closed loop can correct that an open loop cannot.
Predict
A motor is told to run at 60% power for 10 s to move a cart 2 m. Someone loads the cart with bricks. What happens?
- It still moves exactly 2 m
- It moves less than 2 m and nothing notices
- It speeds up to compensate
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start with all gains at zero except a small proportional gain. Watch the output move towards the setpoint. Then add a disturbance or change the setpoint and see the controller respond. Finally set the gain to zero: what does 'no feedback' look like?
What the interactive shows, in words
The feedback lab shows a setpoint line and the system's output over time. With a proportional gain, the output moves towards the setpoint and responds when the setpoint or a disturbance changes. With all gains at zero the controller does nothing, so the output never corrects: no feedback.
Understand
Open loop: act and hope
In open-loop control the command is decided in advance: run the toaster for 2 minutes, run the motor at 60%. It is simple and cheap, and fine when conditions never change. But it cannot notice a disturbance (thicker bread, a heavier cart) or its own mistakes.
Closed loop: measure and correct
In closed-loop (feedback) control a sensor measures the result, the controller compares it with the setpoint (the target) to get the error = setpoint − measurement, and adjusts the actuator to shrink the error. Then it measures again, every loop pass. A thermostat, cruise control and a self-balancing robot all do this.
What feedback buys, and costs
Feedback rejects disturbances and copes with machines that are not quite what you expected. The cost is a sensor, more design, and new risks: a badly tuned loop can overshoot, oscillate or, with a broken sensor, act on nonsense. That is why the noise and calibration work earlier this term matters.
Explain it another way: intuitive
Walking to a door with your eyes shut is open loop. Walking with your eyes open, constantly correcting your direction, is closed loop.
Explain it another way: technical
Block diagram: setpoint r → (compare) → error e = r − y → controller → actuator → plant → output y → sensor → back to compare. Disturbances enter at the plant; sensor noise enters on the feedback path.
Explain it another way: applied
An automatic oven measures its air temperature and switches its element on and off to hold the setpoint; a toaster with only a timer does not measure the toast at all.
Try these examples
Example 1
Classify: (a) a washing machine filling for exactly 90 s, (b) a washing machine filling until a level sensor trips, (c) a sprinkler on a timer.
The worked solution is in the online lesson.
Common mix-ups
Closed-loop control is always better.
✓ Open loop is cheaper and perfectly good when conditions are steady. Feedback adds sensors, tuning and new failure modes.A machine with a sensor is closed loop.
✓ Only if the sensor's reading changes the command. A sensor that only displays a value leaves the loop open.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A toaster pops after a fixed time whatever the bread is like. What kind of control is that?
- Open loop
- Closed loop
2. In a greenhouse heater loop, what is the 'error'?
- The heater's power
- Setpoint minus measured temperature
- The thermometer
3. The setpoint is 18 °C and the thermometer reads 15.5 °C. What is the error, in °C?
Answer: °C
4. A closed-loop heater's thermometer falls off the wall and reads 0 °C. What does the controller do?
- Switches off safely
- Heats flat out, because it thinks it is freezing
- Nothing
5. A proportional heater controller uses effort = gain × error, where error = setpoint − temperature. The gain is 50% per °C and the effort is limited to the range 0 to 100%. The setpoint is 20 °C and the temperature is 14 °C. What heater effort does it command, in %?
Answer: %
Apply it
Find two open-loop and two closed-loop machines at home or school. For each closed-loop one, name the setpoint, sensor, error and actuator. For each open-loop one, name a disturbance it cannot correct.
Reflect
Which machine in your life would you most like to close the loop on, and what sensor would it need?
On/off control and hysteresis
A heater with a single switch-point clicks on and off dozens of times a minute when the temperature hovers near it. How do real thermostats stop that?
Why it matters
Most fridges, irons, kettles and many greenhouses use on/off control because it is simple and the heater or compressor is either on or off anyway. Hysteresis is the small idea that makes it practical, and it is exactly what your term project needs.
Goals
- Describe on/off (bang-bang) control and its typical temperature swing.
- Explain how a hysteresis band reduces switching, especially with a noisy sensor.
- Choose switch-on and switch-off thresholds that meet a comfort band.
Predict
A thermostat switches on below 18.0 °C and off above 18.0 °C. The thermometer jitters by ±0.3 °C. What happens near 18 °C?
- Nothing unusual
- The heater chatters on and off rapidly as the noise crosses 18.0 °C
- The heater stays off
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Do Level 3 of the Smart Greenhouse: the vent is left open overnight and the thermometer is noisy. Set the switch-on and switch-off temperatures so the seedlings stay within 16–24 °C for all but 10 minutes and the heater switches no more than 80 times. Note the default's switch count first.
What the interactive shows, in words
Smart Greenhouse Level 3 runs a simulated night with the vent open from 22:00 to 01:00 and a noisy thermometer. You set the switch-on and switch-off temperatures (and optional smoothing). The results show minutes spent outside 16–24 °C, the number of heater switchings and the energy used. A tiny gap switches hundreds of times; a gap of about 1.5–2 °C near the bottom of the band passes.
Understand
Bang-bang control
On/off control has two outputs: full power or none. If too cold, heater on; if warm enough, heater off. The temperature therefore rises and falls around the setpoint in a sawtooth. It is cheap and robust, and the swing is often acceptable for rooms, fridges and greenhouses.
Two thresholds, not one
Hysteresis uses separate thresholds: switch on below the lower one and off above the upper one; between them, keep doing whatever you were doing. In code:
if temp < ON_BELOW:
heater = True
elif temp > OFF_ABOVE:
heater = False
# otherwise: no changeNotice it is a two-state machine: the heater's current state decides what happens in the band.
Choosing the band
A wider band means fewer switchings (less wear on relays and compressors) but a bigger temperature swing. A narrower band holds the temperature tighter but chatters with noise. A good rule: make the band clearly wider than the sensor noise, and place it so the swing stays inside the comfort range, remembering the temperature overshoots a little after each switch.
Explain it another way: intuitive
Like deciding when to put on and take off a jumper. If you swap the moment you feel a tiny bit warm or cold, you spend all day changing. So you wait until you are clearly cold, and clearly warm.
Explain it another way: technical
Hysteresis gives on/off control a limit cycle whose amplitude is set by the band plus overshoot from thermal lag. A Schmitt-trigger input does the same for noisy digital signals in hardware.
Explain it another way: mathematical
With setpoint r and total band h: on below r − h/2, off above r + h/2. For r = 18 °C, h = 2 °C: on below 17, off above 19.
Explain it another way: applied
Domestic fridges often cycle their compressor with a band of a few degrees; a greenhouse heater might use 1.5–2 °C, as in the Smart Greenhouse Level 3 answer.
Try these examples
Example 1
Seedlings must stay between 16 and 24 °C. The thermometer jitters by about ±0.3 °C, and the air overshoots by about 0.5 °C after each switch. Suggest thresholds.
The worked solution is in the online lesson.
Common mix-ups
Hysteresis makes the controller less accurate, so avoid it.
✓ It deliberately allows a small swing to stop chattering. Without it, noise wears out relays and can cause rapid cycling.The temperature stays inside the band.
✓ Thermal lag makes it overshoot both thresholds a little. Leave room for that.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A thermostat uses a setpoint of 20 °C and a total hysteresis band of 3 °C, centred on the setpoint. Below what temperature does the heater switch on, in °C?
Answer: °C
2. With 'on below 17, off above 19', the heater is ON and the temperature is 18.2 °C. What does the controller do?
- Switch off
- Keep the heater on
- Switch on
3. What do you trade when you widen the hysteresis band?
- Fewer switchings for a bigger temperature swing
- More switchings for a steadier temperature
- Nothing changes
4. A heater relay is rated for 100,000 switchings. A thermostat without hysteresis switches 350 times a night. With a 2 °C band it switches 60 times a night. How many more nights does the relay last with hysteresis? (Nights with band minus nights without, to the nearest night.)
Answer: nights
5. Your thermometer jitters by ±0.4 °C. Which band is most likely to chatter?
- 0.2 °C
- 1.5 °C
- 2.5 °C
Apply it
Pass Smart Greenhouse Level 3 and record three runs: the default thresholds, your passing thresholds, and a band that is too wide. Make a table of time outside 16–24 °C, number of switchings and energy, and write one sentence on what the gap between on and off does.
Reflect
Where else could a gap between two thresholds stop a machine from dithering? (Think about the debouncer in week 20.)
Proportional control: push harder when further away
On/off heaters are either flat out or off. What if the heater could push gently when you are nearly there?
Why it matters
Proportional control is the first step towards the PID controllers inside drones, cruise control and 3D printers. With PWM from last week, a heater or motor can deliver any fraction of full power, and the simplest good rule is to make that fraction proportional to the error.
Goals
- Apply the proportional rule effort = gain × error, with limits on the effort.
- Predict where a proportional heater settles and the leftover (steady-state) error.
- Explain how raising the gain changes the leftover error and the risk of instability.
Predict
A proportional heater has reached a steady temperature on a cold night. Is it exactly at the setpoint?
- Yes, exactly
- No, a little below: it needs some error to keep the heater on at all
- It keeps oscillating forever
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose Proportional. With the setpoint at 18 °C and outside at 5 °C, try a gain of 400 W per °C and read where it settles. Raise the gain to 1,500 and 3,000. Then switch to On/off and compare the energy and switching.
What the interactive shows, in words
The thermostat diagram plots 300 minutes of greenhouse temperature from a 12 °C start, with the setpoint, a ±1 °C band and the heater power underneath. In proportional mode the power is gain × error, limited to 0–3,000 W; the temperature settles below the setpoint at (100 × outside + gain × setpoint) ÷ (100 + gain), and the readout states that value. In on/off mode the heater is full on below the band and off above it, and the readout counts switchings.
Understand
The proportional rule
effort = Kp × error. Big error, big effort; small error, small effort; no error, no effort. With PWM, 'effort' can be a duty cycle. Two practical limits: a heater cannot cool, so negative effort is clipped to 0, and it cannot exceed full power, so large efforts are clipped to 100%. When clipped, the controller is saturated and behaves like on/off.
The leftover error
On a cold night the heater must keep supplying heat. A proportional controller only supplies heat when there is an error, so it settles where the error is just big enough: the steady-state error. More gain means less error is needed, so it settles closer. Removing the error completely needs another idea, integral action, which you meet in Level 3.
Too much gain
Real systems have delays: the heater warms up, air takes time to mix, the sensor responds slowly, and firmware samples at intervals. With a very high gain, the controller overreacts to each change and can overshoot or oscillate. Engineers raise the gain until the error is small enough and stop well before the response turns twitchy.
Explain it another way: intuitive
Braking for a red light: far away, you brake gently; close, you brake harder. Your effort follows how far you still have to go.
Explain it another way: technical
P-only control of a first-order plant with gain K gives steady-state error r/(1 + Kp·K) for a step (the Playground's formula). With delay or second-order dynamics, high Kp reduces stability margins.
Explain it another way: mathematical
u = clamp(Kp·e, 0, u_max); steady state T* = (UA·T_out + Kp·r)/(UA + Kp); error r − T* = UA(r − T_out)/(UA + Kp).
Explain it another way: applied
Smart Greenhouse Level 4 uses the same settling formula with its own greenhouse numbers: P control at Kp = 400 W/°C settles at 14.6 °C at 03:00 against an 18 °C setpoint, which is why PI control is needed to pass.
Derivation: Where a proportional heater settles
Controller: heater power P = Kp × (r − T), limited to 0–3,000 W. (r = setpoint, T = temperature, Kp in W per °C.)
Greenhouse: heat leaks out at UA × (T − T_out) watts, with UA = 100 W per °C in the model.
Steady means heat in = heat out: Kp × (r − T) = UA × (T − T_out).
Expand and collect the T terms: Kp·r + UA·T_out = (UA + Kp) × T.
So T = (UA·T_out + Kp·r) ÷ (UA + Kp). With UA = 100, T_out = 5 °C, Kp = 400, r = 18 °C: T = (500 + 7,200) ÷ 500 = 15.4 °C, 2.6 °C short.
Kp = 1,500 gives (500 + 27,000) ÷ 1,600 ≈ 17.2 °C: closer. The error shrinks as Kp grows but only reaches zero if Kp were infinite.
Try these examples
Example 1
Kp = 25% per °C, setpoint 20 °C. Efforts at 19 °C, 16 °C and 21 °C?
The worked solution is in the online lesson.
Common mix-ups
A proportional controller reaches the setpoint exactly, given time.
✓ Against a steady heat loss it settles short of the setpoint. That offset is built into the rule.Turn the gain up as high as possible.
✓ Delays in real systems make very high gains overshoot or oscillate.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A proportional heater controller uses effort = gain × error, where error = setpoint − temperature. The gain is 40% per °C and the effort is limited to the range 0 to 100%. The setpoint is 18 °C and the temperature is 16 °C. What heater effort does it command, in %?
Answer: %
2. A proportional heater controller uses effort = gain × error, where error = setpoint − temperature. The gain is 10% per °C and the effort is limited to the range 0 to 100%. The setpoint is 22 °C and the temperature is 17.5 °C. What heater effort does it command, in %?
Answer: %
3. Using T = (UA·T_out + Kp·r) ÷ (UA + Kp) with UA = 100 W per °C, T_out = 0 °C, Kp = 900 W per °C and r = 20 °C, where does the greenhouse settle, in °C?
Answer: °C
4. You double Kp. What happens to the leftover (steady-state) error?
- It doubles
- It gets smaller but does not reach zero
- It becomes exactly zero
5. At dusk the greenhouse is 8 °C below the setpoint and Kp × error is 300% of full power. What does the heater actually do?
- 300% power
- 100% power: the effort is saturated
- 0% power
Apply it
In the thermostat diagram, find the smallest gain that keeps the greenhouse within 1 °C of an 18 °C setpoint at 300 minutes with 5 °C outside. Check it against the settling formula, then compare its energy with an on/off thermostat with a 1.5 °C band.
Reflect
Proportional or on/off for the term project's greenhouse? Give one reason for each and decide.
Week 27: Sensor-driven system project
This week you will
- Design a simulated machine that reads a noisy sensor, decides with a state machine or threshold and acts.
- Test it against stated requirements, one variable at a time, and record the results.
Project: design a greenhouse that responds
A cold night, a noisy thermometer and a vent someone forgot to close. Can your controller keep the seedlings alive, and can you prove it?
Why it matters
This is where the whole term joins up: a sensor pipeline (week 21–22), decisions as a state machine (week 23), an actuator driven with timing (weeks 24–25) and feedback (week 26). Engineers call this a system design, and the evidence you collect is what makes it engineering rather than guessing.
Goals
- Design a simulated machine that reads a noisy sensor, decides with a state machine or threshold and acts.
- Write testable requirements and trace each one to a design decision.
- Draw a complete state diagram with every transition labelled and no stuck states.
Predict
Which requirement can you actually test in the simulator?
- The plants should be happy
- The air must stay between 16 and 24 °C for all but 10 minutes of the night
- The heater should be clever
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Run the default night first and write down what fails. Then sketch your controller on paper (states, thresholds, smoothing) BEFORE you change any setting, and only then try it. Keep a log of every run.
What the interactive shows, in words
Smart Greenhouse Level 3 simulates a cold night with the vent open from 22:00 to 01:00 and a noisy thermometer. You set an on/off thermostat (switch-on and switch-off temperatures and optional smoothing). Results report minutes outside 16–24 °C, heater switchings and energy, so each run can be logged against the project's requirements.
Understand
Requirements first
Start with a short list of must requirements, each with a number and a test: 'Air temperature must stay within 16–24 °C for all but 10 minutes of the simulated night.' 'The heater must switch no more than 80 times a night.' Add should requirements for nice-to-haves, such as lower energy. Every later decision should point back to a requirement.
The system on one page
Draw the pipeline: thermometer → ADC → calibration → (optional smoothing) → decision → heater driver → heater, and the greenhouse's heat loss closing the loop. Label each arrow with its units (°C, mV, counts, %, W). Note where noise enters, and how your design copes with it (a hysteresis band wider than the noise, or averaging).
A complete state diagram
Even a thermostat is a state machine: HEATING and IDLE, with transitions 'temp < on-threshold' and 'temp > off-threshold'. Add a FAULT state for an impossible reading (say below −20 °C or above 60 °C) that switches the heater off and raises an alarm. Check every state has an exit and every event is handled or deliberately ignored.
Explain it another way: intuitive
Before building a treehouse, you agree what it must hold, draw it, and decide what happens if a branch snaps. Then you build, and test it against what you agreed.
Explain it another way: technical
This is a lightweight version of systems engineering: requirements → architecture → detailed design → verification. Traceability (each requirement linked to a design element and a test) is how real teams prove a system does what it should.
Explain it another way: applied
Commercial greenhouse controllers combine exactly these parts, with more sensors (humidity, light, CO₂) and more actuators (vents, screens, misting), each specified with numbered requirements and tests.
Try these examples
Example 1
Turn 'the heater shouldn't wear out' into a testable requirement.
The worked solution is in the online lesson.
Common mix-ups
You design by trying settings until it passes.
✓ Trying is part of it, but engineers predict first, record every run and explain why the final design works.A thermostat is too simple to need a state diagram.
✓ Drawing it reveals the missing fault state and the behaviour inside the hysteresis band.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which is the best requirement for the project?
- Keep it warm enough
- The air must stay between 16 and 24 °C for at least 99% of the night
- Use the best controller
2. Your thermometer could fail and read −40 °C. What should the controller do?
- Heat flat out
- Enter a FAULT state: heater off (or a safe fixed level) and raise an alarm
- Ignore it
3. A 10-bit ADC with a 5 V reference reads 602. Using volts = count × Vref ÷ 2^n, what voltage is that, in volts?
Answer: V
4. In ice water (0 °C) your sensor reads 104 counts; in boiling water (100 °C) it reads 874 counts. A new reading is 682 counts. Assuming a straight line, what temperature is that, in °C?
Answer: °C
5. A temperature sensor outputs 0 mV at 0 °C and rises by 10 mV for every 1 °C. It reads 280 mV. What temperature is it measuring, in °C?
Answer: °C
6. The thermometer jitters by ±0.3 °C. Which design choice most directly stops the heater chattering?
- A hysteresis band clearly wider than 0.6 °C
- A faster ADC
- A bigger heater
Apply it
Term project, part 1: write your requirements (at least three musts with numbers), draw the system diagram with units on every arrow, and draw the full state diagram including a FAULT state. Then design your first controller settings and predict, in writing, how many switchings and minutes outside the band you expect.
Reflect
Which requirement was hardest to make testable, and how did you do it?
Project: test it, show the evidence
Your greenhouse passed once. Will it pass on a colder night, with a different noise pattern, or with a different setpoint?
Why it matters
A single passing run is a hopeful anecdote. A table of runs under different conditions, with the requirement next to each result, is evidence. This lesson turns your design into something another engineer would trust.
Goals
- Test a design against stated requirements and record the results in a table.
- Change one variable at a time and explain what the results show.
- Write a short design note that names one improvement and the evidence for it.
Predict
You want to know whether a wider hysteresis band saves energy. What should you change between runs?
- The band, the setpoint and the outside temperature all at once
- Only the band, keeping everything else the same
- Nothing: one run is enough
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Plan four runs before touching anything: change only the hysteresis band (0.2, 1, 2 and 3 °C) with the setpoint at 18 °C, 5 °C outside and the noisy thermometer on. Record switchings, energy and minutes outside ±1 °C for each. Then repeat one run at −5 °C outside.
What the interactive shows, in words
The thermostat diagram reports, for each run, the temperature after 300 minutes, the number of heater switchings, the energy in kWh and the minutes spent more than 1 °C from the setpoint after the first hour. Changing only the hysteresis band between runs (with the setpoint, outside temperature and noise held fixed) shows switchings falling as the band widens while the temperature swing grows.
Understand
A fair test
Decide your question ('How does the band width change switchings and energy?'), the variable you change (band width), the variables you hold (setpoint, outside temperature, noise) and what you measure (switchings, kWh, minutes outside the band). Write your prediction before running. Afterwards, compare results with the prediction honestly, including surprises.
Tables, then claims
Put every run in a table: settings, results and pass/fail against each requirement. Only make claims the table supports: 'Widening the band from 0.2 to 2 °C cut switchings from about N₁ to N₂ in this model.' Include at least one failure and what you changed afterwards: that is how the rubric's 'evidence' criterion is met.
Know the model's limits
The simulations are simplified teaching models: no sun, no wind gusts, one temperature for the whole greenhouse, perfect heaters. State those assumptions in your note. A design that only just passes in a simplified model needs a safety margin before anyone would trust it with real plants.
Explain it another way: intuitive
Like testing a paper plane: throw it several times, change one fold, throw it several more times, and compare averages, not your single best throw.
Explain it another way: technical
Verification checks the design meets its requirements in the model; validation asks whether the model and requirements match reality. Repeating runs with different noise seeds or conditions tests robustness.
Explain it another way: applied
Engineers qualifying real controllers run them across a matrix of conditions (cold and warm, low and high load, sensor faults) and keep the results as a test report.
Try these examples
Example 1
Two runs: band 0.5 °C gave 140 switchings and 11.9 kWh; band 2 °C gave 30 switchings and 12.1 kWh. What can you claim?
The worked solution is in the online lesson.
Common mix-ups
If it passed once, it works.
✓ One run can be lucky. Repeat under different conditions and report all the results.Simulation results are facts about the real world.
✓ They are facts about the model. Say which assumptions your conclusion depends on.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which plan tests whether the outside temperature affects energy use fairly?
- Change outside temperature only; keep the controller settings and noise the same
- Change outside temperature and the band together to save time
- Run once at −5 °C and guess
2. A PWM output switches between 0 V and 3.3 V with a duty cycle of 85%. What is the average voltage, in volts?
Answer: V
3. A traffic light cycles: state 0 red for 25 s, state 1 red-and-amber for 2 s, state 2 green for 20 s, state 3 amber for 3 s, then back to red. It enters red at t = 0 s. Which state number is showing at t = 58 s? (A state that starts at exactly t is already showing.)
Answer: state
4. A proportional heater controller uses effort = gain × error, where error = setpoint − temperature. The gain is 25% per °C and the effort is limited to the range 0 to 100%. The setpoint is 22 °C and the temperature is 22 °C. What heater effort does it command, in %?
Answer: %
5. You sample a 5 Hz signal at 20 Hz. How many samples land in each cycle of the signal?
Answer: samples
6. Switchings fell from 140 to 35 when you widened the band. By what percentage did they fall?
Answer: %
7. Your controller passed all three simulated nights. Which claim is honest?
- It will work in any real greenhouse
- It met the requirements in three runs of a simplified model; real conditions (sun, wind, uneven heating) are untested
- It is perfect
Apply it
Term project, part 2: run at least three simulated nights in Smart Greenhouse Level 3 (and the thermostat diagram if useful), record every run in a results table against your requirements, include at least one failure and what you changed, and write a one-page design note naming one improvement and the evidence for it.
Reflect
What is one thing your evidence cannot tell you about a real greenhouse, and how would you find out?