Analog circuits and sensor front ends
Dividers, RC filters, op-amps and interfacing common sensors.
Why firmware engineers need analog
Sensors produce voltages, currents and resistances, not numbers. Between the sensor and the ADC there is an analog circuit (a divider, an amplifier, a filter), and the quality of every reading depends on it. You do not need to design these circuits, but you need to read them, know what limits their accuracy, and recognise when a "firmware" problem is really an analog one.
Components in one table
| Component | Relationship | Typical use near an MCU |
|---|---|---|
| Resistor | V = I × R | Dividers, pull-ups, current limiting, current sensing (shunt) |
| Capacitor | I = C × dV/dt; blocks DC, passes AC | Decoupling, filtering, timing, sample-and-hold |
| Inductor | V = L × dI/dt; resists changes in current | Switching regulators, EMI filters |
| Diode | Conducts one way, drops about 0.3 to 0.7 V | Reverse-polarity protection, clamping, flyback across relay coils |
| Transistor (BJT, MOSFET) | A small signal controls a large current | Switching LEDs, relays, motors; level shifting |
Voltage dividers
Two resistors scale a voltage down: Vout = Vin × R2 / (R1 + R2). Used to bring a battery or a 12 V rail into ADC range, and in every resistive sensor (thermistor, photoresistor, potentiometer) as one half of the divider.
Two things matter beyond the ratio:
- Source impedance: the divider looks to the ADC like a source with resistance
R1 ∥ R2. A large value slows the charging of the ADC's sample capacitor and gives low readings (see the ADC lesson). Add a capacitor at the ADC pin or buffer it. - Tolerance and temperature: 1% resistors give up to about 2% ratio error; for accuracy use 0.1% parts or calibrate.
RC filters
A resistor and capacitor make a first-order low-pass filter with cut-off frequency f_c = 1 / (2π × R × C). Below f_c signals pass; above it they fall by 20 dB per decade (a factor of 10 in amplitude for every factor of 10 in frequency).
Uses: removing noise before an ADC (the anti-aliasing filter), debouncing a button in hardware, smoothing a PWM output into an analog voltage.
#include <stdio.h>
#include <math.h>
int main(void) {
double pi = 3.14159265358979;
double r = 10e3, c = 100e-9; /* 10 kΩ and 100 nF */
double fc = 1.0 / (2 * pi * r * c);
printf("cut-off frequency: %.0f Hz\n", fc);
/* First-order low-pass gain at a few frequencies: |H| = 1 / sqrt(1 + (f/fc)^2) */
double freqs[] = { 10, 159, 1000, 10000 };
for (int i = 0; i < 4; i++) {
double ratio = freqs[i] / fc;
printf("%6.0f Hz: passes %5.1f%% of the amplitude\n", freqs[i], 100.0 / sqrt(1 + ratio * ratio));
}
/* Smoothing 20 kHz PWM: ripple is attenuated by about fc / f_pwm */
printf("20 kHz PWM ripple reduced to about %.1f%%\n", 100.0 * fc / 20000);
return 0;
}
The time constant τ = R × C (1 ms here) also tells you how fast the filtered signal settles: about 5τ to within 1%.
Operational amplifiers
An op-amp amplifies the difference between its two inputs by a huge gain. Used with feedback, it gives predictable circuits. Two rules analyse most of them: with negative feedback, the op-amp drives its output so the two inputs are at the same voltage, and the inputs draw (almost) no current.
| Circuit | Gain | Use |
|---|---|---|
| Voltage follower (buffer) | 1 | Present a high-impedance sensor to the ADC as a low-impedance source |
| Non-inverting amplifier | 1 + Rf / Rg | Amplify a small sensor voltage to use the ADC's full range |
| Inverting amplifier | −Rf / Rin | Gain with inversion, summing several signals |
| Differential / instrumentation amplifier | Set by resistors | Measure a small difference on top of a large common voltage: bridge sensors, current shunts |
| Active filter (Sallen-Key and others) | Shaped by R and C | Sharper anti-aliasing filters than a single RC |
| Comparator | Saturates high or low | Threshold detection with no ADC (comparators are a separate, faster part type) |
Limits to know when a reading is off: input offset voltage (microvolts to millivolts, amplified with the signal), rail-to-rail capability (many op-amps cannot drive their output within a volt of the supplies), bandwidth and slew rate, and input bias current through large resistors.
Interfacing common sensors
| Sensor | Output | Front end |
|---|---|---|
| Thermistor (NTC) | Resistance falling with temperature | Divider into the ADC; convert with a lookup table or the Steinhart-Hart equation |
| RTD (PT100/PT1000) | Small resistance change | Constant current or bridge plus amplifier, or a dedicated converter IC |
| Thermocouple | Microvolts per degree | Dedicated amplifier with cold-junction compensation (MAX31855 and similar) |
| Strain gauge, load cell | Millivolts from a bridge | Instrumentation amplifier or a 24-bit bridge ADC (HX711) |
| Current shunt | V = I × R_shunt | Current-sense amplifier, high-side or low-side |
| 4–20 mA loop | Current proportional to the measurement | Precision resistor (for example 150 Ω gives 0.6 to 3 V) |
| Microphone | AC signal of millivolts | Pre-amplifier with bias, or a digital MEMS microphone (I2S/PDM) |
Many modern sensors put the analog front end and ADC inside the chip and talk I2C or SPI. That removes most analog design from the product but not the need to understand the datasheet's accuracy, noise and filtering settings.
Grounding and noise
- Keep the analog ground return and digital switching currents apart on the board; route the ADC reference and sensor signals away from switching regulators and fast digital lines.
- Measure differentially where possible.
- A ratiometric measurement (sensor powered from the same reference the ADC uses) cancels supply variation.
- Average or filter in firmware only after the analog front end has removed what it can; digital filtering cannot undo aliasing.
Pitfall: A thermistor divider fed from 3.3 V continuously passes current, self-heats the sensor and drains a battery. Power it from a GPIO only while measuring, and wait a few time constants of any filter capacitor before sampling.
Interview question: How would you measure a 0 to 50 mV signal with a 12-bit, 3.3 V ADC?
Answer: Directly, 50 mV spans only about 62 of the 4096 codes, so resolution and offset errors dominate. Amplify it first with a non-inverting or instrumentation amplifier with gain around 60 (so full scale is about 3 V, leaving headroom), choosing a low-offset, rail-to-rail part, and add an anti-aliasing filter. Alternatively use an ADC with a programmable gain amplifier or a lower reference voltage, or a dedicated delta-sigma ADC. Calibrate offset and gain in production if accuracy matters.
Interview question: Why put a diode across a relay coil driven by a transistor?
Answer: A coil is an inductor and resists changes in current. When the transistor switches off, the collapsing magnetic field produces a large voltage spike of the opposite polarity that can exceed the transistor's rating and destroy it or disturb the circuit. A flyback diode across the coil gives that current a path to circulate and decay safely. The cost is slower release of the relay; a diode plus a Zener speeds it up.
Build it: measure the battery
This is step 3 of the module project. The lithium cell goes up to 4.2 V, but the ADC can only measure up to its 3.3 V reference. A resistor divider scales the voltage down, a capacitor filters it, and a table turns volts into the percentage on the LEDs.
Lab: A divider, an RC filter and a charge table
battery_mv(counts)converts a 12-bit ADC reading of the divider's midpoint back to the battery voltage. The ADC readsvref * counts / 4095at its pin, withVREF_MV3300. The divider hasR_TOP100 kΩ from the battery to the pin andR_BOTTOM220 kΩ from the pin to ground, so the battery voltage is the pin voltage times(R_TOP + R_BOTTOM) / R_BOTTOM. Multiply everything first, divide once at the end (in 64 bits).rc_cutoff_hz(r_ohm, c_nf)returns the cut-off frequency of an RC filter,1 / (2 * pi * R * C), rounded down. With C in nanofarads that is159154943 / (R * C_nF)(159154943 = 10^9 / (2 * pi)).charge_pct(mv)turns a cell voltage into a percentage with the provided table of points, using straight-line interpolation between the two points aroundmv. Below the first point it is 0 %, above the last 100 %.
Going deeper
Interview question: How would you design the front end between a bathroom scale's load cell and its ADC?
Answer: A load cell gives millivolts on a bridge, so it needs an instrumentation amplifier (or a 24-bit sigma-delta ADC with a built-in PGA like the HX711), a ratiometric reference from the same excitation so supply drift cancels, an anti-aliasing filter, and careful grounding. Then calibrate offset and gain in production and check drift over temperature.
Interview question: What does "ratiometric" measurement mean and why is it useful?
Answer: The sensor's excitation and the ADC's reference come from the same voltage, so the reading is a ratio that does not depend on that voltage's exact value. For a resistive divider or a bridge powered from the ADC reference, supply drift and tolerance cancel out, giving accuracy without a precision reference. It works only if the sensor's output really scales with its supply.
Interview question: An ADC input is filtered with an RC low-pass. How long should firmware wait after switching on the sensor before sampling?
Answer: The filter capacitor charges with time constant τ = R × C, reaching about 63% after one τ, 99% after about 5τ and within half an LSB of a 12-bit ADC after about 9τ (ln 8192 ≈ 9). So wait several time constants, plus the sensor's own settling time from its datasheet, before taking the reading.
Explain it: In your own words, explain why an anti-aliasing filter must be analog and placed before the ADC.
Answer: When a signal is sampled, any content above half the sampling rate is folded down and appears as a false lower frequency that is indistinguishable from real signal at that frequency. Once the samples are taken, the information needed to separate the false component from the real one is gone, so no digital filter can remove it. The only fix is to remove the high-frequency content before sampling, which requires an analog low-pass filter between the sensor and the ADC with its cut-off well below half the sample rate.