Appearance
10.1 — Microcontrollers, Sensors and Actuators
An embedded system measures something about the world, decides something, and changes something. Chapter 3.6 covered the deciding part. This chapter is the two ends — how a physical quantity becomes a number, and how a number becomes motion, light or heat.
The rule that governs the whole subject: the sensor and its analog front end almost always limit the result, not the processor. A 16-bit converter fed by a noisy amplifier gives you eleven real bits, and no amount of software recovers the rest.
1. Microcontroller versus system-on-chip
Chapter 3.6 drew the distinction. Here is the practical decision.
| Microcontroller | Application SoC | |
|---|---|---|
| Clock | 8–500 MHz | 1–3 GHz |
| RAM | 2 KB – 1 MB on chip | 1–16 GB external |
| Storage | on-chip flash | external eMMC or SSD |
| Operating system | none, or an RTOS | Linux, Android |
| Boot time | microseconds | seconds |
| Power | µW to mW | W |
| Cost | €0.30–€10 | €5–€100 |
| Timing | deterministic | not |
Choose a microcontroller when timing must be guaranteed, power must be tiny, cost must be low, or the task is simple. That covers most embedded work.
Choose an SoC when you need a filesystem, a network stack, a display, or a language runtime. The moment the requirement includes "and it shows a web interface", the argument is over.
And the common answer is both. A microcontroller handles the real-time work — motor commutation, safety interlocks, sensor sampling at exact intervals — and an SoC handles the interface and the connectivity. A modern washing machine, a car and an industrial controller are all built this way, and the division is exactly the one Chapter 3.P found for signal processing: regular fast work in dedicated hardware, irregular decision-making in software.
2. Sensors — the measurement chain
Every sensor produces one of four things, and the conditioning needed follows directly.
A voltage — thermocouple, photodiode in photovoltaic mode, piezoelectric element. Usually small, so it needs amplification, and often riding on a common-mode voltage, so it needs an instrumentation amplifier (Chapter 2.5).
A resistance — thermistor, strain gauge, photoresistor. Resistance cannot be measured directly, so it must be converted to voltage by a divider or a bridge.
A current — photodiode in photoconductive mode, 4–20 mA industrial transmitter. Converted to voltage by a transimpedance amplifier, which is an op-amp with a resistor in the feedback path and the current injected into the virtual ground.
A digital signal — increasingly common, since the sensor contains its own converter and speaks I²C or SPI. This moves the analog problem inside the sensor's package, where the manufacturer has solved it once, and it is why almost all new designs use digital sensors.
Temperature
| Sensor | Range | Accuracy | Character |
|---|---|---|---|
| Thermocouple | -200 to 1800 °C | ±1 °C | tiny voltage, needs cold junction compensation |
| RTD (Pt100) | -200 to 850 °C | ±0.1 °C | most accurate, needs excitation current |
| Thermistor | -50 to 150 °C | ±0.5 °C | cheap, very nonlinear |
| Silicon IC | -55 to 150 °C | ±0.5 °C | digital output, no calibration |
The thermocouple's cold junction problem is worth explaining, because it catches everyone. A thermocouple produces a voltage proportional to the difference between its two junctions. Connecting it to a terminal block creates a second junction, so the reading is the difference between the tip and the terminal block — not the absolute temperature.
The fix is to measure the terminal block's temperature with a second sensor and add it back. That is cold junction compensation, and every thermocouple interface has one.
The thermistor's nonlinearity is described by the Steinhart-Hart equation:
\frac{1}{T}=A+B\ln R+C(\ln R)^3
or the simpler beta model:
R=R_0\exp\left[\beta\left(\frac1T-\frac{1}{T_0}\right)\right]
A 10 kΩ thermistor with \beta=3950 measures 32 kΩ at 0 °C and 4 kΩ at 50 °C — an eightfold change over 50 degrees, which is enormous sensitivity and the reason thermistors are used despite the nonlinearity.
Strain, force and pressure
A strain gauge is a foil pattern whose resistance changes as it stretches:
\frac{\Delta R}{R}=GF\times\varepsilon
with the gauge factor GF\approx2 for metal foil.
The numbers show why this is hard. A typical full-scale strain is 1000 microstrain, so
\frac{\Delta R}{R}=2\times0.001=0.002=0.2\%
On a 350 Ω gauge that is 0.7 Ω. Measuring 0.7 Ω against 350 Ω to 0.1% accuracy means resolving 0.0007 Ω — two parts per million of the total.
No direct measurement achieves that, which is why the Wheatstone bridge of Chapter 1.2 exists. The bridge subtracts out the 350 Ω and leaves only the change, so the amplifier sees millivolts of signal rather than volts of offset.
A full bridge with four gauges — two in tension and two in compression — gives four times the output and automatically cancels temperature effects, because all four gauges are at the same temperature and their common change cancels in the bridge. That cancellation is the real reason for using four rather than one.
V_{out}=V_{ex}\times GF\times\varepsilon
Worked example. 10 V excitation, GF=2, 1000 µε:
V_{out}=10\times2\times0.001=20\ \text{mV}
Twenty millivolts full scale, needing a gain of 250 to reach a 5 V range, and — from Chapter 2.P — an amplifier with under 10 µV of offset and over 100 dB of common-mode rejection.
Motion — MEMS
Accelerometers use a tiny proof mass on silicon springs, with capacitive plates measuring its displacement.
F=ma \;\Rightarrow\; x=\frac{ma}{k}
They measure proper acceleration, not coordinate acceleration. A stationary accelerometer on a table reads 1 g upward, because the table is pushing it up against gravity. In free fall it reads zero. That distinction confuses everyone once, and it is why an accelerometer alone cannot distinguish tilt from acceleration.
Gyroscopes measure angular rate using the Coriolis effect: a vibrating mass in a rotating frame experiences a sideways force proportional to the rotation rate.
F_{Coriolis}=-2m(\boldsymbol\omega\times\mathbf v)
They measure rate, not angle. Getting angle means integrating, and integrating a signal with any bias at all produces drift that grows without limit — a 0.01°/s bias becomes 36° of error in an hour.
Magnetometers measure the earth's field, about 25 to 65 µT depending on latitude.
And none of the three is sufficient alone, which is the point:
- Accelerometer: good long-term reference for tilt, useless while accelerating.
- Gyroscope: excellent short-term, drifts over minutes.
- Magnetometer: absolute heading, corrupted by any nearby iron or current.
Sensor fusion combines them — a complementary filter or a Kalman filter (Chapter 6.7) — using the gyroscope for fast response and the accelerometer and magnetometer to correct its drift.
The complementary filter is the one worth knowing because it is three lines of code:
\theta=\alpha(\theta_{prev}+\omega\Delta t)+(1-\alpha)\theta_{accel}
with \alpha\approx0.98. Read it: trust the gyroscope for the short term and let the accelerometer pull it back slowly. It is a high-pass filter on one signal and a low-pass on the other, summing to unity — which is where the name comes from.
The measurement chain, drawn
Every sensor in the previous section sits in the same chain, and the chain is worth having as one picture because each stage can ruin the one before it.
Why the amplifier comes before everything else. A thermocouple produces tens of microvolts per degree. Any noise the wiring picks up — mains hum, a switching converter nearby, a motor — adds at that same tiny level, and once it is added it is indistinguishable from signal. Amplifying afterwards amplifies both equally, so the damage is permanent. Amplify as close to the sensor as possible, which is why industrial sensors increasingly contain their own amplifier and send a robust 4–20 mA current rather than a fragile voltage.
Why the filter is not optional. Chapter 4.7 showed that any frequency above half the sampling rate is not merely lost — it is folded down and reappears disguised as a lower frequency that was never there. Software cannot undo this, because the real and the false components arrive as one indistinguishable number. The filter has to be analogue and it has to be before the ADC, and a design that omits it produces readings that drift and wobble for reasons nobody can find.
And the ADC sets the resolution ceiling. A 12-bit converter over a 3.3 V range resolves 3.3/4096 = 0.8 mV. If your sensor moves 0.1 mV per unit of the thing you care about, no amount of averaging makes single units visible, and you need either a bigger amplifier or a better converter.
3. Actuators
DC and brushless motors — Chapter 9.2, driven by an H-bridge with PWM.
Servos — a motor, a gearbox, a potentiometer and a control loop in one package, positioned by a pulse width. 1 to 2 ms of pulse in a 20 ms frame maps to 0 to 180°, and that timing is a legacy of 1970s radio control that has outlived its origin entirely.
Solenoids — a coil pulling an iron plunger. The force falls rapidly with distance, so a solenoid is strong when nearly closed and weak when open, which is why they are used for latching rather than positioning.
And they need the flyback diode of Chapter 1.5, without exception.
Relays — a solenoid operating contacts, giving complete electrical isolation and the ability to switch high voltage or AC. Slow, at 5 to 20 ms, and mechanically finite at perhaps 10^5 operations at rated load.
Solid-state relays switch with a triac or MOSFET, opto-isolated. Fast, silent, unlimited operations, and they leak a little when off and drop a volt or two when on.
Heaters — simply a resistor, controlled by PWM at a low frequency. Or, for AC, by burst firing: switch whole mains cycles on and off. Because thermal time constants are seconds and the mains period is 20 ms, the load never notices the chopping — and switching at zero crossings generates no interference at all, where phase-angle control generates a great deal.
4. The analog front end
Where most designs actually fail, and each stage below exists to solve a specific problem.
Protection. Series resistors and clamp diodes to the rails, as Chapter 2.2 described. Every input that leaves the board needs them.
Filtering. A low-pass before the converter, always, for the anti-aliasing reason of Chapter 4.7.
Amplification. Instrumentation amplifier for differential signals; op-amp for single-ended.
Level shifting. A sensor producing ±5 V feeding a converter that accepts 0 to 3.3 V needs both attenuation and an offset.
Isolation. Where the sensor is at a different ground potential, or where safety demands it.
The mistakes that recur
Ground loops. Two connections to ground at different points, with current flowing between them. The potential difference appears in series with the signal. The fix is a single-point ground for analog signals, or differential measurement.
Insufficient settling time before sampling. A multiplexed converter switching between channels must let the sample capacitor charge through the source impedance. A 10 kΩ source into a 20 pF sample capacitor needs about $7RC = 1.4\ \mu$s to settle to 12-bit accuracy — and sampling sooner gives a reading contaminated by the previous channel.
Ignoring self-heating. An RTD with 1 mA of excitation dissipates I^2R = 0.1 mW, which in still air raises its own temperature measurably. The sensor reports its own heating as a temperature rise.
Sharing a supply between analog and digital. Digital switching noise on the supply appears directly in the converter's reference. Separate regulators, or at minimum separate filtered rails.
Forgetting the reference. A converter's accuracy is its reference's accuracy. A 12-bit converter with a reference that drifts 0.5% with temperature is a 7-bit converter over its temperature range, and the extra bits are decoration.
5. Communication, from a system view
Chapter 3.6 compared the buses. Two additional points matter at system level.
Distance. SPI and I²C are board-level, measured in centimetres. Beyond about 30 cm, use a differential standard — RS-485, CAN, or LVDS — because a single-ended signal referenced to a distant ground picks up every difference in ground potential along the way.
The 4–20 mA current loop deserves attention as an old idea that remains correct. A sensor transmits its reading as a current between 4 and 20 mA.
Three genuine advantages:
- Current is unaffected by wire resistance, so the reading is the same at 1 m and at 1 km.
- 4 mA means zero, so a broken wire reads 0 mA and is unambiguously distinguishable from a genuine zero reading. This is a diagnostic built into the encoding, and it is why the standard uses 4 rather than 0.
- The sensor can be powered from the same two wires, drawing under 4 mA for itself.
It is over sixty years old and still the default in process industries, because those three properties are exactly what a plant needs and no digital standard improves on all three.
6. Reliability
Embedded systems run unattended for years, and the failures that matter are the ones that happen once a month.
The watchdog, from Chapter 3.6. The discipline that makes it work: clear it only from the main loop, after confirming that every critical task has run. A watchdog cleared from a timer interrupt keeps clearing while the main program is stuck, which defeats it entirely.
Brown-out detection. A supply sagging below the processor's minimum but not to zero puts it into an undefined state — executing instructions incorrectly, and possibly corrupting flash. A brown-out detector holds it in reset until the supply is valid.
Flash wear. Chapter 3.4's endurance limits apply. Writing a counter to the same flash location every second exhausts a 10,000-cycle endurance in under three hours. The fix is wear levelling in software, or a small FRAM or EEPROM for frequently changed values.
Data integrity. A CRC over configuration data in flash, checked at boot, so corruption is detected rather than acted upon.
Field updates. A bootloader that can accept new firmware, with a fallback if the update fails. The standard pattern keeps two application images and switches only after the new one has proven it can run — because a failed update on an inaccessible device is a permanent failure.
Electromagnetic compatibility. The single most useful measure is decoupling: a 100 nF capacitor at every supply pin of every chip, placed within a few millimetres. Then keep high-current loop areas small (Chapter 9.5), slow down edges that do not need to be fast (Chapter 3.6), and keep the ground plane continuous.
Electrostatic discharge. Every connector that a person can touch needs protection — a transient voltage suppressor diode, which conducts above a threshold and clamps a several-kilovolt discharge to a survivable level.
7. A worked example: a greenhouse controller
Every topic in this Part, in one device.
Requirements: measure temperature, humidity and light in four zones; control heating, ventilation and irrigation; log data; report over Wi-Fi; run on mains with battery backup.
Sensors.
Temperature and humidity: a digital combined sensor per zone on an I²C bus. Digital chosen deliberately — it puts the analog problem inside the sensor's package and eliminates four channels of front-end design.
But I²C is a board-level bus and the zones are 20 m apart. Options: an I²C bus extender using differential signalling, or a small microcontroller in each zone communicating over RS-485. The second is better — it also lets each zone continue operating if the link fails.
Light: a photodiode with a transimpedance amplifier, because light sensors with the right spectral response for plants are analog.
Soil moisture: capacitive rather than resistive. Resistive probes corrode within weeks, because passing DC through soil electrolyses the electrodes.
Actuators.
Heating: a solid-state relay with burst firing, for the zero-crossing and interference reasons of section 3.
Ventilation: a fan on a variable-frequency drive, so speed can be modulated rather than switched.
Irrigation: solenoid valves through a relay, with flyback diodes and a hardware maximum-run timer independent of the software.
That last point is the important one. A software fault that leaves a valve open floods the greenhouse. A hardware timer that closes the valve after fifteen minutes regardless of what the software says is a safety function, and it must not depend on the thing it is protecting against.
Control.
Temperature: PID with anti-windup (Chapter 6.6), heavily filtered because the process is slow and the measurement is noisy. Sample every 5 seconds; the process time constant is 20 minutes, so this is 240 times faster than needed — comfortable.
Humidity: on-off with hysteresis, because there is no proportional actuator.
Irrigation: scheduled with moisture override.
Architecture.
Zone controllers: a small microcontroller each, running the local sensing and safety interlocks.
Central controller: an SoC running Linux, doing the logging, the web interface and the connectivity.
And the division is deliberate: if the central controller crashes or the network fails, each zone continues holding its last setpoint. The system degrades rather than stopping.
Power.
Mains, with a lithium backup sized for four hours. Battery management per Chapter 9.3. On battery, shut down heating and ventilation — the large loads — and keep only sensing, logging and the ability to close valves.
Reliability measures.
Watchdogs everywhere. CRC on configuration. Two firmware images with fallback. Transient suppressors on every cable entry, since a greenhouse has long cable runs and a lightning strike nearby will induce hundreds of volts into them.
The reflection worth making. The processor is the least interesting part of this design. Everything difficult is in the sensors, the actuators, the wiring, the safety interlocks and the failure behaviour — which is true of embedded systems generally, and is why they are a distinct engineering discipline rather than a branch of programming.
Chapter 10.2 takes the densest embedded system ever mass-produced and finds every chapter of this volume inside it.
Every formula above, built from scratch
None of the results in this chapter are worth memorising, because each one can be rebuilt in under a minute from something simpler. What follows is that rebuilding, one result at a time, so the formula and the reason for it sit on the same page as the explanation that needed them.
Sensors
Thermistor
R=R_0\exp\left[\beta\left(\frac1T-\frac{1}{T_0}\right)\right] \qquad (T \text{ in kelvin})
\frac{1}{T}=A+B\ln R+C(\ln R)^3 \qquad\text{(Steinhart-Hart)}
Worked: a 10 kΩ thermistor at 25 °C with \beta=3950 reads
R(0°\text{C})=10{,}000\exp\left[3950\left(\frac{1}{273}-\frac{1}{298}\right)\right]=10{,}000\,e^{1.214}=33.6\ \text{k}\Omega
Sensitivity:
\frac{dR}{dT}=-\frac{\beta R}{T^2}
At 25 °C: -3950\times10{,}000/298^2=-445\ \Omega/°C — 4.4% per degree, which is enormous and is why thermistors are used despite the nonlinearity.
RTD
R=R_0\left(1+\alpha T\right), \qquad \alpha=0.00385\ /°\text{C for platinum}
Pt100 at 100 °C: 100(1+0.385)=138.5\ \Omega. Only 0.385 Ω per degree, so a four-wire measurement is needed to remove lead resistance.
Thermocouple
V=\alpha(T_{hot}-T_{cold})
Type K: about 41 µV/°C. A 500 °C difference gives 20.5 mV.
Cold junction compensation is compulsory, because the thermocouple measures a difference and the terminal block forms the second junction.
Strain gauge
\frac{\Delta R}{R}=GF\times\varepsilon, \qquad GF\approx2
Full bridge output:
V_{out}=V_{ex}\times GF\times\varepsilon
Worked: 10 V excitation, 1000 µε gives 20 mV — hence the need for gain of 250 and an amplifier with under 10 µV of offset.
Quarter bridge gives a quarter of that, and does not cancel temperature.
MEMS
x=\frac{ma}{k} \qquad\text{(accelerometer proof mass displacement)}
F_{Coriolis}=-2m(\boldsymbol\omega\times\mathbf v) \qquad\text{(gyroscope)}
Gyroscope drift from bias:
\theta_{error}=\text{bias}\times t
A 0.01°/s bias gives 36° after one hour, which is why a gyroscope alone can never give absolute orientation.
Complementary filter:
\theta=\alpha(\theta_{prev}+\omega\Delta t)+(1-\alpha)\theta_{accel}, \qquad \alpha\approx0.98
Read it as a high-pass on the gyroscope and a low-pass on the accelerometer, summing to unity gain — which is exactly what "complementary" means here.
\tau_{crossover}=\frac{\alpha\Delta t}{1-\alpha}
With \alpha=0.98 and \Delta t=10 ms: 0.49 s. Below that the gyroscope dominates; above it the accelerometer does.
Analog front end
Transimpedance amplifier:
V_{out}=-I_{in}R_f
Bandwidth and stability require a feedback capacitor:
C_f\ge\sqrt{\frac{C_{in}}{2\pi R_fGBW}}
without which the photodiode's capacitance and R_f form a pole that makes the amplifier oscillate.
Sample-and-hold settling, to n-bit accuracy:
t_{settle}=R_{source}C_{sample}\ln(2^{n+1})
Worked: 10 kΩ source, 20 pF sample capacitor, 12 bits:
t=10^4\times2\times10^{-11}\times\ln(8192)=2\times10^{-7}\times9.01=1.8\ \mu\text{s}
Sampling sooner reads a mixture of this channel and the previous one.
Self-heating:
\Delta T=I^2R\times R_{th}
An RTD with 1 mA and 100 Ω dissipates 0.1 mW, which in still air with 100 °C/W of thermal resistance raises its own temperature by 0.01 °C — small, and not always negligible at high accuracy.
Reference-limited accuracy:
\text{effective bits}=n-\log_2\left(\frac{\text{reference drift}}{\text{LSB}}\right)
A 12-bit converter with a reference drifting 0.5% is effectively 12-\log_2(0.005\times4096)=12-4.4=7.6 bits over temperature.
Actuators
Servo pulse:
\theta=\frac{t_{pulse}-1\ \text{ms}}{1\ \text{ms}}\times180°
in a 20 ms frame.
Solenoid force:
F=\frac{(NI)^2\mu_0A}{2g^2}
Note the 1/g^2 — force falls as the square of the air gap, which is why a solenoid is strong when nearly closed and weak when open.
Heater PWM:
P_{avg}=D\times\frac{V^2}{R}
Burst firing switches whole mains cycles, so the effective duty is the fraction of cycles conducted. Because thermal time constants are seconds, the load cannot follow the chopping and zero-crossing switching produces no interference.
Power budgets
I_{avg}=\sum_k I_k\frac{t_k}{T}
\text{life}=\frac{\text{capacity}}{I_{avg}}
Energy per operation, which is the number that decides an architecture:
| Operation | Energy |
|---|---|
| CPU instruction | 1 nJ |
| Flash write, 4 kB | 50 µJ |
| BLE advertisement | 30 µJ |
| LoRa transmission | 50 mJ |
| Wi-Fi association + send | 5 J |
| Cellular attach + send | 15 J |
One Wi-Fi transmission costs as much as five million CPU instructions. Compute freely; transmit reluctantly.
Edge processing reduction ratio:
\frac{\text{raw data rate}}{\text{extracted feature rate}}
Worked: 10 kHz vibration sampling at 2 bytes gives 1.7 GB/day raw; six spectral features per minute gives 34 kB/day — a factor of 50,000.
Averaging gain, for both night-mode photography and repeated measurement:
\text{SNR improvement}=\sqrt N
Sixteen frames gives four times the SNR, which is two photographic stops. This is Chapter 5.3's Welch averaging in a different domain.
What the next chapter fixes
One microcontroller with a few sensors is the simple case. Chapter 10.2 takes the most integrated consumer device ever built and works through what is inside it, block by block — and nearly every block is a chapter of this volume in silicon.