Electrical and Embedded Systems
Charge, circuits, power budgets, microcontrollers, pins, ADCs, PWM, buses and registers
Nine chapters that follow electricity from a single coulomb to a working embedded device. Learn what voltage and current really are, analyse series, parallel and divider circuits, budget a battery, then meet the microcontroller: its clock and timers, its pins and pull-ups, the ADC that reads sensors, PWM that drives motors, state machines that keep it organised, the buses it talks on and the registers where software touches silicon.
Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
1. Charge, current and voltage
Current is charge on the move, counted in coulombs per second. Voltage is the energy each coulomb carries, in joules per coulomb. Keep those two definitions in your pocket and most of circuit theory becomes bookkeeping. This chapter also asks why copper conducts, glass does not and silicon sits interestingly in between, and what sets the resistance of a wire: its material, its length and its thickness.
Figure 1.1. Current × time = charge; charge × volts = energy (described in words)
Three boxes in a row: 0.5 A for 60 s gives 30 C of charge, and at 9 V that charge delivers 270 J of energy. Q = I × t = 0.5 × 60 = 30 C; E = Q × V = 30 × 9 = 270 J.
Explanation
1.1 Charge on the move
A phone charger pushes about two coulombs through its cable every second. How many electrons is that, and where do they all come from?
Charge comes in coulombs
Electric charge is a property of particles: electrons carry a tiny negative charge, protons an equal positive one. Engineers count charge in coulombs (C). One coulomb is the charge of about 6.24 × 10¹⁸ electrons, so a single electron carries about 1.6 × 10⁻¹⁹ C.
Current is charge per second
Current is how much charge passes a point each second: I = Q ÷ t. Its unit, the ampere (A), means one coulomb per second. Small circuits use milliamps (mA): 1 A = 1000 mA. An indicator LED might take 10 mA; a phone charging, about 2 A.
No loop, no current
Charge only flows when there is an unbroken path from one terminal of the source, through the components and back to the other terminal. Open a switch anywhere in a single loop and the current stops everywhere, even in the wire touching the battery.
Two directions, one current
By a convention older than the discovery of the electron, conventional current is drawn from + to −. In metal wires the electrons actually drift the other way, from − to +. Both describe the same flow; circuit diagrams use conventional current.
Common mix-ups
Batteries store charge and a flat battery has run out of charge.
✓ A battery stores chemical energy. It pushes charge that is already in the wires round the loop; a flat battery has run out of energy to push with.Electrons zoom round a circuit at the speed of light.
✓ The signal travels nearly that fast, but each electron drifts very slowly. The wire is already full of them, like a pipe full of marbles.
1.2 Voltage: the energy each charge carries
A 9 V battery and a 1.5 V battery can both push the same current. So what does the '9 V' on the label actually promise?
A volt is a joule per coulomb
Voltage (potential difference) is the energy given to, or taken from, each coulomb of charge: V = E ÷ Q. So 1 V = 1 J/C. A 5 V USB supply hands 5 J to every coulomb that leaves it; a lamp with 5 V across it turns 5 J per coulomb into light and heat.
Always between two points
A voltage is a difference, like a height difference on a hill. You measure it across a component, with the meter's two probes on either side. Saying 'the voltage at this wire' only makes sense once you agree which point counts as 0 V, usually the negative terminal, called ground.
The loop rule
In a single loop, the energy each coulomb gains in the battery is all handed out by the components before it gets back. So the voltages across the components add up to the supply voltage. Engineers call this Kirchhoff's voltage law; the circuits lab shows it for any resistor values you pick.
Common mix-ups
Voltage flows through a circuit.
✓ Current flows. Voltage is a difference between two points, the push that drives the current.A higher-voltage battery always gives a bigger current.
✓ Current also depends on the resistance of the circuit. Voltage is energy per charge, not charge per second.
1.3 Conductors, insulators and why silicon
Copper and glass differ in resistivity by about a hundred billion billion times. Silicon sits in between, and that is why your phone works.
Resistivity: a property of the material
Resistivity (ρ, in ohm-metres) says how strongly a material opposes current, whatever its shape. Copper is about 1.7 × 10⁻⁸ Ω·m, glass around 10¹² Ω·m. Conductors, semiconductors and insulators are three bands on that enormous scale.
Free carriers make the difference
Current needs charges free to move. In a metal, each atom lends electrons to a shared 'sea', so there are vast numbers of free carriers. In an insulator, electrons are tightly bound. The band picture says the same thing: to move, an electron must jump an energy gap, which is zero in metals, small in semiconductors (1.1 eV for silicon) and large in insulators (about 9 eV for glass).
Semiconductors can be tuned
In pure silicon, heat lifts a few electrons across the gap, so warming it lowers its resistance. Adding a few impurity atoms per million, called doping, supplies extra carriers and cuts resistivity by millions of times. N-type doping adds electrons; p-type creates 'holes'. Joining the two makes diodes and transistors.
Why silicon?
Silicon is the second most common element in Earth's crust (it is in sand). It grows a tough, insulating oxide layer that chipmakers use to build transistors. Its gap is wide enough to work reliably when hot, yet doping controls it precisely. Germanium came first, but heat frees too many of its electrons.
Common mix-ups
Semiconductors are just bad conductors.
✓ Their resistance can be changed enormously by temperature, light and doping. That controllability is what makes them useful.All materials resist more when they get hot.
✓ Metals do, a little. Semiconductors usually resist much less when hot.
1.4 What resistance does, and what sets it
A toaster element and a phone cable can both be made of metal. Why does one glow red hot while the other stays cool?
Resistance limits current
Resistance (R, in ohms, Ω) is how strongly a component opposes current. For the same voltage, more resistance means less current. Resistance also turns electrical energy into heat: wanted in a toaster, wasted in a cable.
Material, length and thickness
A wire's resistance depends on its material (resistivity ρ), its length L and its cross-sectional area A. Long, thin, high-resistivity wire resists most. Toaster elements are nichrome, about 65 times more resistive than copper, so they heat; cables are thick copper, so they stay cool.
Numbers engineers meet
10 m of 1 mm² copper is about 0.17 Ω. A small resistor on a circuit board might be 220 Ω or 10 kΩ (10,000 Ω). Insulation on a cable is many millions of ohms. The kilohm (kΩ) and megohm (MΩ) save writing zeros.
Derivation: Why R = ρ × L ÷ A
Cut a wire into slices of equal length. Charge must pass through every slice in turn, so the slices are in series and their resistances add. Twice as long means twice as many slices: R ∝ L.
Now think of the wire as many thin strands side by side. Each strand is another path, so more strands make it easier for charge to flow. Twice the cross-section means twice as many parallel strands: R ∝ 1 ÷ A.
Put both together and include the material's own resistivity ρ: R = ρ × L ÷ A.
Units check: ρ in Ω·m, L in m, A in m² gives Ω·m × m ÷ m² = Ω. With ρ in Ω·mm²/m you can use L in metres and A in mm² directly (copper: 0.0168 Ω·mm²/m).
Common mix-ups
Resistance uses up current.
✓ Resistance limits how much current flows, but the current is the same going in and coming out. What it uses up is energy, as heat.Thicker wires have more resistance because there is more metal.
✓ More metal across the path means more routes for charge, so thicker wires have less resistance.
Examples to try
Worked solutions are in the interactive chapter online.
Charge on the move: example 1
A motor draws 0.25 A for 2 minutes. How much charge flows through it?
Charge on the move: example 2
15 C passes through a lamp in 30 s. What is the current?
Voltage: the energy each charge carries: example 1
A 1.5 V cell pushes 2 C through a torch bulb. How much energy does the bulb receive?
Voltage: the energy each charge carries: example 2
A 9 V battery drives two resistors in series. One has 4 V across it. What is across the other?
Conductors, insulators and why silicon: example 1
How many powers of ten separate the resistivity of copper (1.7 × 10⁻⁸ Ω·m) from glass (10¹² Ω·m)?
What resistance does, and what sets it: example 1
Find the resistance of 10 m of copper wire with a cross-section of 1 mm² (ρ = 0.0168 Ω·mm²/m).
What resistance does, and what sets it: example 2
The same wire is replaced by one twice as thick (2 mm²) and half as long (5 m). New resistance?
Interactive figures, in words
Figure 1.2 from “Charge on the move”
Close the switch and set 0.5 A for 10 s: how many coulombs pass? Now double the current, then double the time, and see what happens to Q. Open the switch and check every part of the loop. Switch between conventional current and electron drift and note which way each goes.
The visualiser shows a loop with a cell, a switch and a lamp. With the switch closed, the readout gives the charge Q = I × t and the equivalent number of electrons, for example 0.5 A for 10 s gives 5 C, about 3.1 × 10¹⁹ electrons. Opening the switch stops the current everywhere. Dots move clockwise for conventional current and anticlockwise for electron drift.
Figure 1.3 from “Conductors, insulators and why silicon”
Start with copper, then step through every material and watch the marker jump along the resistivity scale. Pick pure silicon and raise the temperature from 20 °C to 100 °C. Then compare pure silicon with doped silicon at the same size. Which change made the bigger difference?
The materials explorer places eight materials on a resistivity scale from 10⁻⁹ to 10¹⁴ ohm-metres: copper, aluminium and nichrome in the conductor region; germanium, pure silicon and doped silicon in the semiconductor region; glass and rubber in the insulator region. Heating copper from 20 °C to 70 °C raises its resistance about 20%; heating pure silicon over the same range cuts its resistance by more than ten times. Doped silicon conducts millions of times better than pure silicon.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Playground: Circuit fundamentals (Playground lab)
Measure the current in two places in one loop and show that it is the same everywhere in series.
Open online - Electronics Studio (Studio)
Compare a short thick wire with a long thin one of the same metal and explain the difference in resistance.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. In a single loop with a battery, a switch and three lamps, where is the current biggest?
- Next to the + terminal
- Next to the − terminal
- It is the same everywhere in the loop
- In the first lamp
Check it in “Charge on the move”
2. A heater element carries 3 A for 20 s. How much charge flows, in coulombs?
Answer: C
Check it in “Charge on the move”
3. A sensor draws 500 mA for 4 s. How much charge is that, in coulombs?
Answer: C
Check it in “Charge on the move”
4. What does '5 V' on a USB charger tell you?
- It delivers 5 coulombs every second
- Each coulomb of charge gains 5 joules of energy
- It can power exactly 5 devices
Check it in “Voltage: the energy each charge carries”
5. A 6 V battery delivers 0.5 A for 10 s. How much energy does it hand out, in joules? (First find the charge.)
Answer: J
Check it in “Voltage: the energy each charge carries”
6. Which is NOT a reason chips are made from silicon?
- It is abundant, found in sand
- It forms an excellent insulating oxide layer
- It is the best electrical conductor known
- Its conductivity can be set precisely by doping
Check it in “Conductors, insulators and why silicon”
7. You use a wire three times as long, same material and thickness. Its resistance…
- Is a third
- Stays the same
- Triples
Check it in “What resistance does, and what sets it”
8. Why are a robot's battery cables made thick?
- Thick cables look more robust
- Larger area means lower resistance, so less heating and voltage drop at high current
- Thick cables store extra charge
Check it in “What resistance does, and what sets it”
Engineering applications
Charging cables
Fast chargers push more current, so cable makers use thicker copper to keep resistance and heating down. A long, thin cable can waste noticeable power before any reaches the phone.
Why silicon
Silicon's conductivity can be changed enormously by adding tiny amounts of other elements. That controllability, not raw conductivity, is why nearly every chip is built on it.
Summary
- Current is the rate of charge flow: I = Q / t, in amperes.
- Voltage is energy per unit charge: one volt is one joule per coulomb.
- Resistance grows with length and falls with cross-sectional area, and depends strongly on the material.
Glossary
- Ohm's law
- For a resistor, the voltage across it equals the current through it multiplied by its resistance.
- Kirchhoff's current law (KCL)
- At any junction in a circuit, the total current flowing in equals the total current flowing out.
- Electrical power
- The power transferred in a component is the voltage across it multiplied by the current through it. For a resistor this can also be written I²R or V²/R.
- Short circuits and open circuits
- A short circuit is an unintended near-zero-resistance path, which lets a large current flow; an open circuit is a break in the path, which stops current entirely.
Project: Charge bookkeeping
A phone battery is labelled with its capacity in milliamp-hours and its voltage. Convert the capacity into coulombs, work out the energy it stores in joules and watt-hours, and estimate how many times it could lift a 1 kg bag through one metre with that energy.
Deliverables
- The capacity converted to coulombs
- The stored energy in joules and watt-hours
- The lifting estimate with every unit shown
References
- Anant Agarwal and Jeffrey H. Lang (2005). Foundations of Analog and Digital Electronic Circuits. Morgan Kaufmann.
- Samuel J. Ling et al. (2016). University Physics Volume 2. OpenStax. Link
2. Ohm's law and real components
For a resistor, double the voltage and the current doubles: the graph of current against voltage is a straight line whose slope is one over the resistance. Real parts add complications. Resistors come in standard values with tolerances, sensors such as thermistors and light-dependent resistors change resistance on purpose, and an LED is not a resistor at all, so it needs one in series to limit its current.
Figure 2.1. Slope = 1 / R (described in words)
Current against voltage from 0 to 5 V for two resistors. At 5 V, 100 Ω passes 50 mA and 220 Ω passes 22.7 mA; the larger resistance gives the shallower straight line, because the slope is 1 / R.
Explanation
2.1 Ohm's law: V = I × R
Measure the current through a resistor at 1 V, 2 V and 3 V. One number connects all three readings. Can you find it before the graph does?
The law
For a resistor at a steady temperature, V = I × R. Know any two of voltage (V), current (A) and resistance (Ω) and you can find the third. A 220 Ω resistor with 20 mA through it has 0.02 × 220 = 4.4 V across it.
Units are where answers go wrong
Convert first: mA ÷ 1000 → A, kΩ × 1000 → Ω. A current of 5 mA through 2.2 kΩ is 0.005 A × 2200 Ω = 11 V. Then sanity-check: does the answer have the right size and unit?
Reading the graph
Plot current against voltage. For a resistor you get a straight line through the origin: that is what 'ohmic' means. The slope is I ÷ V = 1 ÷ R, so a steeper line means a smaller resistance.
Not everything is ohmic
A filament lamp's line curves over: as it heats, its resistance rises. An LED passes almost nothing below about 1.8–2 V and then the current shoots up. For these, V ÷ I still gives 'the resistance right now', but it changes from point to point.
Derivation: One law, three forms
Start from the experimental finding: for a resistor, current is proportional to voltage, I ∝ V. The constant of proportionality is 1/R, so I = V ÷ R.
Multiply both sides by R: V = I × R.
Divide both sides of V = I × R by I: R = V ÷ I.
Units: volts = amps × ohms. If I is in mA and R in kΩ, the factors of 1000 cancel (10⁻³ × 10³), so mA × kΩ gives volts directly: 5 mA × 2.2 kΩ = 11 V.
Common mix-ups
R = V ÷ I means resistance depends on the voltage you apply.
✓ For a resistor, R is fixed: change V and I changes in proportion, so V ÷ I stays the same. Only non-ohmic parts change.Ohm's law works for every component.
✓ It describes ohmic components. Lamps, LEDs and diodes do not follow a straight line.
2.2 Real resistors, and sensors that resist
Why can you buy a 4.7 kΩ resistor but not a 4.5 kΩ one? And how can a resistor tell a robot that it is getting dark?
Preferred values
Manufacturers sell resistors in E-series steps. The E24 series has 24 values per decade (1.0, 1.1, 1.2, 1.3, 1.5, … 8.2, 9.1), each about 10% above the last, so 4.7 kΩ exists but 4.5 kΩ does not. The steps are spaced so that, with ±5% tolerance, every resistance is close to some value you can buy.
Tolerance
A resistor marked 4.7 kΩ ± 5% could really be anywhere from 4.7 × 0.95 = 4465 Ω to 4.7 × 1.05 = 4935 Ω. Good designs still work at both ends of every part's range.
Power rating
A resistor turns electrical energy into heat. Small through-hole resistors are commonly rated at 0.25 W; beyond that they overheat. Week 14 shows how to calculate the power; the circuits lab warns you when a resistor would exceed 0.25 W.
Resistors as sensors
A light-dependent resistor (LDR) is a semiconductor whose resistance falls in bright light, from tens of kilohms in the dark to hundreds of ohms in sunshine. An NTC thermistor falls in resistance as it warms. Put either in a circuit and a changing resistance becomes a changing voltage the robot can read.
Common mix-ups
A resistor marked 1 kΩ is exactly 1000 Ω.
✓ It is within its tolerance of 1000 Ω, for example 950 Ω to 1050 Ω at ±5%.Any resistor can take any current if the value is right.
✓ Each resistor has a power rating; above it, it overheats, drifts and can fail.
2.3 Keep the LED alive: current-limiting resistors
Connect a red LED straight to a 5 V supply and it may flash brightly once and never again. One resistor prevents it. Which one?
LEDs are not resistors
An LED is a diode: below its forward voltage almost no current flows, and above it the current rises extremely steeply (you saw this on the V–I plotter). On its own it cannot limit its own current, so a tiny overshoot in voltage can mean a huge, destructive current.
The resistor takes the rest
Put a resistor in series. The LED settles at about its forward voltage and the resistor takes the remainder, Vs − Vf. Because the resistor is ohmic, that voltage fixes the current: I = (Vs − Vf) ÷ R.
Pick a real value, then recheck
Calculate R, choose the next standard value up (so the current is a little less, not more), then recalculate the current and the resistor's power. Typical small indicator LEDs are rated around 20 mA; 5–15 mA is usually bright enough.
Derivation: Where R = (Vs − Vf) ÷ I comes from
Loop rule around supply, resistor and LED: Vs = V_R + Vf, where Vf is the LED's forward voltage (about 2.0 V for red, 3.0 V for blue in this model).
So the resistor's voltage is V_R = Vs − Vf.
It is a series loop, so the same current I flows through the resistor and the LED. Ohm's law for the resistor: V_R = I × R.
Combine: I × R = Vs − Vf, so R = (Vs − Vf) ÷ I.
Example: Vs = 5 V, red LED, I = 15 mA: R = (5 − 2) ÷ 0.015 = 200 Ω. The nearest standard value above is 220 Ω, giving I = 3 ÷ 220 ≈ 13.6 mA: safe and still bright.
Common mix-ups
The resistor must go on the + side of the LED.
✓ In a series loop the current is the same everywhere, so the resistor works on either side.A bigger resistor makes the LED brighter.
✓ A bigger resistor means less current, so the LED is dimmer.
2.4 Module check: when calculation meets simulation
Your calculation says 4.50 mA. The simulator says 4.49 mA. A meter on a real board might say 4.3 mA. Who is right?
Three ways to know
A calculation shows you understand the circuit. A simulation checks the arithmetic and handles circuits too tedious to solve by hand. A measurement checks reality, including everything the model left out. Agreement between all three is evidence; disagreement is a clue.
Small differences
Rounding during the calculation, standard resistor values instead of ideal ones, and resistor tolerance (±5%) all cause small differences. If your answer is within a few per cent and you can name the reason, that is a match.
Big differences
Ten times out? Look for a unit mistake (mA vs A, kΩ vs Ω). Current zero? Look for an open circuit or an LED below its forward voltage. Wildly high? Look for a short circuit or a resistor in parallel instead of series.
Meters change circuits too
An ammeter measures current, so the current must pass through it: it goes in series and has very low resistance. A voltmeter measures a difference across a part, so it goes in parallel and has very high resistance. Wire them the wrong way and you change, or even short out, the circuit you are measuring.
Common mix-ups
If the simulator disagrees with me, the simulator must be wrong.
✓ Check your units and connections first. Simulators follow the equations exactly; they are only wrong when the model or the input is.A measured value that differs from the calculation means the circuit is faulty.
✓ Small differences within tolerance are expected. Only differences you cannot explain point to a fault.
Examples to try
Worked solutions are in the interactive chapter online.
Ohm's law: V = I × R: example 1
A 9 V battery is connected across a 450 Ω resistor. What current flows?
Ohm's law: V = I × R: example 2
A sensor has 3.3 V across it and draws 1.5 mA. What is its resistance?
Real resistors, and sensors that resist: example 1
A design needs about 450 Ω. Which E24 value would you choose, and what is its 5% range?
Keep the LED alive: current-limiting resistors: example 1
A blue LED (Vf = 3.0 V) on a 5 V supply should take 10 mA. Which resistor?
Keep the LED alive: current-limiting resistors: example 2
Why is the 'next value up' safer than the 'nearest value'?
Module check: when calculation meets simulation: example 1
A student calculates 0.45 A through a 2 kΩ resistor on 9 V. The simulator shows 4.5 mA. Diagnose.
Interactive figures, in words
Figure 2.2 from “Ohm's law: V = I × R”
Choose the 220 Ω resistor. Record points at 1 V, 2 V, 4 V and 6 V and check that V ÷ I is the same each time. Do the same for the 100 Ω resistor: which line is steeper? Then try the filament lamp and the LED and record three points each. What is different about their V ÷ I?
The V–I plotter shows current (0 to 60 mA) against voltage (0 to 6 V). The 100, 220 and 470 ohm resistors give straight lines through the origin; the 100 ohm line is steepest. The filament lamp's curve bends over as its resistance rises. The LED passes almost no current below about 1.8 V, then rises steeply. Recorded points are listed in a table with V ÷ I for each.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: LED current limiting (Simulation OS experiment)
Choose the nearest standard resistor for a red LED on 5 V and check the resulting current and resistor power.
Open online - Electronics Studio (Studio)
Plot current against voltage for a resistor and for a lamp, and explain why only one is a straight line.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. There are 6 V across a 1.5 kΩ resistor. What current flows, in milliamps?
Answer: mA
Check it in “Ohm's law: V = I × R”
2. On a current-against-voltage graph, resistor X's line is steeper than resistor Y's. Which has the larger resistance?
- X
- Y
- They are equal
Check it in “Ohm's law: V = I × R”
3. A filament lamp's V–I graph curves so that equal voltage steps give smaller and smaller current steps. Why?
- The lamp is broken
- Its filament heats up and its resistance rises
- Ohm's law stops working at high voltage for everything
Check it in “Ohm's law: V = I × R”
4. A 470 Ω ± 5% resistor: what is the lowest resistance it could have, in ohms?
Answer: Ω
Check it in “Real resistors, and sensors that resist”
5. An NTC thermistor in a battery pack reads 10 kΩ at 25 °C. If the pack heats up, the reading will…
- Go above 10 kΩ
- Go below 10 kΩ
- Stay at 10 kΩ
Check it in “Real resistors, and sensors that resist”
6. A red LED (Vf = 2.0 V) runs from 5 V and should carry 15 mA. What series resistor is needed, in ohms?
Answer: Ω
Check it in “Keep the LED alive: current-limiting resistors”
7. Why must an LED never be connected straight across a 5 V supply?
- LEDs only work on AC
- Without a resistor nothing limits the current, which can rise far above the LED's rating
- It would be too dim
Check it in “Keep the LED alive: current-limiting resistors”
8. Your answer is exactly 1000 times bigger than the simulator's. The most likely cause is…
- Resistor tolerance
- Rounding
- A unit slip, such as mA vs A or kΩ vs Ω
Check it in “Module check: when calculation meets simulation”
Engineering applications
Indicator LEDs
Every power light on every gadget has a resistor beside it. Its value is picked from a standard series, then the current is recalculated to check the LED stays bright enough and well inside its rating.
Temperature sensing
Thermostats, battery packs and 3D printer hot ends use thermistors whose resistance falls as they heat. Measuring that resistance, usually through a divider, gives a cheap and robust thermometer.
Summary
- Ohm's law, V = I × R, holds for resistors; their V–I graph is a straight line with slope 1 / R.
- Resistors come in standard values with a tolerance, so real currents differ from ideal ones.
- Thermistors and LDRs are resistors that change with temperature or light, which makes them sensors.
- An LED needs a series resistor: R = (Vsupply − Vforward) / I.
Glossary
- Ohm's law
- For a resistor, the voltage across it equals the current through it multiplied by its resistance.
- LED current-limiting resistor
- An LED needs a series resistor to set its current, chosen so that the supply voltage minus the LED's forward voltage, divided by the resistance, gives the desired current.
- Resistor colour code
- Through-hole resistors show their value as coloured bands: digit bands, then a multiplier band, then a tolerance band.
- Diode forward voltage
- A diode conducts in one direction once the voltage across it reaches its forward voltage, after which its voltage stays roughly constant whatever the current.
- Measuring with a multimeter
- A multimeter measures voltage across a component (in parallel), current through a branch (in series, by breaking the circuit), and resistance on an unpowered part.
Project: An LED panel that will not burn out
Design the resistors for three LEDs of different colours on a 5 V supply, using standard resistor values. For each, compute the current at nominal, minimum and maximum resistor tolerance, and the power in the resistor. Show the design stays within every rating.
Deliverables
- The resistor choice for each LED
- A table of currents across the tolerance range
- A check of every power rating
References
- Paul Horowitz and Winfield Hill (2015). The Art of Electronics, 3rd edition. Cambridge University Press.
- Paul Scherz and Simon Monk (2016). Practical Electronics for Inventors, 4th edition. McGraw-Hill Education.
3. Series, parallel and dividers
Components in series share one current and split the voltage; in parallel they share one voltage and split the current. Those two rules, which are Kirchhoff's laws in disguise, solve most small circuits. The voltage divider, two resistors in series with a tap between them, is the workhorse of sensing: it turns a changing resistance into a changing voltage that a microcontroller can read, as long as nothing loads it too heavily.
Figure 3.1. Two resistors share the voltage (described in words)
A voltage divider: 9 V across R1 = 10 kΩ on top of R2 = 4.7 kΩ. The tap between them sits at 2.88 V, given by Vout = Vin·R2/(R1+R2), and 0.612 mA flows through both resistors.
Explanation
3.1 Series circuits: one path, shared voltage
Old strings of fairy lights went completely dark when one bulb failed. What does that tell you about how they were wired?
One path, one current
Components in series are joined end to end with no branches. Charge has only one route, so the current is identical through every part, and a break anywhere stops it everywhere. That is why the old fairy lights went dark.
Resistances add
The total resistance is the sum: R = R1 + R2 + …. Adding a resistor in series always increases the total and reduces the current.
Voltage is shared in proportion
Each resistor's voltage is V = I·R, so bigger resistors take bigger shares, and the shares add up to the supply. For 220 Ω, 470 Ω and 1 kΩ on 9 V: R = 1690 Ω, I = 9 ÷ 1690 ≈ 5.33 mA, voltages ≈ 1.17 V, 2.50 V and 5.33 V.
Derivation: Why series resistances add
In series there is only one path, so the same current I flows through every resistor.
By the loop rule, the supply voltage is shared: V = V1 + V2 + V3.
Ohm's law for each resistor: V1 = I·R1, V2 = I·R2, V3 = I·R3. So V = I·R1 + I·R2 + I·R3 = I·(R1 + R2 + R3).
The whole chain therefore behaves like one resistor with R = R1 + R2 + R3, since V = I·R.
Common mix-ups
The first resistor in a series chain gets the most current.
✓ Every resistor in series carries exactly the same current.Each resistor in series gets the full supply voltage.
✓ They share it, in proportion to their resistances.
3.2 Parallel circuits: many paths, shared current
Add another resistor to a circuit and the total resistance goes DOWN. How can more resistors mean less resistance?
Same voltage, separate paths
Components in parallel connect across the same two points, so each has the full supply voltage and its own current. Break one branch and the others carry on, which is why house lights do not all go out when one bulb fails.
Currents add, resistance falls
The supply current is the sum of the branch currents. Every extra branch is another path, so the combined resistance is smaller than the smallest branch. Two equal resistors in parallel give exactly half.
The small branch dominates
1 kΩ ∥ 10 kΩ = 10,000,000 ÷ 11,000 ≈ 909 Ω, close to the 1 kΩ. The low-resistance branch carries most of the current, so it sets the total. A very small resistor in parallel with anything is almost a short circuit.
Derivation: Why 1/R = 1/R1 + 1/R2
Each branch connects directly across the supply, so every branch has the same voltage V.
Charge splits at the junction and rejoins afterwards, so the currents add: I = I1 + I2.
Ohm's law for each branch: I1 = V/R1 and I2 = V/R2, so I = V/R1 + V/R2 = V·(1/R1 + 1/R2).
For one equivalent resistor I = V/R, so 1/R = 1/R1 + 1/R2.
For exactly two resistors this rearranges to R = R1·R2 ÷ (R1 + R2) ('product over sum'). Check: 1 kΩ ∥ 1 kΩ = 1,000,000 ÷ 2000 = 500 Ω.
Common mix-ups
Adding a resistor always increases total resistance.
✓ Only in series. In parallel it adds a path and lowers the total.Parallel branches share the supply voltage between them.
✓ Each branch gets the full supply voltage; they share the current.
3.3 Voltage dividers: turning resistance into a reading
A microcontroller cannot measure resistance, only voltage. So how does a robot know how bright the room is?
Two resistors, one share
A voltage divider is two resistors in series with the output taken from the middle. The output is the bottom resistor's share of the supply: Vout = Vin × R2 ÷ (R1 + R2). 9 V across 10 kΩ (top) and 4.7 kΩ (bottom) gives 9 × 4.7 ÷ 14.7 ≈ 2.88 V.
Sensors in dividers
Replace R2 with a light sensor (LDR). In bright light its resistance falls, so its share falls and Vout drops; in the dark Vout rises. A microcontroller reads Vout and decides 'day' or 'night'. Thermistors and force sensors work the same way.
Scaling down a big voltage
A 12 V battery is too much for a 3.3 V chip's input. A divider with R1 = 27 kΩ and R2 = 10 kΩ gives 12 × 10 ÷ 37 ≈ 3.24 V, so the chip can watch the battery safely.
Loading
Anything connected to Vout draws current and sits in parallel with R2, lowering Vout. Rule of thumb: the load should be at least ten times R2. Microcontroller inputs are usually very high resistance, so they barely load a divider.
Derivation: The divider formula
R1 and R2 are in series across Vin, so (with nothing attached to the output) the current is I = Vin ÷ (R1 + R2).
Vout is the voltage across R2: Vout = I × R2.
Substitute: Vout = Vin × R2 ÷ (R1 + R2).
Checks: if R2 = R1, Vout = Vin/2. If R2 ≫ R1, Vout → Vin. If R2 → 0, Vout → 0. Vout is always between 0 and Vin.
With a load R_L attached, R2 is replaced by R2 ∥ R_L, which is smaller, so Vout drops. Example: 10 kΩ and 10 kΩ on 5 V give 2.5 V; add a 10 kΩ load and the bottom becomes 5 kΩ, so Vout = 5 × 5 ÷ 15 ≈ 1.67 V.
Common mix-ups
Vout depends only on R2.
✓ It depends on the ratio R2 ÷ (R1 + R2): change either resistor and Vout changes.A divider is a good way to power a motor from a lower voltage.
✓ A load like a motor draws so much current that it collapses Vout. Dividers are for signals, not for power.
Examples to try
Worked solutions are in the interactive chapter online.
Series circuits: one path, shared voltage: example 1
100 Ω and 330 Ω are in series on 12 V. Find the current and the voltage across each.
Parallel circuits: many paths, shared current: example 1
A 470 Ω and a 330 Ω resistor are in parallel on 5 V. Find the combined resistance and total current.
Voltage dividers: turning resistance into a reading: example 1
R1 = 2.2 kΩ, R2 = 3.3 kΩ across 5 V. Find Vout.
Interactive figures, in words
Figure 3.2 from “Series circuits: one path, shared voltage”
Choose series with three resistors: 220 Ω, 470 Ω and 1 kΩ on 9 V. Check that the three voltages add to 9 V. Now double one resistor and predict, before looking, which voltages go up and which go down. Finally drop the supply until no resistor's power is shaded.
The series and parallel builder, in series mode with 220, 470 and 1000 ohms on 9 volts, reports a total of 1690 ohms and 5.33 mA through every resistor. The voltages are about 1.17, 2.50 and 5.33 volts, adding to 9 volts. A table lists voltage, current and power for each part and flags any above 0.25 watts.
Figure 3.3 from “Voltage dividers: turning resistance into a reading”
Set 5 V with R1 = R2 = 10 kΩ and check Vout. Switch the bottom part to the light sensor and sweep the light from 0% to 100%: which way does Vout move? Then go back to fixed resistors and attach each load in turn. Which load barely changes Vout, and which drags it down?
The divider explorer draws R1 above R2 with Vout taken from the middle and shown on a vertical meter. With 5 volts and two 10 kΩ resistors, Vout is 2.5 volts. With the LDR as the bottom part, Vout falls from about 4 volts in the dark to under 0.3 volts in bright light. Adding a 100 kΩ load barely changes Vout; a 1 kΩ load drags it down to well under half its unloaded value.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: Voltage divider under load (Simulation OS experiment)
Connect a load to the divider's tap and find the load resistance at which the output sags by 10%.
Open online - Playground: Circuit fundamentals (Playground lab)
Put two resistors in parallel and show the total is smaller than either one.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. What is the total resistance of 220 Ω, 470 Ω and 1000 Ω in series, in ohms?
Answer: Ω
Check it in “Series circuits: one path, shared voltage”
2. Two resistors, 1 kΩ and 2 kΩ, are in series on 6 V. What is the voltage across the 2 kΩ resistor, in volts?
Answer: V
Check it in “Series circuits: one path, shared voltage”
3. Two 2.2 kΩ resistors are in parallel. What is the combined resistance, in ohms?
Answer: Ω
Check it in “Parallel circuits: many paths, shared current”
4. A 100 Ω resistor and a 10 kΩ resistor are in parallel. The combined resistance is…
- About 10.1 kΩ
- Just under 100 Ω
- About 5 kΩ
Check it in “Parallel circuits: many paths, shared current”
5. In a parallel circuit of three lamps, one lamp's filament breaks. The other two…
- Go out
- Stay lit with the same brightness
- Get brighter because they share the current
Check it in “Parallel circuits: many paths, shared current”
6. A divider has R1 = 10 kΩ and R2 = 4.7 kΩ across 9 V. What is Vout, in volts?
Answer: V
Check it in “Voltage dividers: turning resistance into a reading”
7. An LDR is the bottom resistor of a divider. The room gets brighter. Vout…
- Rises
- Falls
- Stays the same
Check it in “Voltage dividers: turning resistance into a reading”
8. 10 kΩ over 10 kΩ across 5 V gives 2.5 V. A 10 kΩ load is connected to the output. What is the new Vout, in volts?
Answer: V
Check it in “Voltage dividers: turning resistance into a reading”
Engineering applications
Battery monitors
A microcontroller cannot read a 12 V battery directly. A divider scales the voltage into the ADC's range; choosing high resistances keeps the drain on the battery tiny.
Household wiring
Sockets are wired in parallel so every appliance gets the full supply voltage and one switched off does not affect the rest. Old series fairy lights did the opposite: one dead bulb darkened the string.
Summary
- Series: one current, resistances add, voltages share in proportion to resistance.
- Parallel: one voltage, currents add, and the total resistance is smaller than the smallest branch.
- Divider: Vout = Vin × R2 / (R1 + R2), valid when the load draws little current.
- A load on the tap acts in parallel with R2 and pulls the output down.
Glossary
- Resistors in series
- Resistors connected end to end, with one path for current, have a total resistance equal to the sum of their resistances. The same current flows through each.
- Resistors in parallel
- Resistors connected across the same two nodes share the same voltage; the reciprocal of their total resistance is the sum of the reciprocals.
- Voltage divider
- Two resistors in series across a supply produce, at their junction, a fraction of the supply voltage set by the ratio of the resistors.
- Kirchhoff's voltage law (KVL)
- Around any closed loop in a circuit, the sum of voltage rises equals the sum of voltage drops.
- Kirchhoff's current law (KCL)
- At any junction in a circuit, the total current flowing in equals the total current flowing out.
Project: A light meter
Design a divider with a light-dependent resistor so that a 3.3 V microcontroller sees a useful voltage range from a dim room to daylight. Choose the fixed resistor, calculate the output at both extremes, and check what a 10 kΩ input load would do to the readings.
Deliverables
- The circuit with component values
- Output voltages at the two light levels
- The effect of the load, calculated
References
- Anant Agarwal and Jeffrey H. Lang (2005). Foundations of Analog and Digital Electronic Circuits. Morgan Kaufmann.
- Paul Horowitz and Winfield Hill (2015). The Art of Electronics, 3rd edition. Cambridge University Press.
4. Power, energy and batteries
Power is volts times amps; energy is power times time. Those two lines decide whether a resistor gets warm, what an appliance costs to run and how long a battery lasts. For battery devices the trick is to stop thinking about peak current and think about the average: a sensor node that wakes for a moment, measures, transmits and sleeps can live for months on a small cell.
Figure 4.1. Average current sets the run time (described in words)
A current-against-time bar: 80 mA for 10% of the time while awake and 2 mA for the other 90% asleep. The average is 9.8 mA, so a 2000 mAh battery lasts about 204 h, about 8.5 days.
Explanation
4.1 Electrical power: how fast energy flows
A tiny resistor and a car headlight can both be 'just a resistor'. Why does one stay cool and the other burn too hot to touch?
Watts are joules per second
Power is the rate of energy transfer. P = V × I: a 5 V USB port supplying 2 A delivers 10 W, ten joules every second. A watt is small: a phone charger is a few watts, a robot drive motor tens of watts.
Pick the formula that fits your numbers
Know V and I? Use P = V·I. Know the current and resistance? P = I²·R. Know the voltage and resistance? P = V²/R. All three give the same answer for the same resistor.
Power ratings
Resistors turn all their electrical power into heat. Common small resistors are rated at 0.25 W. 470 Ω on 5 V: P = 25 ÷ 470 ≈ 0.053 W, fine. 100 Ω on 9 V: 0.81 W, too hot. Fix it with a higher-rated resistor (e.g. 1 W) or a larger resistance.
Derivation: Three formulas from one idea
Power is energy per second: P = E ÷ t, in watts (W), where 1 W = 1 J/s.
Voltage is energy per coulomb, E = V × Q, so P = V × Q ÷ t.
Charge per second is current, Q ÷ t = I, so P = V × I.
Substitute V = I × R: P = I × R × I = I² × R.
Substitute I = V ÷ R: P = V × V ÷ R = V² ÷ R. Halving V quarters the power in a fixed resistor.
Common mix-ups
A higher-power device uses more voltage.
✓ Power is voltage × current. Two devices at the same voltage can have very different power because they draw different currents.Power and energy are the same thing.
✓ Power is how fast energy is used (watts). Energy is power × time (joules or watt-hours).
4.2 Energy over time: watt-hours and what they cost
Which uses more energy in a day: a 10 W phone charger used for two hours, or a 0.25 W gadget that is never switched off?
Energy is power × time
E = P × t. With P in watts and t in seconds, E is in joules. Engineers usually use watt-hours (Wh): 1 Wh = 1 W for 1 hour = 3600 J. Electricity is sold in kilowatt-hours: 1 kWh = 1000 Wh = 3.6 million joules.
Working out a cost
Cost = energy in kWh × price per kWh. A 60 W laptop for 6 hours a day uses 360 Wh = 0.36 kWh a day, 131.4 kWh a year. At an illustrative 25 p per kWh that is about £32.85 a year. Prices vary by place and time, so always state the price you assumed.
Power is not the whole story
A big power for a short time can use less energy than a small power for a long time. Comparing devices by power alone can mislead: always multiply by how long they run.
Common mix-ups
A kilowatt-hour is a kilowatt per hour.
✓ It is a kilowatt FOR an hour: power multiplied by time, a unit of energy.Low-power devices cost nothing to run.
✓ Left on all year, small powers add up to measurable energy and cost.
4.3 Battery budgets: peak, average and run time
A robot's motors draw 1.5 A, but only for a tenth of the time. Do you size the battery for 1.5 A, or for something much smaller?
Capacity: mAh and Wh
Battery capacity is often quoted in milliamp-hours (mAh): 2000 mAh can supply 2000 mA for 1 hour, or 200 mA for 10 hours, ideally. Energy capacity in Wh = mAh × voltage ÷ 1000. A 2000 mAh, 3.7 V cell holds 7.4 Wh.
Average from a duty cycle
If a load draws a large current only part of the time, the average is current × fraction of time on. A 1.5 A motor running 10% of the time averages 150 mA. Add the constant loads: a 50 mA controller plus that motor averages 200 mA.
Peak still matters
Run time depends on the average, but the battery, wiring and regulator must survive the peak: here 50 + 1500 = 1550 mA. A battery that cannot deliver the peak will sag in voltage and may reset the controller just as the motor starts.
Common mix-ups
A battery rated 2000 mAh will always give exactly 2000 mA for an hour.
✓ That is an ideal figure. Real capacity is lower at high currents, low temperatures and as batteries age.Only the average current matters.
✓ The peak decides whether the battery, wiring and regulator can supply bursts without the voltage collapsing.
Examples to try
Worked solutions are in the interactive chapter online.
Electrical power: how fast energy flows: example 1
A 12 V robot motor draws 1.5 A. What power does it take?
Electrical power: how fast energy flows: example 2
20 mA flows through a 470 Ω resistor. Is a 0.25 W resistor enough?
Energy over time: watt-hours and what they cost: example 1
A 100 W device runs 10 hours a day for 30 days. At 25 p per kWh, what does it cost?
Battery budgets: peak, average and run time: example 1
A sensor node draws 20 mA for 1 second, then sleeps at 0.1 mA for 59 seconds, repeating. What is its average current?
Interactive figures, in words
Figure 4.2 from “Energy over time: watt-hours and what they cost”
Step through each device and note its power and its energy per day. Which has the biggest power? Which uses the most energy in a year? Change the hours per day for the laptop and watch the yearly cost. Finally pick a battery pack and find a device it can run for more than a day.
The power and energy meter lists five low-voltage devices: an indicator LED (5 V, 15 mA), a microcontroller board (5 V, 50 mA), a phone charging (5 V, 2 A), a robot drive motor (12 V, 1.5 A) and a laptop (20 V, 3 A). For each it shows power, energy per day, energy per year and cost per year at an adjustable illustrative price, plus run time from a chosen battery pack. For example, the phone at 10 W for 2 hours uses 20 Wh a day.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: Battery sensor node (Simulation OS experiment)
Change how often the node wakes and transmits until it lasts a whole season, and report the average current.
Open online - BUILD: Smart greenhouse, level 3 (BUILD level)
Estimate the energy the greenhouse heater uses overnight and what it would cost.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A USB port supplies 5 V at 0.5 A. What power is that, in watts?
Answer: W
Check it in “Electrical power: how fast energy flows”
2. Which resistor would exceed a 0.25 W rating?
- 470 Ω on 5 V
- 1 kΩ on 12 V
- 100 Ω on 9 V
Check it in “Electrical power: how fast energy flows”
3. The current through a resistor doubles. Its heating power becomes…
- The same
- Twice as much
- Four times as much
Check it in “Electrical power: how fast energy flows”
4. A 20 W device runs for 3 hours. How much energy does it use, in watt-hours?
Answer: Wh
Check it in “Energy over time: watt-hours and what they cost”
5. How many joules are in 2 Wh?
Answer: J
Check it in “Energy over time: watt-hours and what they cost”
6. A controller draws a constant 50 mA and a motor draws 1500 mA for 10% of the time. What is the average total current, in mA?
Answer: mA
Check it in “Battery budgets: peak, average and run time”
7. A 2000 mAh battery has a voltage of 3.7 V. How much energy does it store, in Wh?
Answer: Wh
Check it in “Battery budgets: peak, average and run time”
8. Which number decides whether the battery and wires can cope when the motor starts?
- The average current
- The peak current
- The battery's weight
Check it in “Battery budgets: peak, average and run time”
Engineering applications
Wildlife trackers
Trackers on birds can weigh only a few grams, battery included. They sleep almost all the time and wake briefly to take a fix, so the sleep current, not the radio, often decides how long they work.
Standby costs
A device drawing a few watts on standby all year uses tens of kilowatt-hours. Multiplying power by hours by price turns that small number into a bill people notice.
Summary
- P = V × I = I² × R = V² / R; check every component against its power rating.
- Energy = power × time; a watt-hour is 3600 joules.
- Battery life ≈ capacity / average current, so duty cycling matters more than peak current.
- Size supplies for the peak, but budget batteries for the average.
Glossary
- Electrical power
- The power transferred in a component is the voltage across it multiplied by the current through it. For a resistor this can also be written I²R or V²/R.
- Battery capacity and runtime
- A battery's capacity in ampere-hours says how long it can supply a current; multiplied by its voltage it gives stored energy in watt-hours.
- Efficiency
- Efficiency is the fraction of input energy or power that comes out as useful output. The rest becomes heat, sound or other losses.
Project: A year on two batteries
A weather station must run for a year on two AA cells. Choose how often it measures and transmits, estimate the current in each state from datasheet-style numbers you state, compute the average current and battery life, and say which state dominates the budget.
Deliverables
- A state table with current and time in each state
- The average current and predicted life
- The dominant state and one way to improve it
References
- Elecia White (2011). Making Embedded Systems: Design Patterns for Great Software. O'Reilly Media.
- Paul Scherz and Simon Monk (2016). Practical Electronics for Inventors, 4th edition. McGraw-Hill Education.
5. Inside a microcontroller
A microcontroller is a whole small computer on one chip: processor, flash for the program, RAM for the variables and a crowd of peripherals. Its clock ticks millions of times a second, which sets an instruction budget for every loop. Programs run as a super-loop that sets up once and repeats forever, and hardware timers count ticks for you, so the loop can juggle several tasks without ever stopping to wait.
Figure 5.1. Divide the clock, count the ticks (described in words)
A 16 MHz CPU clock divided by a prescaler of 64 gives timer ticks at 250 kHz, one every 4 µs. 1 ms is 250 ticks, and an 8-bit timer overflows after 256 ticks, which is 1.024 ms.
Explanation
5.1 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?
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.
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.
5.2 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?
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.
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.
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.
5.3 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?
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.
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.
5.4 Timers: hardware that counts for you
Your loop is busy reading sensors. Who is keeping track of the time?
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).
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.
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.
5.5 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?
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.
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.
Examples to try
Worked solutions are in the interactive chapter online.
A whole computer on one chip: example 1
A bike light flashes, reads a button and dims when the battery is low. Which microcontroller parts are involved?
Counting in nanoseconds: example 1
A 48 MHz chip averages 2 cycles per instruction. Can a 30,000-instruction loop run 1,000 times a second?
Counting in nanoseconds: example 2
How long is one period of a 240 MHz clock?
Set up once, loop forever: example 1
Write pseudocode for a night light: an LED should be on when a light sensor reads below 300 counts.
Timers: hardware that counts for you: 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?
Doing several things at once (without waiting): 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?
Interactive figures, in words
Figure 5.2 from “Counting in nanoseconds”
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.
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.
Figure 5.3 from “Set up once, loop forever”
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.
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.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Write a non-blocking loop that blinks one light every 500 ms and checks a button every 10 ms, using elapsed time instead of delays.
Open online - BUILD: Washing machine, level 2 (BUILD level)
Write the controller's loop so it keeps reading the door sensor while the drum is running.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
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
Check it in “A whole computer on one chip”
2. A microcontroller's clock runs at 160 MHz. How long is one clock period, in nanoseconds?
Answer: ns
Check it in “A whole computer on one chip”
3. 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
Check it in “Counting in nanoseconds”
4. Where should 'set pin 3 as an output' go?
- In setup, once
- Inside the loop, every pass
- After the loop ends
Check it in “Set up once, loop forever”
5. A timer counts at 16 MHz divided by a prescaler of 1. How many ticks does it count in 20 ms?
Answer: ticks
Check it in “Timers: hardware that counts for you”
6. A 16-bit timer counts at 16 MHz ÷ 256. How long until it overflows, in seconds? (Give 3 decimal places.)
Answer: s
Check it in “Timers: hardware that counts for you”
7. 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
Check it in “Doing several things at once (without waiting)”
8. 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
Check it in “Doing several things at once (without waiting)”
Engineering applications
Everywhere, unseen
Washing machines, keyboards, toothbrushes and car windows each hide a microcontroller running a super-loop. Most never run an operating system; they simply set up their pins once and loop for years.
Why delays hurt
A program that waits one second in a delay cannot notice a button press during that second. Non-blocking timing checks the clock on every pass instead, so a stop button always works.
Summary
- A microcontroller combines a CPU, flash, RAM and peripherals on one chip.
- Clock period = 1 / frequency; the loop rate times the work per pass must fit the instruction budget.
- A super-loop runs setup once, then repeats loop forever.
- Timers count prescaled clock ticks; non-blocking code compares elapsed time instead of waiting.
Glossary
- RAM, flash and EEPROM
- RAM is fast, volatile working memory that loses its contents without power; flash and EEPROM are non-volatile and keep data, but are slower to write and wear out after many write cycles.
- Clock speed, cycles and CPI
- Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency.
- Registers
- Registers are a small number of very fast storage locations inside the processor that hold the values it is working on right now.
- Interrupts
- An interrupt is a hardware signal that makes the processor pause the main program, run a short interrupt service routine (ISR), and then resume where it left off.
Project: Three tasks, one loop
Design a super-loop that blinks a status light at 1 Hz, samples a sensor at 50 Hz and checks a stop button at 100 Hz, without delays. Give the timer settings you would use, the time budget for each pass and how you would detect a pass that overruns.
Deliverables
- Pseudocode or code for the loop
- Timer and prescaler choices with tick calculations
- An overrun check and what it does
References
- Elecia White (2011). Making Embedded Systems: Design Patterns for Great Software. O'Reilly Media.
- Edward A. Lee and Sanjit A. Seshia (2017). Introduction to Embedded Systems: A Cyber-Physical Systems Approach, 2nd edition. MIT Press.
6. Pins, inputs and sensors
A digital pin reads high or low, but an unconnected input floats and reads nonsense, so a pull-up resistor gives a button a resting voltage. Mechanical contacts bounce, so one press must be debounced into one count. Analogue sensors go through the ADC, which turns a voltage into a whole number of steps; a datasheet line or a two-point calibration then turns those counts into degrees, metres or newtons.
Figure 6.1. Voltage in, stepped code out (described in words)
A 10-bit ADC with a 5 V reference has 1024 codes, 4.88 mV per step, shown as a staircase beside the ideal straight line; code 512 means 2.5 V. A 10 kΩ pull-up to 3.3 V draws 0.33 mA when the button is pressed.
Explanation
6.1 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?
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.
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.
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.
6.2 Pull-ups: giving a button a resting voltage
A button only connects two wires. So why does every microcontroller button also need a resistor?
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.
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.
6.3 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 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.
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.
6.4 Reading the datasheet line
A temperature sensor says 750 mV. The datasheet has one line of maths. What is the temperature?
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.
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. ✓
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.
6.5 ADC counts, quantisation and noise
A 10-bit ADC says 512. A 12-bit one says 2048. Are they measuring the same voltage?
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.
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.
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.
Examples to try
Worked solutions are in the interactive chapter online.
Pins: high, low and in between: example 1
A 5 V pin drives a green LED (V_f = 2.2 V) at 15 mA. What resistor?
Pull-ups: giving a button a resting voltage: 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?
Debouncing: one press, one count: example 1
A switch bounces for up to 8 ms. Your loop reads every 2 ms. How many identical readings should the debouncer require?
Reading the datasheet line: example 1
An MCP9700A-style sensor gives 400 mV at 0 °C and 19.5 mV per °C. It reads 790 mV. Temperature?
ADC counts, quantisation and noise: 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?
Interactive figures, in words
Figure 6.2 from “Pins: high, low and in between”
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.
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.
Figure 6.3 from “Debouncing: one press, one count”
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?
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.
Figure 6.4 from “Reading the datasheet line”
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?
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.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Electronics Studio (Studio)
Wire a button with a pull-up and show the pin reads high at rest and low when pressed.
Open online - BUILD: Sorting machine, level 3 (BUILD level)
Tune the sensor thresholds so the sorter separates parts reliably despite noisy readings.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
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
Check it in “Pins: high, low and in between”
2. 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
Check it in “Pins: high, low and in between”
3. 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:
Check it in “Pull-ups: giving a button a resting voltage”
4. 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
Check it in “Pull-ups: giving a button a resting voltage”
5. 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
Check it in “Debouncing: one press, one count”
6. 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
Check it in “Reading the datasheet line”
7. What voltage does one step (1 LSB) of a 10-bit ADC with a 3.3 V reference represent, in millivolts?
Answer: mV
Check it in “ADC counts, quantisation and noise”
8. 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
Check it in “ADC counts, quantisation and noise”
Engineering applications
Keyboards
Every key on a keyboard bounces for a few milliseconds when pressed. Firmware samples the key repeatedly and only accepts a change once it has been stable, so one press types one letter.
Reading a temperature
A temperature sensor's datasheet gives a voltage per degree and an offset. Firmware converts ADC counts to volts, then volts to degrees, and engineers check the result against a reference thermometer at two points.
Summary
- An unconnected input floats; a pull-up or pull-down resistor gives it a defined resting level.
- With a pull-up, a button to ground reads low when pressed: active low.
- Debouncing accepts a change only after the input has been stable for a set time.
- ADC step = reference / 2^bits; convert counts to volts, then to physical units with the datasheet or a calibration.
Glossary
- Pull-up and pull-down resistors
- A pull-up resistor connects an input pin to the supply so it reads high when nothing else drives it; a pull-down connects it to ground so it reads low.
- ADC resolution
- An n-bit analogue-to-digital converter splits its reference voltage into 2^n steps; one step, the least significant bit, is the smallest change it can detect.
- Reading a datasheet
- A datasheet is the manufacturer's technical description of a part: pinout, electrical characteristics, absolute maximum ratings, timing and typical application circuits.
- Calibration
- Calibration compares an instrument's readings with known references and builds a correction, often an offset and a gain, so that future readings are accurate.
- Voltage divider
- Two resistors in series across a supply produce, at their junction, a fraction of the supply voltage set by the ratio of the resistors.
Project: A calibrated thermometer
Design the input side of a thermometer: a thermistor divider into a 10-bit ADC. Choose the resistor, estimate the counts at 0 °C and 40 °C, and describe a two-point calibration that turns counts into degrees. State the temperature resolution you would get.
Deliverables
- The circuit and component values
- Expected ADC counts at both temperatures
- The calibration procedure and resulting resolution
References
- Paul Horowitz and Winfield Hill (2015). The Art of Electronics, 3rd edition. Cambridge University Press.
- Elecia White (2011). Making Embedded Systems: Design Patterns for Great Software. O'Reilly Media.
7. PWM, state machines and actuators
A microcontroller pin can only be fully on or fully off, yet it can dim a light or slow a motor: switch fast enough and the load feels the average. That is pulse-width modulation. Controlling what happens when is the job of a state machine, a short list of states, events and transitions that keeps behaviour predictable. And since pins give milliamps while motors want amps, a driver stage does the heavy lifting.
Figure 7.1. Average voltage = duty × supply (described in words)
Three PWM waveforms on a 5 V supply with their averages as dashed lines: 25% duty averages 1.25 V, 50% duty averages 2.5 V and 75% duty averages 3.75 V.
Explanation
7.1 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?
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.
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.
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.
7.2 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?
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.
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.
7.3 A state machine in twelve lines
Can a whole automatic door fit in one variable and a handful of ifs?
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.
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.
7.4 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?
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.
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.
Examples to try
Worked solutions are in the interactive chapter online.
PWM: dimming with an on/off switch: example 1
A 1 kHz PWM signal is high for 0.35 ms each period. Duty cycle and average on a 5 V pin?
States, events and transitions: example 1
Start: closed (0). Events: person, fully open, person, timer ended, person, fully open. Final state?
A state machine in twelve lines: example 1
Trace step from CLOSED with events: timer, person, fully_open, person, timer, fully_closed.
Choosing an actuator, and why pins need help: 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?
Interactive figures, in words
Figure 7.2 from “PWM: dimming with an on/off switch”
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.
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.
Figure 7.3 from “States, events and transitions”
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?
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.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- BUILD: Traffic system, level 2 (BUILD level)
Build the junction's state machine and check that no state lets two conflicting roads show green.
Open online - Simulation OS: Traffic-light junction timing (Simulation OS experiment)
Share green time between roads and a crossing, and confirm every phase stays safe.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
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
Check it in “PWM: dimming with an on/off switch”
2. You want an average of 4.5 V from a 12 V supply. What duty cycle is needed, in percent?
Answer: %
Check it in “PWM: dimming with an on/off switch”
3. 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
Check it in “PWM: dimming with an on/off switch”
4. 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
Check it in “States, events and transitions”
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
Check it in “States, events and transitions”
6. 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
Check it in “A state machine in twelve lines”
7. 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
Check it in “Choosing an actuator, and why pins need help”
8. 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
Check it in “Choosing an actuator, and why pins need help”
Engineering applications
LED dimming
Screens and lamps are often dimmed with PWM at hundreds or thousands of hertz. Too slow and people see flicker, especially out of the corner of the eye or on camera.
Doors and vending machines
Automatic doors, vending machines and lifts are state machines. Writing out every state and transition, including what happens on a fault, is how designers make sure the door never closes on someone.
Summary
- PWM switches a pin on and off quickly; the load sees the average: duty × supply.
- A state machine has states, events and transitions; every state needs a rule for every event.
- In code, a state machine is a variable and a branch on it inside the loop.
- Pins cannot drive motors directly; a transistor or driver switches the real current.
Glossary
- PWM average voltage
- Pulse-width modulation switches a signal fully on and off quickly; the fraction of time it is on, the duty cycle, sets the average voltage delivered.
- Hobby servo motor
- A hobby servo is a motor, gearbox, position sensor and controller in one case. It moves to an angle set by the width of a pulse repeated about every 20 ms.
- Stall torque and no-load speed
- For a DC motor, stall torque is the torque at zero speed and no-load speed is the speed with zero torque; between them torque falls roughly linearly as speed rises.
- On–off control with hysteresis
- On–off control switches the actuator fully on or off; hysteresis uses two thresholds, one to switch on and a different one to switch off, so the output does not chatter around a single value.
Project: A fan with manners
Design a cooling fan controller with states Off, Low, High and Fault. It reads a temperature, drives the fan with PWM, and enters Fault if the fan stalls. Draw the state diagram, list the transitions, pick duty cycles and choose a driver for a 12 V, 0.5 A fan.
Deliverables
- A state diagram with every transition
- Duty cycles and the PWM frequency with reasons
- The driver choice and its current rating
References
- Edward A. Lee and Sanjit A. Seshia (2017). Introduction to Embedded Systems: A Cyber-Physical Systems Approach, 2nd edition. MIT Press.
- Paul Scherz and Simon Monk (2016). Practical Electronics for Inventors, 4th edition. McGraw-Hill Education.
8. Talking between chips
Sensors, displays and radios talk to the microcontroller over a handful of wires. UART sends bytes on one wire with a start bit and a stop bit at an agreed speed. I²C shares two wires among many devices, each with an address, and every byte is acknowledged. SPI uses a clock and separate data lines to swap bytes at high speed. Knowing the framing lets you calculate throughput and decode a captured signal by eye.
Figure 8.1. Start, eight data bits, stop (described in words)
A UART frame for the byte 0x41: a start bit 0, eight data bits sent least significant first (10000010), and a stop bit 1. Ten bits at 9600 baud take 1.042 ms, giving 960 bytes per second.
Explanation
8.1 UART: one wire, ten bits, one byte
There is no clock wire between your laptop and a GPS module, yet not a single bit gets lost. How does the receiver know when each bit starts?
Asynchronous means no shared clock
A UART line rests high (idle). To send a byte, the transmitter pulls it low for one bit time: the start bit. The receiver sees that falling edge, waits half a bit, then samples once per bit time. Both sides must agree on the baud rate in advance; each keeps its own clock, so they only have to stay in step for one short frame before the next start bit lines them up again.
The frame, bit by bit
After the start bit come 8 data bits, least significant bit first, then an optional parity bit, then a stop bit (high) that returns the line to idle. The common format 8N1 means 8 data bits, no parity, 1 stop bit: 10 bits on the wire per byte. 8E1 adds an even-parity bit (11 bits). The letter A is 0x41 = 01000001, so the data bits go out as 1 0 0 0 0 0 1 0.
Parity: a one-bit alarm
With even parity the transmitter picks the parity bit so the total number of 1s in data + parity is even. 0x41 has two 1s, so its even-parity bit is 0. If noise flips any single bit, the count becomes odd and the receiver flags the frame. Two flipped bits cancel out and slip through, so parity detects errors but cannot correct them; real protocols add checksums on top.
When the text turns to garbage
A baud-rate mismatch makes the receiver sample in the wrong places, so bytes decode as nonsense or framing errors (no high stop bit where one was expected). Other usual suspects: transmit wired to transmit instead of crossing TX→RX, no shared ground, or a 5 V device talking to a 3.3 V input. UART voltage levels are a separate choice from the frame format.
Derivation: From baud rate to bytes per second
One bit lasts T = 1/baud seconds. At 9600 baud, T = 1/9600 s ≈ 104.2 µs.
One 8N1 frame is 1 start + 8 data + 1 stop = 10 bits, so it lasts 10·T ≈ 1.042 ms.
Back to back with no idle gaps, frames per second = 1/(10·T) = baud/10 = 960.
Each frame carries one data byte, so the maximum data rate is 960 bytes/s. In general: bytes/s = baud ÷ (bits per frame).
Common mix-ups
Baud rate ÷ 8 gives bytes per second.
✓ Divide by the frame length: 10 bits for 8N1, so 9600 baud carries 960 bytes/s, not 1200.Bytes are sent most significant bit first, just as we write them.
✓ UART sends the least significant bit first; I²C and most SPI devices send the most significant bit first.Parity can fix a corrupted byte.
✓ Parity only detects an odd number of flipped bits. It cannot tell which bit flipped, and two flips go unnoticed.
8.2 I²C: decoding a bus conversation
Twenty sensors share the same two wires, and none of them talk over each other. Who decides who speaks, and how does a sensor say “got it”?
Two wires, pulled up
I²C has SCL (clock, driven by the controller) and SDA (data). Devices never drive a line high: they can only pull it low or let go (open drain). Pull-up resistors bring released lines back high. So two devices can never fight, one pushing high and one low; at worst both pull low. It also means a 0 is a definite act, which is why the acknowledge is a 0.
Start, address, acknowledge
A transaction begins with START: SDA falls while SCL is high (data normally changes only while SCL is low). Then the controller sends the address byte: 7 address bits, MSB first, plus R/W (0 = write, 1 = read). On the 9th clock it releases SDA; the device with that address pulls it low: ACK. If nobody does, SDA stays high: NACK, meaning no such device (or it is busy).
Reading a register
Most sensors keep values in numbered registers. A register read is: START, address+W, register index (target ACKs both), repeated START, address+R, then the target sends data bytes. Now the controller acknowledges: ACK means “send another”, and a NACK on the last byte means “that's enough”, followed by STOP (SDA rises while SCL is high).
Counting the time
Every byte costs 9 clocks: 8 data bits and the acknowledge. Reading 2 data bytes from a register is 5 bytes on the bus, so 45 clocks: 450 µs at standard mode (100 kHz) or 112.5 µs at fast mode (400 kHz), before counting the START, repeated START and STOP. The addressing overhead is why I²C suits small, occasional reads rather than streaming video.
Derivation: How long a register read takes
List the bytes: address+W, register index, address+R (after the repeated START), then n data bytes: 3 + n bytes.
Each byte is 8 data clocks plus 1 acknowledge clock: 9 clocks per byte, so 9(3 + n) clocks.
One clock lasts 1/f. At 100 kHz that is 10 µs; at 400 kHz, 2.5 µs.
Time ≈ 9(3 + n)/f. For n = 2: 45 clocks → 450 µs at 100 kHz, 112.5 µs at 400 kHz (START/STOP conditions add a little more).
Common mix-ups
The address byte on the wire is the 7-bit address itself.
✓ It is the address shifted left with R/W in the lowest bit, so 0x48 appears as 0x90 (write) or 0x91 (read).I²C devices drive the data line high and low like any output.
✓ They only pull low or let go; pull-up resistors make the highs. That is what makes sharing the bus safe.A NACK always means an error.
✓ A NACK after the address usually means no device; a NACK on the last byte of a read is the normal way to finish.
8.3 SPI: swapping bytes at full speed
A tiny colour screen needs over a megabyte every second. Which bus can keep up, and why does reading from it mean sending something too?
Four wires, one conversation at a time
SCLK is the clock from the controller. MOSI (controller out, peripheral in) and MISO (controller in, peripheral out) carry data. CS (chip select, active low) picks which peripheral is listening: each peripheral normally gets its own CS line, so four devices need four CS pins. There are no addresses: pulling a CS low is the address.
Two shift registers in a ring
Inside, the controller and the peripheral each hold an 8-bit shift register, joined in a ring by MOSI and MISO. On each clock, each side shifts its most significant bit out and takes the other side's bit in. After 8 clocks the bytes have swapped. That is why SPI is full duplex, and why reading always means writing something.
Modes: when to sample
Devices differ on the clock's idle level (CPOL) and on which edge data is sampled (CPHA), giving modes 0–3. Mode 0 (clock idles low, sample on the rising edge) is the most common. Controller and peripheral must use the same mode, or every bit is read half a clock off. The datasheet always states it; check it before blaming the wiring.
Choosing a bus
UART: 2 wires, point to point, no clock; 115200 baud 8N1 is about 11.5 kB/s. I²C: 2 wires shared by many addressed devices, acknowledged; 400 kHz gives at most about 44 kB/s before addressing overhead. SPI: 3 wires plus a CS per device, no addressing or acknowledge; 10 MHz moves 1.25 MB/s. Choose by data rate, number of devices and spare pins.
Derivation: SPI burst time and data rate
SPI moves one bit per clock edge pair and has no start, stop, parity or acknowledge bits.
So N bytes need exactly 8N clocks (with CS held low and no gaps).
One clock lasts 1/f, so the burst takes t = 8N/f. With f in MHz, t comes out in microseconds.
The maximum data rate is N/t = f/8 bytes per second: 8 MHz → 1 000 000 bytes/s.
Common mix-ups
You can read from SPI without writing.
✓ Every clock shifts one bit each way; reading N bytes means sending N bytes (often dummies).SPI devices have addresses like I²C devices.
✓ SPI has none: the chip-select line picks the device, at the cost of one pin each.If the wiring is right, any SPI mode will work.
✓ Controller and peripheral must agree on CPOL and CPHA; the wrong mode shifts every bit by half a clock.
Examples to try
Worked solutions are in the interactive chapter online.
UART: one wire, ten bits, one byte: example 1
A logic analyser shows, after the start bit, the data bits 0 0 1 0 1 1 0 0 (first to last). What byte is it?
UART: one wire, ten bits, one byte: example 2
How long does one 8E1 frame take at 115200 baud?
I²C: decoding a bus conversation: example 1
A capture shows the first byte after START as SDA bits 1 1 0 1 0 0 0 1 (MSB first), then SDA low on the 9th clock. Decode it.
I²C: decoding a bus conversation: example 2
After sending address 0x3C+W, SDA stays high on the 9th clock. What does it mean and what would you check?
SPI: swapping bytes at full speed: example 1
How long does it take to send 64 bytes to an SD card at 4 MHz?
SPI: swapping bytes at full speed: example 2
A board has 3 SPI peripherals and 1 I²C sensor. How many microcontroller pins do the buses use?
Interactive figures, in words
Figure 8.2 from “UART: one wire, ten bits, one byte”
Pick the letter A (65) and look at the waveform: find the start bit and read the data bits from left to right. Then flip one data bit with parity off, then with even parity on. Which setting notices the damage?
The UART diagram draws one frame as a square wave. For the letter A (65 = 0x41) with even parity the line reads, in time order: start 0, data 1 0 0 0 0 0 1 0, parity 0, stop 1. Choosing a byte updates the bits; choosing a data bit to flip inverts it and the readout reports the wrongly decoded byte and whether the parity check fails (it fails for any single flip when parity is on; with no parity the error is not noticed).
Figure 8.3 from “I²C: decoding a bus conversation”
Leave the address at 0x48 and step through the register read one byte at a time. Watch the 9th bit of each byte: who drives it, and why is the very last one different?
The I²C diagram lists a register read from address 0x48, register 0x00, with sample data 0x1A and 0xC3: byte 1 address+W 0x90 ACK by target; byte 2 register 0x00 ACK by target; byte 3 address+R 0x91 ACK by target; byte 4 data 0x1A ACK by controller; byte 5 data 0xC3 NACK by controller, then STOP. Each step shows the 8 SDA bits most significant first and the 9th acknowledge bit. The readout totals 45 clocks: 450 µs at 100 kHz and 112.5 µs at 400 kHz.
Figure 8.4 from “SPI: swapping bytes at full speed”
Set the controller to 0x9F and the peripheral to 0x3C. Clock once at a time and watch both registers. After how many clocks have the two bytes completely swapped places?
The SPI diagram shows two 8-bit registers. Starting with the controller holding 0x9F (10011111) and the peripheral holding 0x3C (00111100), each press of Clock once shifts both registers left by one: the controller's top bit goes into the peripheral's bottom bit over MOSI and the peripheral's top bit goes into the controller's bottom bit over MISO. After 8 clocks the controller holds 0x3C and the peripheral holds 0x9F: the bytes have swapped.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Write a function that turns a byte into its ten-bit UART frame and another that decodes a frame back into a byte.
Open online - Nexus: Computer-Controlled Machine (Nexus project)
Decide which bus each device in the machine should use and estimate the data each one needs per second.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. What level does a UART transmit line sit at when nothing is being sent?
- Low (0)
- High (1)
- It toggles at the baud rate
Check it in “UART: one wire, ten bits, one byte”
2. After the start bit, a UART frame carries the data bits 0 0 1 0 1 1 0 0 (first to last, least significant bit first). What byte value is that, in decimal?
Answer:
Check it in “UART: one wire, ten bits, one byte”
3. At 9600 baud with 8N1 framing and no gaps, what is the maximum data rate, in bytes per second?
Answer: bytes/s
Check it in “UART: one wire, ten bits, one byte”
4. During the acknowledge clock, what does the receiving device do to say ACK?
- Drives SDA high
- Pulls SDA low
- Stops the clock
Check it in “I²C: decoding a bus conversation”
5. In a multi-byte read, the controller answers the final data byte with a NACK. Why?
- The data was corrupted
- To tell the target to stop sending before the STOP condition
- Because the target sends the acknowledge on reads
Check it in “I²C: decoding a bus conversation”
6. In an 8-bit SPI transfer, how many clock cycles does it take for the controller's and peripheral's bytes to swap completely?
Answer:
Check it in “SPI: swapping bytes at full speed”
7. Which bus suits a colour display that needs about 1 MB/s, on a board with pins to spare?
- UART at 115200 baud
- I²C at 400 kHz
- SPI at 10 MHz
Check it in “SPI: swapping bytes at full speed”
8. Four SPI peripherals share SCLK, MOSI and MISO, each with its own chip select. How many microcontroller pins does the SPI bus use?
Answer:
Check it in “SPI: swapping bytes at full speed”
Engineering applications
Debug consoles
Almost every embedded board has a UART debug port. Engineers connect it to a laptop to read log messages while the device runs, the quickest way to see what firmware is thinking.
Choosing a bus
A slow temperature sensor and a fast display can share a board: the sensor on I²C, which saves pins, and the display on SPI, which moves pixels fast enough. The choice is a trade between wires and speed.
Summary
- UART frames each byte with a start bit and a stop bit; 10 bits per byte sets the throughput.
- I²C uses two shared wires, a 7-bit address and an acknowledge bit after every byte.
- SPI shifts bits out and in at the same time, with one chip-select line per device.
- Pick a bus by trading pin count, speed, distance and the number of devices.
Glossary
- Bus and link bandwidth
- Bandwidth is how much data a bus or link can move per second. For a UART each byte usually costs 10 bit times: one start bit, eight data bits and one stop bit.
- Bits and bytes
- A bit is a single binary digit, 0 or 1. A byte is 8 bits. n bits can represent 2^n different values.
- Hexadecimal
- Hexadecimal is base 16, using digits 0–9 and A–F. Each hex digit stands for exactly four bits, so two hex digits describe one byte.
- Endianness
- Endianness is the order in which the bytes of a multi-byte value are stored in memory or sent over a link: little-endian puts the least significant byte first, big-endian the most significant.
Project: A bus plan for a sensor board
A board has a microcontroller, a temperature sensor, an accelerometer sampled at 400 Hz, a small display and a debug port. Assign each to a bus, calculate the data rate each needs, and check that every bus has headroom at the speed you choose.
Deliverables
- A wiring plan naming the bus for each device
- Data-rate calculations per device
- A headroom check for every bus
References
- Elecia White (2011). Making Embedded Systems: Design Patterns for Great Software. O'Reilly Media.
- Edward A. Lee and Sanjit A. Seshia (2017). Introduction to Embedded Systems: A Cyber-Physical Systems Approach, 2nd edition. MIT Press.
9. Registers, interrupts and integration
Underneath every library call, software controls hardware by writing bits into registers. Bit masks set, clear and test single bits without disturbing their neighbours. Interrupts let hardware call the processor when something happens, saving the energy and latency of constant polling, but they bring shared-data hazards. Finally, the build chain turns source into a running image, and hardware-in-the-loop tests check the join between code and circuit.
Figure 9.1. Touch one bit, leave the rest (described in words)
Three rows of eight bit cells. The register holds 10100000 (160). OR with 1 << 3 sets bit 3, giving 10101000 (168). AND with NOT (1 << 7) then clears bit 7, giving 00101000 (40). Bit 7 is on the left.
Explanation
9.1 Registers and bit masks: where software touches silicon
One line of C turns on a motor driver. Which single bit, at which address, did it change, and what else could it break?
Memory-mapped I/O
Microcontrollers give each peripheral (GPIO, timers, ADC, UART) a block of addresses. Writing to an address doesn't store data in RAM; it sets flip-flops whose outputs drive the hardware: a pin's direction, a timer's prescaler, an interrupt enable. Reading may return live hardware state, such as whether a conversion has finished.
The four mask operations
Set bit n: reg |= (1 << n). Clear: reg &= ~(1 << n). Toggle: reg ^= (1 << n). Test: (reg & (1 << n)) != 0. Multi-bit fields (a 3-bit prescaler at bits 4–6) are cleared with a field mask, then the new value is ORed in, shifted into place. Datasheets give each bit's meaning; the code should name them, not use magic numbers.
Read–modify–write hazards
reg |= mask is really three steps: read, OR, write. If an interrupt changes the same register between the read and the write, its change is lost. Fixes: disable interrupts briefly around the update, or use hardware 'set' and 'clear' registers that change only the bits you write as 1. Some status bits clear when read, so even reading has side effects.
Integration means checking both sides
A firmware unit test can't see a wrongly configured clock. Integration tests run real code on real (or accurately simulated) hardware and check observable behaviour: the pin toggles at the expected frequency, the ADC reads a known voltage correctly. Write down what each register should contain and check it in a debugger.
Common mix-ups
Writing to a register is like writing to a variable.
✓ It changes hardware immediately and can have side effects; reading can too.reg |= mask is a single, safe operation.
✓ It is read–modify–write and can lose updates made by interrupts in between.
9.2 Polling or interrupts? Latency, energy and shared data
Checking a button a million times a second never misses a press. Why is it usually the wrong design?
Polling
The main loop repeatedly reads a status bit. Simple, deterministic and easy to debug. Worst-case latency is the loop period (plus the work done each loop). Energy cost: the CPU wakes every period whether or not anything happened. Good when events are frequent and regular, or when you need a fixed sampling rate anyway (a control loop at 1 kHz).
Interrupts
Hardware detects the event and forces the CPU to run a short handler (an ISR). Latency is microseconds (entry cycles plus any time interrupts are disabled). Between events the CPU can sleep. The price is complexity: handlers interrupt main code at unpredictable moments, which creates races on shared data.
Protecting shared data
Rules of thumb: keep ISRs short (set a flag, copy a value, leave); declare shared variables volatile; read multi-byte values with interrupts briefly disabled or with a consistency check; use a ring buffer with one writer and one reader. Never call slow or blocking functions inside an ISR.
Hybrid designs
Many systems use an interrupt to wake from sleep, then poll briefly while active, or a timer interrupt that runs a fixed-rate control loop. The choice is a budget trade: latency target, energy per event, CPU time left for other work, and how much complexity you can verify.
Common mix-ups
Interrupts are always better than polling.
✓ Polling is simpler and deterministic; it is often right for fixed-rate control loops or frequent events.A variable shared with an ISR is safe if it's only one line of code.
✓ One line can compile to several instructions; protect shared data explicitly.
9.3 From source code to running hardware, and testing the join
The code compiled, the tests passed, and the robot still twitched. Where in the chain did it go wrong?
The chain
Compiler: C or Rust → assembly for the target. Assembler: assembly → machine-code object files. Linker: combines objects and libraries, places code and data at real addresses using a linker script (flash here, RAM there). Image: a binary or hex file. Flashing: a programmer writes it into the chip's flash. Boot: the reset vector jumps to start-up code that sets up the stack and memory, then calls main.
Optimisation levels are trade-offs
-O0: slow, large, every variable visible to the debugger. -O2: fast, usually smaller. -Os: smallest. -O3: aggressive inlining, can be larger. On a microcontroller with 64 KB of flash, size may decide. Benchmark the configuration you will ship: timings measured on a debug build can differ greatly.
What changes between builds
Library versions, compiler versions, flags, linker scripts and configuration headers can all change behaviour. Reproducible builds pin them all and record a version or commit hash in the firmware itself, so a measurement can always be traced to the exact binary that produced it.
Integration testing
Unit tests check functions in isolation on a computer. Hardware-in-the-loop tests run the real firmware on the real board while a test rig feeds sensor signals and measures outputs and timing. Test the joins: clock configuration, interrupt latency under load, behaviour at power-up, and what happens when a sensor is unplugged.
Common mix-ups
If it compiles and the unit tests pass, the firmware works.
✓ Configuration, timing and hardware interaction need integration tests on the real target.Compiler optimisation changes what the program does.
✓ It preserves defined behaviour; failures after optimising usually expose bugs such as missing volatile or undefined behaviour.
Examples to try
Worked solutions are in the interactive chapter online.
Registers and bit masks: where software touches silicon: example 1
reg = 0x5A (0101_1010). Clear bit 3, then toggle bit 0. Result?
Polling or interrupts? Latency, energy and shared data: example 1
A polling loop runs every 2 ms and takes 0.3 ms per pass. What is the worst-case delay before an event is noticed?
From source code to running hardware, and testing the join: example 1
A firmware image is 58 KB at -O2 and 49 KB at -Os on a chip with 64 KB flash. The -Os build runs a control loop 12% slower. The loop has 30% timing margin. Which do you ship, and what do you record?
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Write set_bit, clear_bit and test_bit functions with masks and test them on every bit of a byte.
Open online - Silicon Studio: Registers (Silicon Studio stage)
Load and hold a value in a register, then explain what a write-enable signal protects.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. Which C expression clears bit 5 of reg and leaves every other bit unchanged?
- reg = reg & (1 << 5)
- reg &= ~(1 << 5)
- reg |= (1 << 5)
- reg ^= 0xFF
Check it in “Registers and bit masks: where software touches silicon”
2. reg = 0x3C. After reg |= 0x81, what is reg in decimal?
Answer:
Check it in “Registers and bit masks: where software touches silicon”
3. Main code does PORT |= LED_BIT while an interrupt handler sets MOTOR_BIT in the same register. Occasionally the motor bit is lost. Why?
- The compiler is broken
- The interrupt ran between main's read and write, so main wrote back the old value
- Bits can't be shared
- The LED draws too much current
Check it in “Registers and bit masks: where software touches silicon”
4. A battery-powered door sensor must react within 10 ms to a door opening, which happens a few times a day. Which design?
- Poll every 1 ms forever
- Interrupt on the sensor pin, sleeping between events
- Poll every 10 seconds
- Neither can meet 10 ms
Check it in “Polling or interrupts? Latency, energy and shared data”
5. Which is good practice inside an interrupt handler?
- Print a long debug message over a slow serial port
- Set a flag or copy a value into a buffer, then return
- Wait for another sensor to be ready
- Run the whole control algorithm, however long it takes
Check it in “Polling or interrupts? Latency, energy and shared data”
6. Which tool decides the actual memory addresses where code and data end up?
- The compiler
- The linker, using a linker script
- The debugger
- The flash programmer
Check it in “From source code to running hardware, and testing the join”
7. What can a hardware-in-the-loop test catch that a unit test on a laptop cannot?
- Spelling errors in comments
- A wrongly configured clock that makes the control loop run at the wrong rate
- A sorting bug in pure code
- Nothing
Check it in “From source code to running hardware, and testing the join”
Engineering applications
Sleeping until needed
Battery devices spend most of their time asleep and let an interrupt from a timer, a button or a radio wake them. Polling the same button in a loop would keep the processor awake and empty the battery.
Testing the join
Hardware-in-the-loop rigs feed real firmware with simulated sensor signals and check its outputs. They find the bugs that only appear when code meets real timing and real voltages.
Summary
- Registers are memory addresses wired to hardware; each bit or field controls something.
- Set with OR, clear with AND NOT, test with AND; a read-modify-write can race with an interrupt.
- Interrupts cut latency and energy compared with polling; keep handlers short and protect shared data.
- The build chain compiles, links and flashes; hardware-in-the-loop tests the code with its circuit.
Glossary
- Registers
- Registers are a small number of very fast storage locations inside the processor that hold the values it is working on right now.
- Interrupts
- An interrupt is a hardware signal that makes the processor pause the main program, run a short interrupt service routine (ISR), and then resume where it left off.
- Memory-mapped I/O
- With memory-mapped I/O, peripheral control and data registers appear at fixed memory addresses, so the processor talks to hardware with ordinary load and store instructions.
- Bits and bytes
- A bit is a single binary digit, 0 or 1. A byte is 8 bits. n bits can represent 2^n different values.
- Hexadecimal
- Hexadecimal is base 16, using digits 0–9 and A–F. Each hex digit stands for exactly four bits, so two hex digits describe one byte.
Project: A register-level driver
Write a tiny driver for an imaginary peripheral whose 8-bit control register has an enable bit, a two-bit mode field and an interrupt-enable bit. Provide functions to enable it, set the mode and acknowledge an interrupt, using masks only, and explain where a race could occur.
Deliverables
- A register map table
- The driver functions with tests on a simulated register
- A note on the race and how you would prevent it
References
- Edward A. Lee and Sanjit A. Seshia (2017). Introduction to Embedded Systems: A Cyber-Physical Systems Approach, 2nd edition. MIT Press.
- Elecia White (2011). Making Embedded Systems: Design Patterns for Great Software. O'Reilly Media.
- Paul Horowitz and Winfield Hill (2015). The Art of Electronics, 3rd edition. Cambridge University Press.
Known limitations
- Not yet tested by a person using a screen reader; only automated structure checks have run.
- Some interactive lesson diagrams need a pointer or keyboard and a recent browser; their text alternatives carry the same idea without the interaction.
- Mathematics is written as plain text (for example x^2 and sqrt(x)), like the School lessons, not typeset notation.