Skip to content
Tech Interview Prep
Technical interview guide

Sensors & Actuators

How a robot perceives its environment and acts on it: the hardware interface between software and the physical world.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Current NIST SP 800-82 Rev. 3, Arduino, Texas Instruments, Analog Devices, NXP I2C, OSHA, and IEC functional-safety guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-14

How do you calibrate an analog sensor, and what is the difference between zero error and span error adjustment?

Answer

Calibration fits the sensor's raw output to true physical units. For a sensor that is linear over its range, that fit is two numbers, offset and gain, and the two error types map onto them exactly. Zero error is the offset: a constant shift, the same magnitude at every input. Span error is the gain: a slope error that is zero at the zero point and grows to its maximum at full scale. You correct zero with one known low reference, span with a second known high reference, and in analog hardware you iterate because the two adjustments interact.

State these assumptions before you start: the sensor is linear (or piecewise linear) over the range that matters; the reference you calibrate against is traceable and at least ~4× more accurate than the target; and the ADC reference is stable. A ratiometric sensor must share its excitation reference with the ADC, or supply drift shows up as span error.

Zero vs span

Zero (offset) errorSpan (gain) error
Wrong term in y = m·x + bbm
Error at zero inputfull magnitudezero
Error at full scalesame as at zeromaximum
Typical causeamplifier offset, bridge imbalance, ADC offsetgain-resistor tolerance, reference error, sensor sensitivity tolerance
Correctionone-point trim at low referencetwo-point trim at high reference

Two-point procedure

  1. Apply a known low reference (0 psi, ice point, 4.00 mA). Record raw counts x₁.
  2. Apply a known high reference near full scale. Record x₂.
  3. Solve m = (y₂ − y₁)/(x₂ − x₁) and b = y₁ − m·x₁.
  4. In hardware, trim zero first, then span, then re-check zero. If the zero trim sits ahead of the gain stage, its offset is multiplied by the gain, so any span change moves the zero. Iterate until both endpoints are inside tolerance.
  5. In firmware the two constants come out of the two points in one shot: no iteration.
C
typedef struct {
    float raw_zero, raw_span;   // x1, x2
    float phys_zero, phys_span; // y1, y2
    float gain, offset;         // m, b
} SensorCal;

void compute_cal_constants(SensorCal *cal) {
    cal->gain   = (cal->phys_span - cal->phys_zero) /
                  (cal->raw_span  - cal->raw_zero);   // guard x2 != x1
    cal->offset = cal->phys_zero - cal->gain * cal->raw_zero;
}

float convert_raw_to_phys(const SensorCal *cal, float raw_adc) {
    return cal->gain * raw_adc + cal->offset;
}

Worked example. 0–100 psi sensor, 10-bit ADC, V_ref = 5.0 V, LSB = 5.0/1024 = 4.883 mV. Conditioning is scaled so 0 psi → 0 counts and 100 psi → 1023 counts.

  • 0 psi applied: x₁ = 51 counts. Zero error = +51 counts = +249 mV ≈ +5.54 psi.
  • 100 psi applied: x₂ = 972 counts. Measured span = 972 − 51 = 921 counts against an ideal 1023 → span error = −9.97% FS.
  • m = 100/921 = 0.10858 psi/count; b = −0.10858 × 51 = −5.537 psi.
  • At 900 counts: y = 0.10858 × 900 − 5.537 = 92.18 psi. The uncalibrated formula (900/1023 × 100) gives 87.98 psi: 4.2 psi low.
  • With no calibration, the 51 counts the sensor actually produces at true 0 psi is reported as 51/1023 × 100 = 4.99 psi of phantom pressure.

Failure modes and how to catch them

  • Nonlinearity (bow). Two-point calibration leaves a midscale residual. Check a third point at 50% FS; if the residual exceeds tolerance, fit a polynomial or lookup table instead.
  • Hysteresis. Up-scale and down-scale readings differ. Approach the same setpoint from both directions and compare.
  • Reference error. A 0.25%-accurate gauge caps your calibration at 0.25%. Use a reference at least 4× better than the target accuracy.
  • Temperature drift. Zero and span have separate tempcos; a sensor trimmed at 25 °C can be out of spec at 85 °C. Check the datasheet tempco or calibrate at two temperatures.
  • Quantization. A 4.883 mV LSB on a 10-bit ADC means you cannot resolve better than ~1 LSB without averaging.

When two-point is the wrong tool. Strongly nonlinear sensors (thermocouples, some RTDs) need multi-point fits. Sensors that ship with factory coefficients (IEEE 1451 TEDS) need those coefficients applied, not derived.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Choose between I2C, SPI, and UART for a sensor.

Answer

Assumptions first: the sensor sits on the same board as the MCU, 3.3 V logic, a few centimetres of trace, one to four sensors, sample rate below a few kHz. Change any of those and the answer moves.

The choice. Low-rate sensor, more than one device, two spare pins: I2C. One sensor that needs real bandwidth, an ADC or IMU sampled at kHz to MHz, SPI. UART only when the "sensor" is a module with its own MCU that streams bytes (GPS, many CO2 and particulate parts) or when the link runs over a cable.

Why. I2C is two open-drain wires, SDA and SCL, with pull-ups to Vdd. A device can only pull a line low; the high comes from the resistor. That makes the bus multi-drop and addressable (7-bit addresses, 112 usable) but it also makes rise time the limit: t_r = 0.8473·R·C. With 4.7 kΩ pull-ups and 100 pF of bus capacitance, t_r = 398 ns, which passes 100 kHz (limit 1000 ns) and fails 400 kHz (limit 300 ns). Drop to 2.2 kΩ and you get 186 ns. Bus capacitance is capped at 400 pF, so long cables or many devices force smaller resistors and more idle current.

SPI is push-pull: the driver actively pulls both high and low, so edges are fast and there is no pull-up/capacitance trade. Four wires (SCLK, MOSI, MISO, CS) plus one CS per extra peripheral. No address and no ACK: the peripheral never confirms it heard you, and CPOL/CPHA mode must match the datasheet or every bit shifts.

UART has no clock. Both ends agree on a baud rate and the receiver samples mid-bit; over a 10-bit frame the two clocks must stay within roughly 2–3% or you get framing errors. Two wires, strictly point-to-point.

When each is wrong. I2C is wrong when you need sustained >1 MHz, when the sensor is off-board (capacitance), or when a device can hold SDA low and hang the whole bus. SPI is wrong when you have many devices (pins grow as 4+N), when the link is noisy and you need error detection, or when you need hot-plug. UART is wrong for more than two devices and for clock-accurate high rates.

Failure modes and detection.

  • I2C bus stuck low: a peripheral holds SDA after a glitch. Detect: SCL toggles, SDA never releases. Recover by clocking 9 pulses then issuing STOP; if that fails the bus is down until power cycle.
  • I2C NACK: 9th bit stays high. Device absent or busy. Retry with backoff.
  • SPI mode mismatch: reads shifted one bit, garbage. Detect by reading a known device-ID register.
  • UART baud mismatch: framing-error flag set, bytes garbage. Detect by checking the error flag or a known header.
I2CSPIUART
wires24 (+1 CS/device)2
rate100k/400k/1M/3.4M10–50 MHz typ9.6k–115.2k typ, to ~3M
topologymulti-drop, addressedmulti-drop via CSpoint-to-point
clocksynchronous, sharedsynchronous, sharednone, agreed baud
error detectACK/NACKnone in protocolparity/framing

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Define sensor and actuator reliability metrics.

Answer

Core answer (first 90 seconds). Reliability metrics for a sensor or actuator answer three questions: does the reading or motion match physical truth, does a failure announce itself, and how fast does the loop reach a safe state. Accuracy, repeatability and drift cover the first. Diagnostic coverage, PFH/PFDavg and proof-test coverage cover the second. Safe-state transition time and spurious-trip rate cover the third. ENOB, jitter and MTBF are just ways of putting a number on one of those three.

Definitions.

MetricDefinitionIllustrative figure
Accuracy / uncertaintymax deviation from true value over a stated range and temperature band±0.1% of span, industrial pressure transmitter
Repeatabilityspread of readings for the same input approached from the same direction±0.05% of span
Driftoutput change at fixed input over time0.1% of span/year, or 20 ppm/°C
Noise / ENOBENOB = (SINAD − 1.76) / 6.0212-bit ADC at 68 dB SINAD → 11.0 ENOB
Latency / jitterphysical change to value at the controller; jitter is its spread2 ms sensor + 1 ms bus + 5 ms PLC scan
Valid-data availabilityfraction of time the value sits inside its validity bounds99.9%
Diagnostic coverage (DC)fraction of dangerous failures the diagnostics detect60–90% low, 90–99% medium, ≥99% high (ISO 13849-1)
PFH / PFDavgdangerous failure rate per hour (high demand) / average probability of failure on demand (low demand)SIL 2 high demand: 10⁻⁷ to 10⁻⁶ PFH
Proof-test coveragefraction of dangerous undetected failures the proof test reveals95%
MTBF / FIT1 FIT = 1 failure per 10⁹ h; MTBF = 10⁹ / FIT500 FIT → MTBF 2×10⁶ h
Spurious-trip ratesafe failures that stop the process1 per 10 years
Safe-state transition timefault detection to output in safe state<100 ms

Trade-offs. Diagnostics are not free. Pulse-testing a valve or adding line-break detection raises DC toward 99% and buys you PL e territory, but every added check is another way to trip a running process: a spurious trip on a continuous line costs a shutdown, so DC and spurious-trip rate are tuned against each other, not maximised independently. Proof-test interval trades directly against PFDavg and against production loss. Filtering trades noise against latency: averaging 16 samples cuts random noise by 4× (√16) but adds 16 sample periods of delay, which matters if the loop closes at 1 ms. Redundancy follows the same shape: 1oo2 lowers PFD but roughly doubles spurious trips; 2oo3 balances both.

Failure modes and how they are caught. An open or shorted 4–20 mA loop is caught by NAMUR NE 43 bounds: valid signal is 3.8–20.5 mA, and <3.6 mA or >21.0 mA is a fault: within one scan. A stuck sensor is caught by a rate-of-change or variance monitor, with detection latency equal to the window length. Slow drift is caught only by calibration or by cross-checking a diverse second sensor. Actuator stall is caught by current signature plus no position change within one command cycle; winding overtemperature by an embedded RTD.

Worked check. A 4–20 mA pressure transmitter on a low-demand SIL 2 loop, λDU = 5×10⁻⁷ failures/hour (500 FIT). With a one-year proof-test interval, PFDavg ≈ λDU × T / 2 = 5×10⁻⁷ × 8760 / 2 = 2.2×10⁻³: inside the SIL 2 band (10⁻³ to 10⁻²). Halving the interval to six months gives 1.1×10⁻³, still SIL 2. You need T ≈ 4000 h (about 5.5 months) to cross 10⁻³ into SIL 3, and that only holds if the proof test actually exercises the failure modes you claim. The price is a plant shutdown twice a year instead of once.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Evaluate whether increasing ADC resolution improves a design.

Answer

Short answer: usually not by itself. Resolution only buys accuracy if the rest of the chain delivers more effective bits than you already have. Compute the LSB you need from the usable input span, then compute the ENOB the chain actually achieves from its input-referred noise. If ENOB is already below the nominal bit count, a higher-resolution converter changes nothing.

Assumptions for the numbers below: 3.3 V reference, full-scale sine, signal of interest spans 0–100 mV, target resolution 10 µV, input-referred noise 200 µV RMS.

Mechanism. Nominal bits set the quantization step; noise sets how many of those steps are real. An ideal N-bit converter has quantization noise LSB/√12, so each extra bit needs 6.02 dB more SNR to mean anything. ENOB = (SINAD − 1.76)/6.02. Two things eat bits: the noise floor, and not using the full range.

Arithmetic. 16-bit at 3.3 V: LSB = 3.3/65536 = 50.4 µV. A 100 mV signal uses 3.03% of full scale, which costs log2(3.3/0.1) = 5.0 bits: you are down to about 11 bits of span before noise. Now the noise: full-scale sine RMS = 1.1668 V; SINAD = 20log10(1.1668/200 µV) = 75.3 dB; ENOB = (75.3 − 1.76)/6.02 = 12.2 bits. Relative to the 100 mV signal you actually care about, that is roughly 12.2 − 5.0 ≈ 7 usable bits. An 18- or 20-bit part in the same chain still gives about 7 bits. To genuinely reach 16 bits you need input-referred noise below the 16-bit quantization floor of 50.4/√12 = 14.5 µV RMS: roughly 14× lower than what you have.

Alternatives. (a) Oversampling and averaging: white noise falls 3 dB per doubling, so 4× oversampling buys 1 bit. Gaining 5 bits needs 2^10 = 1024×: 10 kSPS becomes 10.24 MSPS. (b) Fix the front end: lower-noise amplifier, lower source impedance, an RC/anti-alias filter to cut noise bandwidth, and gain to use more of the range. (c) Calibration removes offset, gain and linearity error but not noise: it does not buy bits. Do not increase resolution when the chain is noise-limited, when you need speed (higher-resolution SARs are slower and cost more), or when the sensor itself is the limit.

Failure modes.

  • Noise floor dominates. Detect: sample a fixed DC input 10k times and compute the standard deviation in codes; σ > 1 LSB means you are losing bits. Cost: a 16-bit part behaving like a 12-bit one.
  • Reference error and drift. 0.1% initial tolerance on 3.3 V = 3.3 mV = 65 LSB at 16-bit; 10 ppm/°C over 40 °C adds 1.3 mV = 26 LSB. Detect: measure a known source or go ratiometric. Cost: per-unit gain calibration.
  • Incomplete settling. A 4 pF SAR sampling cap with a 10 kΩ source gives τ = 40 ns; you need about 10τ = 400 ns of acquisition. A 200 ns window leaves code-dependent error. Detect: sweep source resistance and watch INL/DNL degrade.
  • Missing codes. Detect: histogram a slow ramp; DNL > 1 LSB shows gaps.

If ENOB is below nominal, the next dollar goes to the front end, not the converter.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Choose sampling rate and anti-alias filtering.

Answer

Four numbers decide this before any part is picked: the band to preserve, the worst out-of-band interferer, the in-band flatness budget, and the ADC's own limits. Take a concrete case: an 8-channel multiplexed DAQ, signal of interest DC–10 kHz, 16-bit SAR, 2.5 V full scale, and a switching supply whose harmonics reach 100 mV at the pin. I want 0.1 dB flatness to 10 kHz and any aliased interferer below 1 LSB.

The interferer, not Nyquist, sizes the filter. 1 LSB is 2.5/65536 = 38 µV, so a 100 mV tone must be knocked down 20·log10(0.1/38e-6) = 68 dB before it folds into the band.

Nyquist for 10 kHz is 20 kSPS, which leaves a 10–20 kHz transition band, one octave, and forces a filter so sharp it is unusable. Oversampling trades ADC speed for analog slack. Here is the order each candidate rate demands, from a Butterworth that is 0.1 dB down at 10 kHz and 68 dB down at the first alias band:

Python
import math

FS_V, BITS, F_P = 2.5, 16, 10e3      # full scale, bits, top of band
V_INT = 0.1                            # worst interferer at the pin, V
lsb = FS_V / 2**BITS
A_need = 20*math.log10(V_INT / lsb)    # dB the filter must deliver

def order(fs):
    f_stop = fs - F_P                  # first alias band edge
    ratio = (10**(A_need/10) - 1) / (10**(0.1/10) - 1)
    n = math.ceil(math.log(ratio) / (2*math.log(f_stop/F_P)))
    return f_stop, n

print(f"LSB   = {lsb*1e6:.1f} uV")
print(f"A_need= {A_need:.1f} dB")
for fs in (25e3, 50e3, 500e3):
    f_stop, n = order(fs)
    print(f"fs={fs/1e3:5.0f} kSPS  f_stop={f_stop/1e3:5.0f} kHz  order={n}")

Tracing it: lsb = 2.5/65536 = 38.1 µV; A_need = 20·log10(0.1/3.8147e-5) = 68.4 dB; ratio = (10^6.837 − 1)/(10^0.01 − 1) = 2.95e8. The loop then computes ln(ratio)/(2·ln(f_stop/f_p)) and rounds up: 25 kSPS gives ln(2.95e8)/(2·ln(1.5)) = 24.05 → 25; 50 kSPS gives ln(2.95e8)/(2·ln(4)) = 7.03 → 8; 500 kSPS gives ln(2.95e8)/(2·ln(49)) = 2.51 → 3.

fsfirst alias bandf_stop/f_passButterworth order for 68 dB
25 kSPS15–25 kHz1.525
50 kSPS40–60 kHz48
500 kSPS490–510 kHz493

A 25-pole analog filter is not a design. At 500 kSPS the first band that aliases into 0–10 kHz is 490–510 kHz, so the filter has 10 kHz to 490 kHz to roll off: 5.6 octaves of slack. I pick a 4-pole Butterworth with fc = 16 kHz: 0.1 dB at 10 kHz fixes (10/fc)^8 = 10^0.01 − 1 = 0.0233, so fc = 16 kHz, and at 490 kHz the ideal response is (490/16)^8 ≈ 7.7e11, i.e. 119 dB. Real op-amp GBW and parasitics cap that near 60–70 dB, which is why the 68 dB requirement is the one that matters: you are not relying on the asymptote.

The trade-off is real. A low rate like 50 kSPS saves ADC power and data rate but needs an 8-pole filter whose corner moves with every 5% capacitor. Oversampling buys filter tolerance at the cost of ADC throughput and a decimation stage. Delta-sigma pushes it further: the modulator oversamples so hard a single RC is enough and the digital filter does the sharp work, but you pay group delay and passband droop.

Then the things that bite. Aperture jitter sets a noise floor of −20·log10(2π·f_in·σ_t); for 96 dB at 10 kHz, σ_t must stay under 1.58e-5/(2π·10e3) = 250 ps. Easy at 10 kHz, brutal at 1 MHz: jitter only shows up when f_in climbs. Mux settling: at 500 kSPS each conversion gets 2 µs, and settling to 0.5 LSB needs ~11.8 time constants, so with 1 µs of acquisition the source-plus-mux RC must be under 85 ns. About 1 kΩ into 85 pF. Miss it and you get channel-to-channel crosstalk. Filter tolerance: 5% caps move fc to 15.2 kHz and the droop at 10 kHz becomes 0.15 dB, over budget. Use 1% caps or back the corner off to 18 kHz.

Detection: sweep a sine past fs/2 and watch the FFT. A real alias folds back and moves the wrong way. Drive one mux channel full-scale DC and the next at zero; the zero channel must read under 1 LSB. Measure SNR with a clean full-scale tone at 10 kHz; if it is below the datasheet, suspect the clock, not the ADC.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design and validate an oversampling strategy.

Answer

First 60-120 seconds: I would clarify signal bandwidth fs_out/2, required ENOB, latency budget, input and reference noise, and headroom. Assume white quantization noise dominates and the input is not clipping. Then oversample the ADC at fs_os = OSR * fs_out, and decimate/filter back to fs_out. For white noise, SNR improves by 10log10(OSR), which is 3.01 dB per doubling, and ENOB improves by 0.5 bit per doubling. To go from 12 to 16 ENOB, OSR = 2^(2(16-12)) = 256, so a 100 kSPS output needs 25.6 MSPS conversion. If input noise, 1/f noise, or reference noise is already above the target, oversampling buys nothing.

Mechanism: quantization noise power q^2/12 is spread over fs_os/2. The digital decimation filter passes only fs_out/2, so only 1/OSR of that noise remains. Signal power is unchanged. That is the whole gain. The decimation filter also provides anti-alias protection: its stopband must attenuate what would fold into fs_out/2. If the modulator shapes noise, in-band noise falls faster. An ideal Lth-order sigma-delta gives 6L+3 dB per doubling: L=1 is 9 dB per doubling, L=2 is 15 dB per doubling, and ENOB improves by 1.5 or 2.5 bits per doubling respectively.

OSRSNR gain vs OSR=1ENOB gain
23.01 dB0.5 bit
1612.0 dB2.0 bit
25624.1 dB4.0 bit
102430.1 dB5.0 bit

Assumes ideal decimation and white quantization noise.

Design trade-offs: alternatives are a higher-resolution SAR, a delta-sigma converter, analog gain, or chopping. Deciding criteria are required ENOB, signal bandwidth, latency, power, and whether the dominant noise is quantization or something else. Oversampling is wrong when the input is already noise-limited, when 1/f or reference noise dominates, when interference is coherent, when the latency budget is below the decimation filter group delay, or when fs_os cannot be powered. Cost is real: an N-tap FIR at fs_os costs about N * fs_os MAC/s. For N=64, OSR=256, fs_out=100 kSPS, that is 64 * 25.6 MSPS = 1.64 G MAC/s. Group delay is about N/(2*fs_os); 64 taps at 25.6 MSPS is 1.25 us, and 256 taps is 5 us. A delta-sigma can be milliseconds.

Validation: collect 1M DC samples at mid-scale. For a 12-bit ADC, OSR=256, ideal output noise sigma is q/sqrt(12*256) = 0.018 input LSB, or 0.29 LSB at 16-bit output. Check mean, sigma, missing codes, DNL, and INL. A bimodal or gapped histogram means missing dither or correlated noise; add dither and verify histogram flattening. For dynamic test, use a coherent sine, take an FFT, compute SINAD, and compute ENOB = (SINAD - 1.76)/6.02. Compare against the predicted 4-bit gain. Spurs indicate interference or reference drift. Measure a step response for group delay and settling to 0.5 LSB; ringing or slow settling means the decimation filter is too long for the latency budget. Repeat at temperature extremes, at clipping, with reference drift, and with dither removed. If measured gain is below prediction, the noise was not white quantization noise.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Create a sensor measurement requirements and error budget.

Answer

Core answer. Fix the measurand and the budget first, then allocate. Say it out loud: gauge pressure of ISO VG 46 hydraulic oil, 0–10 bar span, 4–20 mA output into a 16-bit ADC, ambient 0–70 °C, 5-year life, target ±0.5 % of span (±50 mbar) at any reading. Then build the budget as a table, because the arithmetic is what decides whether the requirement is buyable.

TermType% FSSource
Nonlinearity (BFSL)systematic0.25datasheet
Hysteresissystematic0.10datasheet
Thermal zero shiftsystematic0.500.011 %/°C over 0–70 °C
Thermal span shiftsystematic0.50same
Reference driftsystematic0.10ADC ref, 10 ppm/°C
Calibration standardsystematic0.05class 0.05 deadweight tester
Repeatabilityrandom0.05datasheet
ADC quantizationrandom0.001510 bar / 65536 = 0.153 mbar
Noise (rms)random0.02measured

Why the two columns add differently. Systematic terms are correlated: nonlinearity, thermal shift and reference drift all push the reading the same way at the same operating point, so worst case you sum magnitudes. 0.25 + 0.10 + 0.50 + 0.50 + 0.10 + 0.05 = 1.50 % FS. Random terms are independent and zero-mean, so variances add: √(0.05² + 0.0015² + 0.02²) = 0.054 % FS. Combine the two groups in quadrature: √(1.50² + 0.054²) = 1.50 % FS. That is 3× the 0.5 % budget, and the thermal pair alone is 1.0 % of it.

The trade-off and the criterion. Three ways to close the gap. (a) Buy a 0.1 % FS compensated transducer: nonlinearity 0.25→0.10, hysteresis 0.10→0.05, thermal 1.0→0.2, giving 0.10 + 0.05 + 0.20 + 0.10 + 0.05 = 0.50 % FS, exactly on budget, at roughly 5× the unit cost. (b) Keep the cheap sensor, add a thermistor on the body, and characterize zero and span against temperature in firmware: this removes the 1.0 % thermal term and leaves 0.50 % FS, at the cost of a calibration step and a temperature channel. (c) Narrow the operating range to 20–40 °C: thermal falls to ~0.3 %, total ~0.8 % FS. Still over. The deciding criterion is volume: (b) amortizes over a production run, (a) wins for a one-off or low-volume build, and (c) only works if the environment is genuinely controllable.

Failure modes and how you catch them. Cycle 0→10→0 bar in 1 bar steps and compare up versus down at 5 bar; a difference above 10 mbar (0.1 % FS) means the diaphragm is yielding or the unit was overpressured. Soak at 0 °C and 70 °C and read zero; a shift above 50 mbar points at the compensation network or a failing strain-gauge bond. Mount at 15 N·m then 25 N·m and read zero; a shift above 10 mbar is mechanical cross-sensitivity, so the torque belongs in the work instruction. Recalibrate at six months; zero movement above 20 mbar means the sensor is aging out of the 5-year claim.

What calibration can and cannot remove. Calibration removes zero offset, span error, and, with five or more points, nonlinearity, because each is a deterministic function of the input. It cannot remove hysteresis, which depends on the path taken to reach a pressure; drift that happens after the calibration date; random noise; or cross-sensitivity to variables you do not measure. Those four stay in the budget as residual terms, which is why the budget is written before the sensor is chosen, not after.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design grounding, shielding, and isolation for analog sensing.

Answer

Assume a 24-bit ADC with a 2.5 V reference, so 1 LSB is 149 nV. The sensor is 10 m away, and there's a 1 A switching load nearby. The core answer: control return currents with a star ground, use differential inputs to reject common-mode, shield the cable, and isolate only when common-mode exceeds the amplifier's input range or safety requires it.

Grounding. Every signal has a return. If a 1 A load shares 10 mΩ of ground trace with the sensor return, it develops 10 mV: that's 67,000 LSBs. So I run a dedicated return for the sensor and join analog and digital grounds at one point under the ADC. That stops return-current sharing because the high-current path no longer flows through the sensitive reference.

Differential inputs. An INA128 has 120 dB CMRR at DC, but only 80 dB at 10 kHz. A 1 V common-mode at 10 kHz then produces 100 µV of error: 671 LSBs. So I keep the common-mode within the amp's input range. If it's not, I isolate. The AMC1301 isolation amplifier gives 7 kV peak isolation and 200 kHz bandwidth, but costs about $8 and adds 3 µs of delay. A digital isolator like the ADuM1201 is about $1.50 and 25 Mbps, but it only isolates digital signals, so the ADC must be on the isolated side.

Shielding. For low-frequency signals, ground the shield at the source end only. That breaks the ground loop. For RF, ground both ends if you have a solid chassis ground. A 1 cm² loop in a 1 mT 50 Hz field picks up 31 µV; twisting the pair reduces the loop area by about 10x. Use a guard ring around high-impedance nodes, driven at the same potential, to reduce leakage.

Isolation. Use it when common-mode exceeds the amplifier's supply rails, or when safety requires it. For medical, IEC 60601-1 2 MOPP at 250 Vrms means 8 mm creepage and a 4 kVrms dielectric test. Don't isolate if you don't need it: it adds cost, power, and delay.

Failure modes and detection:

FailureSymptomDetection
Ground loop50/100 Hz humFFT of ADC samples shows peak at line frequency
Common-mode saturationOutput stuck at railRead code is 0 or full-scale
Isolation breakdownLeakage current > 10 µAHipot test at 1.5x rated voltage for 60 s
EFT (IEC 61000-4-4, 2 kV, 5/50 ns)Bit errorsCompare ADC readings during burst
ESD (IEC 61000-4-2, 8 kV contact)Latch-up or resetCurrent spike or reset flag

Trade-off: single-point ground is good below 10 kHz but bad for RF; multi-point is the opposite. Differential inputs reject common-mode but need matched source impedances. Isolation breaks loops but costs money and bandwidth. Pick based on the dominant noise frequency and safety class.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design a robust digital input for a mechanical switch.

Answer

Core answer (first 90 seconds). Assume a 3.3 V MCU, a panel or limit switch on 1–10 m of cable, and "robust" meaning it survives contact bounce, EMI, and wiring faults without emitting a false event. My default: a 10 kΩ pull-up to 3.3 V at the MCU pin, a 1 kΩ series resistor and 100 nF cap at the pin forming a ~1 ms RC, feeding a Schmitt-trigger input (74HC14, or the MCU's own hysteresis), plus a firmware state machine that needs 5 ms of stable low to register a press and 20 ms of stable high to register a release. The asymmetry is deliberate.

Why bounce happens and what each stage does. Metal contacts don't close cleanly: they collide, arc, and re-open several times. A cheap tactile switch bounces for 1–10 ms; a large panel button with a long actuator can hit 20 ms. The RC does not need to settle to the rail; it only needs to slew the node past the Schmitt's hysteresis band, which is roughly 0.5–0.9 V depending on Vcc (74HC14 datasheet). With τ = RC = 10 kΩ × 100 nF = 1 ms, a 3.3 V swing crosses a 0.6 V band in well under 1 ms, so the RC swallows the fast edges and the hysteresis cleans up the slow ones. Drop the hysteresis and a slow RC edge parked near the threshold will chatter on noise.

Why press and release differ. Contacts are usually noisier on release: worn faces, arcing, spring rebound. On a safety input you also want to react to a press fast but never declare release on one glitch. So 5 ms to press, 20 ms to release.

C
// 1 kHz tick, 3.3 V MCU, active-low switch. raw: 0 = pressed, 1 = released
#define PRESS_MS   5
#define RELEASE_MS 20
static uint8_t  stable = 1;   // 1 = released
static uint16_t count  = 0;

void tick(uint8_t raw) {
    if (raw != stable) {
        if (++count >= (raw == 0 ? PRESS_MS : RELEASE_MS)) {
            stable = raw; count = 0; emit(stable);
        }
    } else {
        count = 0;
    }
}

Trace: a 3 ms glitch drives raw to 0, count reaches 3, then raw returns to 1 and count resets. No event. A real press holds raw at 0, count hits 5, stable flips, press emitted 5 ms after contact. Release needs 20 ms of stable high. So press latency is 5 ms, release latency 20 ms.

Trade-offs. Hardware RC + Schmitt costs three parts and works while the MCU sleeps or feeds a hardware interlock. Firmware debounce costs nothing but needs a periodic tick and wakeups. Use hardware when the input must wake the MCU or drive a safety relay; use firmware when you already have a 1 kHz tick and want tunable timing. Don't stack both with the same time constant: you add the latencies.

Failure modes and detection. A welded contact reads pressed forever; detect by expecting periodic release or cross-checking a redundant input. A broken wire with a plain pull-up reads "released": indistinguishable from an open switch. Fix it with a three-state input: put a 10 kΩ resistor across the switch at the far end.

ConditionNode voltage (3.3 V, 10 kΩ pull-up, 10 kΩ across switch)Reads
Switch closed0 Vpressed
Switch open, wire intact1.65 Vopen
Wire broken3.3 Vfault

A short to ground reads pressed; a short to Vcc reads released. For long cable, keep the RC at the MCU pin (the cable is the antenna, the cap shunts it) and add a series resistor plus TVS for ESD. Note the 10 kΩ pull-up draws 0.33 mA while pressed; on a coin cell, go to 100 kΩ or poll the switch.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Choose PWM frequency and duty cycle for an actuator.

Answer

Assumptions I'd state first: a 24 V brushed DC gearmotor actuator, H-bridge of N-channel MOSFETs with 100 ns total rise+fall, armature inductance L = 1.2 mH, winding resistance 2.4 Ω, rated 2 A, MCU timer clock 168 MHz, sign-magnitude drive.

The choice: 20 kHz, duty = V_target / 24 V with a stall floor. Here's why those two numbers.

Frequency: ripple current sets the lower bound. Peak-to-peak ripple is ΔI = V·D(1−D)/(L·f), worst at D = 0.5, so ΔI = V/(4·L·f). At 20 kHz: 24 / (4 × 1.2e-3 × 20e3) = 0.25 A, 12.5% of rated. At 5 kHz it's 1.0 A: 50% ripple, which heats the winding and erodes the brushes. So 5 kHz is out on ripple alone, before noise.

Frequency: switching loss sets the upper bound. Energy per transition is ½·V·I·(t_r+t_f), so P = ½·V·I·(t_r+t_f)·f per switching FET. At 20 kHz, 24 V, 2 A, 100 ns: 0.048 W per FET, ~0.1 W for the pair, against ~0.4 W conduction (I²·R_ds(on) × 2). At 100 kHz that becomes ~0.5 W: now comparable to conduction, so you're paying real heat for ripple you don't need.

Frequency: resolution ties it to the timer. Counter top = f_clk / f = 168e6 / 20e3 = 8400 counts ≈ 13 bits, a 0.012% duty step. If you insisted on 16-bit you'd need f_clk ≥ 65536 × f; at 20 kHz that's 1.31 GHz, so you'd have to drop to ~2.5 kHz: back inside the audible band. 20 kHz at 13 bits is the trade.

fΔI at D=0.5switching loss (2 FETs)audible
5 kHz1.0 A (50%)0.025 Wloud whine
20 kHz0.25 A (12.5%)0.1 Wno
100 kHz0.05 A (2.5%)0.5 Wno

20 kHz sits just above the 20 Hz–20 kHz audible band, so the motor doesn't sing, and it's the lowest frequency that clears the ripple target.

Duty cycle. Average voltage is V_avg = D·V_bus minus FET drops and dead-time loss. For 12 V average, D = 0.5. The floor matters more than the map: below roughly 10–15% duty the motor can't break static friction, so it stalls and dissipates I²R without moving. Clamp to 0 and coast rather than hold a stalling duty. Above ~95%, dead-time and FET drop mean you never quite reach full bus voltage: budget for it if you need rated speed.

When I'd choose differently. A coreless or low-inductance motor (L ≈ 50 µH) needs 40–60 kHz to keep ripple sane, and you accept the switching loss. A high-current actuator (20 A) with slow gate drive pushes the other way: drop to 8–10 kHz and accept the whine, because switching loss scales with current. If the actuator is a heater or solenoid where ripple doesn't matter, frequency is chosen purely for EMI and audible noise.

Failure modes and how I'd catch them. Shoot-through from too-short dead time shows as FET heating at idle: scope the gate waveforms. Ripple heating shows as winding temperature rising with duty but not speed. Stall at low duty shows as current climbing with no rotation: log commanded duty against encoder counts. Audible whine means f drifted into the band or the timer prescaler is wrong: measure with a mic. EMI on the supply shows as ADC noise: check with the motor running at 20 kHz versus off.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design a low-side solenoid driver.

Answer

Assume a 12 V nominal supply, a 6 Ω / 20 mH coil drawing 2 A steady and about 2.5 A inrush, 100% duty to hold, and a release spec under 5 ms. Those four numbers decide the rest of the design.

The switch goes low side: N-channel MOSFET, source to ground, drain to the coil's return, coil's other end on +12 V. Ground-referenced gate drive is the whole reason: a high-side N-channel needs a charge pump or bootstrap, and a P-channel needs a level shifter and has worse Rds(on) per dollar. Size Vds for the worst transient, not the nominal rail: 60 V minimum on a 12 V automotive bus, 100 V if your clamp sits above 40 V. Use Rds(on) at the gate voltage you actually drive, not the 10 V headline figure. An IRLZ44N (55 V, 0.028 Ω max at Vgs = 5 V) dissipates 2² × 0.028 = 0.11 W: no heatsink. Gate: 47 Ω series to tame dV/dt and ringing, 10 kΩ gate-source pull-down so a floating MCU pin cannot turn the FET on.

Turn-off is where the design lives. The coil stores ½LI² = ½ × 20 mH × (2 A)² = 40 mJ, and it leaves through whatever clamp you fit. The clamp voltage sets the release time, because the current decays at di/dt = V/L:

ClampPeak VdsTime to 10% of 2 ANotes
Freewheel diode (SS34)Vbus + 0.5 Vτ = L/R = 3.3 ms, so 2.3τ ≈ 7.7 msCheapest, quietest, misses a 5 ms release spec
TVS (SMAJ33A)53.3 V max clampL·I/V = 20 mH × 2 A / 33 V ≈ 1.2 msFast, more radiated EMI, forces a 100 V FET
Active clamp / Zener + FETSet by design, e.g. 40 VUnder 1 msFastest and controlled, most parts and cost

The diode is the right answer when release timing is loose and EMI is tight; do not use it when the spec is under 5 ms. The TVS is the right answer when you need speed and can afford the Vds headroom: note that a 60 V FET against a 53.3 V clamp leaves almost nothing, so the TVS choice drags the FET choice with it.

Failure modes worth designing for, each with a way to see it:

  • Open coil. No current, and no clamp event on turn-off. Detect by current sense reading near zero during on-time, or by the drain failing to spike above Vbus when the FET opens.
  • Coil shorted to ground. Current is limited only by wiring; the fuse or a comparator tripping at 4 A within 100 µs is the only thing between you and a burnt harness.
  • FET stuck on. The coil sees 12 V continuously and dissipates 12²/6 = 24 W, which cooks it in seconds. Detect with a current-sense hold timeout: cut drive if current stays above threshold past, say, 500 ms.
  • Brownout. Below gate threshold the FET goes linear; 2 A across 6 V is 12 W in a TO-220 and it runs away thermally. Detect with UVLO on the gate supply, disabling below 8 V.
  • Hot turn-off. Copper resistance rises about 0.4%/°C, so 6 Ω at 20 °C is roughly 8 Ω at 105 °C and hold current falls from 2 A to about 1.5 A. Detect by sensing current at the end of the hold window, not at the start.

Verify the clamp choice on the bench with a scope on drain and a current probe: confirm the peak Vds against the FET rating at hot turn-off, and confirm release time at the lowest supply you will ever see.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and protect a motor actuator channel.

Answer

Assumptions. 12 V nominal (9–16 V) brushed DC gearmotor on a leadscrew: 0.6 Ω winding, 1 mH rotor inductance, 0.6 A no-load, 2.5 A running under rated load, 20 A stall at 12 V. Duty cycle 10% (2 s on, 18 s off), 25 °C ambient, 60 °C inside the enclosure. One bidirectional channel, no regenerative braking required. Figures are illustrative for this actuator class; substitute your motor's datasheet values.

The 90-second answer. Size the H-bridge for stall current, not run current, because stall is the only condition where the silicon sees peak current and worst thermal stress at the same time. Then add a current-sense loop that chops at ~1.5× run current and hard-latches off after a bounded time, so the driver never has to survive stall continuously. Clamp the inductive kick with rail capacitance plus a TVS, and detect the four faults that actually happen: jam, short, open winding, brownout.

Sizing. At zero speed back EMF is zero, so I = V/R = 12/0.6 = 20 A. That is the number the driver's peak rating and the supply's transient response must cover. Steady-state thermal sizing uses run current: with two low-side FETs on, P = I²·RDS(on) = 2.5² × 0.1 = 0.63 W. A SOT-23 driver at 200 °C/W would rise 125 °C: too hot. A SOIC-8 with thermal pad at 50 °C/W rises 31 °C, fine. The package, not the current rating, decides.

Flyback. Turning off 20 A through 1 mH dumps ½LI² = 0.2 J into the rail. ΔV = I√(L/C). With 470 µF that is 29 V on top of 12 V: 41 V, which kills a 40 V driver. With 2200 µF it is 13.5 V, so a 37 V-rated driver (DRV8874) survives with a 24 V TVS as backup. The clamp path is motor → low-side body diode → bulk cap.

Trade-off: integrated vs discrete.

integrated (DRV8874)discrete (BTS7960 pair)
peak current6 A43 A
protectionUVLO, OCP, OTP built inexternal comparator + gate drive
board area~30 mm²~200 mm²
when to usestall ≤ 6 A, duty ≤ 20%stall > 10 A or 100% duty

Pick integrated when stall current fits and the duty cycle lets the package cool between strokes. Go discrete when the actuator must hold torque continuously, because an integrated part's thermal pad cannot dump 0.6 W indefinitely in a sealed enclosure.

Failure modes.

faultdetectionthresholdresponse
jamcurrent high, no encoder edge> 3.75 A for 150 mschop 500 ms, then latch off
output shortcomparator on shunt> 6 A, < 10 µshardware latch off
open windingno current while PWM on< 50 mA for 50 msreport, stop
brownoutsupply divider< 9 VUVLO disables, re-home on recovery

Shunt 10 mΩ, gain 20 → 0.2 V/A; comparator at 0.75 V trips at 3.75 A.

C
// stall detect, 1 kHz tick
if (current > 3.75f && !encoder_edge) {
    if (++stall_ms > 150) { chop(); if (++chop_ms > 500) latch_off(FAULT_JAM); }
} else { stall_ms = 0; chop_ms = 0; }

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Choose open-loop versus closed-loop actuation.

Answer

Core answer

Default to open loop when you can bound the output error across the whole operating envelope and that bound sits inside tolerance. Go closed loop when the error is dominated by something you cannot predict (load, disturbance, drift, wear) or when you must detect a stall.

"Predictable enough" is a number, not a feeling. Build the open-loop error budget from every term you can name: actuator resolution, transmission error, thermal expansion, supply variation, load-induced deflection. If the worst case over the full envelope is under half your tolerance, open loop is defensible. If any single term can exceed tolerance on its own, or the load is not known at design time, you need feedback.

Worked budget: stepper-driven linear stage

200 steps/rev, 8× microstepping = 1600 microsteps/rev; 2 mm/rev leadscrew → 1.25 µm per microstep. Move 50 mm = 40,000 microsteps.

termsourceworst case over 50 mm
resolution1.25 µm/microstep±1.3 µm
leadscrew lead error±50 µm/300 mm rolled screw±8.3 µm
thermalsteel, 11.7 µm/m/°C, 10 °C rise±5.9 µm
total±15.4 µm

Tolerance is ±50 µm, so open loop passes with 3× margin: no encoder, no tuning, no sensor failure mode. Tighten tolerance to ±10 µm, or add a load that varies with the part, and the budget fails: now you add a 1 µm linear encoder (a few hundred dollars plus wiring) and a PID loop.

Trade-offs

open loopclosed loop
hardwaremotor + driver+ sensor, wiring, ADC
errorset by budget, uncorrectedcorrected to sensor accuracy
tuningnoneloop gain, filter, anti-windup
new failure modessilent step losssensor bias/loss, instability, windup

Failure modes and detection

  • Silent step loss (open loop): the motor skips under high acceleration or a jam, and nothing in the controller knows. Detect by re-homing to a switch each cycle, or by a verification encoder that only alarms. Detection latency is one cycle; the cost is a scrapped part or a crashed axis.
  • Sensor bias (closed loop): the loop drives measured error to zero, so a biased sensor parks the true output off-target. A 1% bias over 50 mm is 0.5 mm: 10× the tolerance you were trying to hold. Detect with a second sensor or periodic calibration against a hard stop.
  • Sensor loss: feedback rails or drops to zero and the loop slams the actuator to a limit. Detect with a rate-of-change plausibility check and a timeout; fail to a safe state (disable drive, engage brake).
  • Integral windup: during saturation the integrator accumulates and the axis overshoots on recovery. Detect by comparing command to the actuator limit; clamp the integrator while saturated.
  • Instability from delay: sample/compute/update delay adds phase, and too much gain gives a limit cycle. Detect by watching error RMS or a limit-cycle counter; back off gain.

When closed loop is not worth it

When the sensor costs more than the error it removes, or the plant is well characterized and the consequence is low: a windshield wiper, a microwave turntable, a cheap printer carriage. Adding a sensor adds a failure mode; if the open-loop budget already passes, you have bought accuracy you did not need and a new way to fail.

What changes the decision: tolerance tightening below the open-loop bound, a load that varies or is unknown at design time, or a requirement to detect a stall.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design position feedback for an actuator.

Answer

Clarify first. What actuator, what accuracy, what safety class? I'll assume a 24 V brushed DC motor on a 5 mm/rev leadscrew, 100 mm stroke, ±0.1 mm accuracy, single-fault-safe stop, ~10⁶ cycles over life. Those four numbers decide almost everything below.

Core answer. Position feedback is three things, not one: a sensor that measures resulting state, a control loop that closes on it, and an independent path that stops the motor when the loop lies. The sensor choice is a trade, so I'd pick by cycle count and whether absolute position at power-up matters.

sensorabsolute?resolution herelifepick when
incremental quadrature encoderno, needs homing4000 counts/rev10⁸+high cycle, homing acceptable
potentiometeryes~1 µm on this screw~10⁶ wipeslow cycle, cost-critical
absolute magnetic (e.g. AS5600)yes12-bit10⁸absolute at power-up, dusty
LVDTyessub-µminfinitehigh accuracy, harsh environment

Resolution is rarely the limit. 1000 PPR × 4 = 4000 counts/rev; at 5 mm/rev that's 1.25 µm/count, so ±0.1 mm is 80 counts. Backlash and screw lead error dominate, not counts.

Redundancy. Pair the encoder with a potentiometer: different physics, so debris or a magnet fault doesn't kill both. Disagreement beyond 2 mm held for 100 ms is a fault, not noise.

Control and limits. Cascade position→velocity PID at 1 kHz. Soft limits sit 2 mm inside the stroke in software. Hard limit switches wire to a safety relay that cuts motor power independently of the MCU: never let the same code path that commands motion also be the only thing that stops it.

Failure modes, with detection.

faultsignaturedetection
stallcurrent > 3 A, encoder staticcommand nonzero, Δenc < 5 counts over 200 ms, current high
broken couplingcurrent ~0.3 A (no load), encoder staticsame static test, current low
wrong directionsign(Δenc) ≠ sign(command)50 ms
oscillationerror sign flips > 4× in a 300 ms windowcounter
sensor disagreement|enc − pot| > 2 mm100 ms
limit violationhard switch asserted inside soft rangeimmediate, cut power

The stall/broken-coupling pair is the one interviewers push on: both look like "no motion," and current separates them. Stall draws torque current against a load; a broken coupling draws almost nothing because the motor spins free.

Test design. Obstruction: drive into a rigid stop at 50% duty, expect stall detection within 200 ms and a current trip. Broken coupling: disconnect the coupling, command 10 mm, expect a no-motion fault with low current, and confirm the two tests produce different signatures, or the detector can't tell them apart.

When not to do this. If the actuator is a stepper with a hard mechanical stop and no accuracy requirement, closed-loop position sensing is cost you don't need: a limit switch and a step counter suffice. Add sensing when the consequence of being wrong is physical.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design saturation, rate limiting, deadband, and anti-windup.

Answer

Assumptions. One servo position axis: 1 kHz position loop, PI controller, drive takes a ±10 V torque command and enforces its own 10 A current limit, 10:1 gearbox, 5 mm/rev ballscrew, 20 µm backlash, 1 µm encoder. Numbers are illustrative for this axis; the derivation is what transfers.

Core answer. Four limits, each from a different physical constraint, plus anti-windup that tracks the command actually applied.

LimitValueDerived from
Output clamp u_max±10 Vdrive command input range
Current limit10 Amotor/drive thermal rating
Setpoint rate25 mm/s3000 rpm ÷ 10:1 × 5 mm/rev = 1500 mm/min
Deadband±1 µm (2 counts)encoder resolution
Back-calc gain Kt50 s⁻¹ (Tt = 20 ms)~5× the loop's dominant time constant

Saturation is the drive's ±10 V, not the torque you'd like: anything above is unreachable and only feeds the integrator. Rate-limit the setpoint to 25 mm/s so the loop never asks for a move the axis can't follow; following error then stays inside the profile instead of tripping the drive's own following-error fault. Deadband of ±1 count kills quantization dither; do not widen it to cover the 20 µm backlash, which hides real positioning error and starts a limit cycle at every reversal.

Anti-windup: back-calculation, not clamping. Clamping freezes the integrator at its pre-saturation value, so overshoot on reversal scales with how long you sat saturated. Back-calculation bleeds the integrator toward the applied command continuously:

Python
# Position PI, 1 kHz (dt = 1e-3 s), back-calculation anti-windup
Kp, Ki, Kt = 12.0, 400.0, 50.0   # V/mm, V/(mm*s), 1/s
u_min, u_max = -10.0, 10.0       # drive command limits, V
integ = 0.0

def step(err, dt=1e-3):
    global integ
    u_unsat = Kp*err + integ
    u = min(max(u_unsat, u_min), u_max)
    integ += (Ki*err + Kt*(u - u_unsat)) * dt
    return u

Trace, err held at 5 mm (axis against a hard stop):

  • step 1: u_unsat = 60 V, u = 10 V, integ += (2000 - 2500)*1e-3 = -0.5
  • step 2: u_unsat = 59.5, u = 10, integ += (2000 - 2475)*1e-3 = -0.475 → -0.975
  • step 3: u_unsat = 59.025, integ += (2000 - 2451.25)*1e-3 = -0.451 → -1.426

The integrator settles where Ki*err = Kt*(u_unsat - u), i.e. u_unsat - u = Ki*err/Kt = 400*5/50 = 40 V, so integ → -10 and u_unsat → 50 V. That residual is the point: back-calculation bounds the integrator to within Ki*err/Kt of the limit rather than letting it run to 2000 V after one second of clamping. Pick Kt ≈ 1/Tt with Tt a few times the loop time constant: too large and the integrator is sluggish, too small and it winds up.

Failure modes and detection.

  • Windup: command stays pinned at 10 V after the error reverses; detected by logging u_unsat vs u. Cost is overshoot and a following-error trip on recovery.
  • Rate limit too tight: following error grows during fast moves; cost is cycle time.
  • Deadband too wide: standing error up to the deadband at rest, seen comparing commanded vs encoder position; cost is scrap.
  • Deadband too narrow: audible dither and motor heating, visible in the current spectrum; cost is wear.
  • Kt too high: integrator can't hold against a steady gravity load, seen as droop; cost is position error under load.

Keep overtravel limit switches and the drive's following-error fault independent of the controller: they must act when the controller is the thing that's wrong. Test a large step, sustained saturation against a stop, reversal, load disturbance, sensor noise, recovery, and mode transfer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design a calibration lifecycle for field sensors.

Answer

Core answer (first 90 seconds)

A calibration lifecycle is the loop that keeps a field sensor's reported value traceable to a national standard and keeps the conversion from raw signal to engineering units honest. I'd assume a 0–100 psi pressure transmitter with a 4–20 mA output, ±0.5% of span accuracy, feeding a control loop, so a bad calibration is a safety and quality issue, not just a number.

Five stages: define the requirement and the traceability chain; calibrate against a reference with a documented method; fit and store coefficients atomically; verify on independent points; monitor drift and re-calibrate on evidence.

Traceability and the reference

The reference must be traceable to a national metrology institute (NIST or equivalent) through a lab whose ISO/IEC 17025:2017 scope covers that quantity, and its certificate must state uncertainty and coverage factor (usually k=2). The working rule is a 4:1 test uncertainty ratio: if the transmitter tolerance is ±0.5% of 100 psi = ±0.5 psi, the reference's expanded uncertainty should be ≤0.125 psi. Below 4:1 you are measuring the reference, not the sensor.

The calibration itself

Five stimulus points at 0, 25, 50, 75 and 100% of span, ascending then descending, after a warm-up (say 30 minutes) at controlled temperature. Record raw mA, not just the converted value. Fit offset and gain; add a second-order term only if residuals show curvature, and a temperature coefficient only if you have data across the operating range: otherwise you are fitting noise.

Uncertainty budget: reference standard, DUT resolution, repeatability, hysteresis, temperature effect, fixture. Combine in quadrature per JCGM 100:2008 (GUM). If the combined expanded uncertainty exceeds roughly one-third of the tolerance, the calibration is not fit for purpose.

Storage and verification

Store coefficients as a versioned blob with a CRC, written atomically (write to temp, fsync, rename) so a power loss cannot leave half a calibration. The device reports its calibration version; the host refuses to convert if it does not match. Verify on points not used in the fit: 12.5% and 62.5%, and require residual ≤ tolerance.

Intervals and trade-offs

Fixed 12-month intervals are simple and auditable but wasteful for stable sensors and dangerous for drifting ones. Drift-based scheduling (ILAC-G24 / OIML D 10) starts at 12 months and adjusts: if observed drift at the interval is under 20% of tolerance, extend; if over 80%, shorten. The trade-off is administrative cost and statistical confidence against the cost of an out-of-tolerance sensor in service. On-site calibration is cheaper and avoids process downtime but carries worse uncertainty than a lab; choose on-site only when the 4:1 TUR still holds.

Failure modes

  • Overdue: asset DB due-date, alert at 30 days; symptom is an audit finding or an out-of-tolerance reading.
  • Corrupt coefficients: CRC mismatch or version mismatch; device flags and falls back to last-known-good or refuses to convert.
  • Implausible: residual above acceptance, or a drift jump over 3× historical, or a reading outside physical range; quarantine the sensor and check the reference first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and troubleshoot an I2C sensor bus.

Answer

First 90 seconds

Assume a single master, 3.3 V sensors on a board-level bus, target 400 kHz (fast mode), a handful of devices, total bus capacitance under 400 pF. The bus is open-drain: every device can only pull a line low, and the high level comes from the pull-up resistor. That one fact drives everything else.

Pull-up sizing is the first real decision. Rise time is set by the RC of the pull-up and bus capacitance: t_r ≈ 0.8473 × R_p × C_b. Fast mode caps t_r at 300 ns. At C_b = 400 pF that gives R_p ≤ 300 ns / (0.8473 × 400 pF) ≈ 885 Ω. The lower bound comes from sink current: at 3.3 V and V_OL = 0.4 V, a 3 mA sink sets R_p ≥ (3.3 − 0.4)/3 mA ≈ 970 Ω. So at full capacitance the window is narrow, around 1 kΩ. If the bus is only 100 pF, R_p can be ~3.5 kΩ and you save power. That is the trade: smaller R_p gives faster edges but more static current whenever a line is low; larger R_p saves current but rounds the edges until setup time is violated.

Modef_SCLt_r maxC_b maxR_p at C_b max
Standard100 kHz1000 ns400 pF~2.9 kΩ
Fast400 kHz300 ns400 pF~885 Ω
Fast-mode+1 MHz120 ns550 pF~260 Ω

Mechanisms that bite

Clock stretching: a target holds SCL low after the master releases it. The master must read SCL back and wait. A driver that assumes SCL follows what it drives sees a stretching sensor as a hang. Detection: scope shows SCL low while the master is idle, and the firmware timeout fires.

Arbitration: two masters transmit at once and each monitors SDA. A master that drives SDA high but reads low has lost and must switch to slave-receive. It fails when a driver never reads SDA back, then both masters think they own the bus and corrupt data.

Failure modes and detection

  • Stuck-low SDA/SCL: a slave reset mid-byte holds the line. Detect by releasing both lines and reading them with only the pull-ups active; if a line stays low, it is stuck. Recover with up to 9 SCL pulses then a STOP.
  • NACK: an address NACK means the device is absent or mis-addressed; a data NACK usually means the device is busy (common with EEPROM writes). Retry with backoff, do not spin.
  • Timeout: bound every transaction. Without it a stuck bus hangs the driver forever.
C
// Bit-bang recovery: up to 9 clocks, then STOP.
static void i2c_bus_recover(void) {
    sda_release();                 // pull-up takes SDA high if free
    for (int i = 0; i < 9 && !sda_read(); i++) {
        scl_low();     delay_us(5);
        scl_release(); delay_us(5); // slave may release SDA here
    }
    sda_low();     delay_us(5);     // START
    scl_release(); delay_us(5);
    sda_release(); delay_us(5);     // STOP
}

Trace: a slave stuck holding SDA low mid-byte releases it on the 9th clock, a byte boundary. The loop condition re-reads SDA each pass, so it exits as soon as the line goes high. START then STOP resets the bus state machine. If SDA is still low after 9 clocks, the line is shorted or a device is dead: isolate that branch.

Recovery versus isolation is the last trade: recovery is cheap and non-destructive, while isolation (a mux or power gate) costs a component and firmware but contains a permanently bad device.

Verify with a scope at worst case (max capacitance, max temperature, all devices powered) and measure rise time at the far end of the bus, not at the master.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design online diagnostics for a sensor channel.

Answer

Ask what consumes the reading and how fast a wrong value hurts before naming any check. For a 0-10 bar piezo element on 4-20 mA, 12-bit ADC, 100 Hz sampling, feeding a closed-loop flow controller, I run three tiers at two rates: electrical checks in the ADC driver at 100 Hz, statistical checks in a 10 Hz task, and model plus redundancy checks at 10 Hz. Each tier owns its threshold and its action.

tiercheckexample thresholdon trip
0loop currentbelow 3.6 mA = open loop, above 21 mA = short; 20.5-21 mA is overrange, not a fault (NAMUR NE 43)channel fail, quality BAD
0raw vs scaledraw ADC outside 0-4095 impossible; abs(raw - gain*scaled - offset) over 2 LSBcalibration fault, not element fault
1slewabs(dp/dt) over 200 bar/s, held 2 consecutive samplesrate fault, hold output
1stuck variancevariance of 64 samples below 1e-6 bar^2frozen element
1freshnesscounter not advancing, or timestamp age over 30 msreplay or freeze, not drift
2model residualabs(r) over 4 sigma for 5 samples; CUSUM with k=0.5 sigma, h=5 sigmaslow drift
2redundancyabs(p1-p2) over 0.085 bar for 1 sdegraded, limp mode

Why these numbers. The 200 bar/s slew bound comes from the valve's own slew rate, not from the sensor: at 100 Hz a legitimate step is at most 2 bar in one sample. Quantization sets the stuck threshold. A 16 mA span over 10 bar gives 1.6 mA/bar; 12 bits over that span gives 16 mA/4096 = 3.9 uA per LSB, or 2.44e-3 bar per LSB. Quantization variance alone is LSB^2/12 = 4.96e-7 bar^2, and real element noise (sigma 0.02 bar) adds 4e-4 bar^2. So a threshold of 1e-6 bar^2 sits about twice quantization yet far below live noise, and a frozen sample-and-hold gives exactly 0. The open/short check is separate from range because a live-but-wrong element sits inside 3.8-20.5 mA and only the statistical tier sees it. The residual in tier 2 is against a one-step prediction from the last value and the commanded actuator state, normalized by the 0.02 bar innovation sigma; CUSUM catches the 0.05 bar/s drift a per-sample gate never trips on. Reset the accumulator on any commanded step, otherwise the step masks as a fault.

Debounce is asymmetric: 3 consecutive violating windows to enter fault, 5 clean windows to clear, so a marginal sensor cannot flap. Redundancy threshold is 3sqrt(2)sigma = 31.4140.02 = 0.085 bar, floored at 0.05 bar for the case where the two elements have unequal noise.

Python
# Python 3.11
WIN, TRIP_VAR, ENTER, EXIT = 64, 1e-6, 3, 5

class StuckDetector:
    def __init__(self):
        self.buf, self.trip, self.clean, self.faulted = [], 0, 0, False
    def push(self, x):
        self.buf.append(x)
        if len(self.buf) < WIN:
            return None
        m = sum(self.buf) / WIN
        var = sum((v - m) ** 2 for v in self.buf) / WIN
        self.buf = []
        if var < TRIP_VAR:
            self.trip += 1
            self.clean = 0
            if self.trip >= ENTER:
                self.faulted = True
        else:
            self.clean += 1
            self.trip = 0
            if self.clean >= EXIT:
                self.faulted = False
        return var, self.faulted

Tumbling window, not sliding: a sliding window recomputed every sample makes the 3-in-a-row rule three correlated decisions, not three independent ones. Trace with the input held at exactly 5.0000 bar: pushes 1 to 63 return None; push 64 returns (0.0, False) because variance is 0 and trip is 1, below ENTER; pushes 65 to 127 return None; push 128 returns (0.0, False) with trip 2; push 192 returns (0.0, True) as trip reaches 3. Fault declared at 1.92 s. Feeding live noise with sigma 0.02 bar gives a window variance near 4e-4, which resets trip to 0, and five such windows clear the fault in 3.2 s.

Tier choice is a cost question. A single-channel, non-safety, slow process needs tier 0 plus stuck and freshness only; model residuals and redundancy add engineering and false alarms without changing an outcome. If a wrong value drives a closed loop or a safety function (IEC 61508 SIL 2, ISO 26262 ASIL B), all three tiers and a second element are mandatory, and the fault goes into the DTC store (AUTOSAR Dem) with a snapshot of the frozen raw values.

Three failure modes of the diagnostics themselves. A genuinely static process (tank at equilibrium overnight) trips stuck variance, so gate the check on the command side: only run it while the valve command has moved in the last 10 s or the flow setpoint is non-zero. A legitimate actuator slam trips the slew check, so mask it for 200 ms after any commanded step. A replayed CAN frame with a valid CRC defeats every value check, which is why freshness is a counter and an uptime timestamp, not a CRC.

On fault, never substitute silently. The control path gets the last good value tagged quality BAD with an age counter, held at most 500 ms, and a model estimate is used only if it sits within 2 sigma of the last good value; otherwise the actuator goes to its safe default. OPC UA quality codes carry the same distinction between UNCERTAIN (suspect, still usable with limits) and BAD (failed).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design sensor-fault handling in a control loop.

Answer

The 90-second version. First I'd ask what the loop controls and what happens when it's wrong: a temperature loop on a mixing tank is a nuisance-trip problem, a loop on a pressure relief path is a safety problem. That answer picks the strategy. My default: detect faults in layers, and the moment feedback is invalid, freeze the integrator and clamp the output to a bounded band, then transition to a state that hazard analysis already chose. For a non-safety loop that's usually hold-and-alert; for a safety loop it's a defined safe state, and the loop's own logic is never the last line of defence.

Detection. I layer the cheap checks first. Range: for a 4–20 mA transmitter, NAMUR NE 43 puts valid measurement at 3.8–20.5 mA and flags ≤3.6 mA or ≥21.0 mA as a fault. That's free, it's already in the signal. Rate: a physical slew limit, so a reactor that moves at most 5 °C/s gets a 10 °C/s trip. Stuck: a moving window whose variance collapses while the commanded output is changing. Disagreement: with three sensors take the median and flag any channel more than a tolerance band from it. Timeout: a heartbeat. No frame within three bus cycles and the channel is stale.

The threshold is where most designs go wrong. A per-sample 3σ limit on Gaussian noise fires 0.27% of the time; at 100 Hz that's 0.27 false alarms per second, which is useless. Require five consecutive samples and it drops to about 1.4×10⁻¹³ per sample. Persistence, not a tighter band, is what buys a usable detector.

Why the integrator matters. If feedback freezes at a low value while the actuator drives up, the error stays large and the integral term keeps accumulating. With Ki = 0.5 per second and the integral wound to 50, unwinding takes 100 seconds after the sensor recovers: 100 seconds of overshoot on a process that may not tolerate it. So on invalid feedback: stop integrating, clamp the integral to the band the output can actually use, and clamp the output.

Choosing the degraded state.

OptionWhen it's rightWhen it's wrong
Hold last outputShort faults, slow process, no hazard from holdingAnything where holding feeds the fault, e.g. a runaway heater
Controlled shutdownHazard grows with time, restart is cheapContinuous process where a trip costs hours and the fault is transient
Redundant sensor (2oo3)Safety loop, third sensor affordable2oo2: you can't tell which channel lied
Limited open-loopModel is trustworthy for a bounded timeModel drift unmonitored, or an unstable plant
Safe stateSafety function, hazard analysis demands itUsing it as the default for nuisance faults: operators bypass it

Failure modes I'd name. A stuck-high sensor drives the controller the wrong way until the product is off-spec: caught by disagreement or a model residual. Nuisance trips are their own failure: operators bypass interlocks that fire too often, so a detector tuned too tight is a safety hazard. Common cause, two channels on one supply or one ADC, takes out both at once; diversity in technology and manufacturer is the mitigation. And the protection must be independent: the safety instrumented function sits outside the controller, per IEC 61511, so a controller fault can't disable its own protection.

Recovery and test. Recovery is explicit: the channel must read valid for a defined dwell before it's trusted again, and the controller ramps back rather than stepping. I'd inject each fault class in test: force the mA signal, freeze the value, kill the bus, and check the transition and the alarm.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design communications-loss handling for sensors and actuators.

Answer

Assumptions I'd state before designing anything. A 100 Hz control loop (10 ms period), sensors on CAN at 500 kbit/s, actuators on I2C at 400 kHz, and one actuator whose stuck-open state is the hazard. Change any of those and the numbers move, but the structure holds.

Core answer: three nested budgets. Transaction, device, system.

Transaction. Every reading carries a sequence number and a monotonic timestamp. Freshness is now - timestamp < age_limit, and the age limit comes from the control period, not the bus: three periods (30 ms here) is typical. One missed frame is invisible; three means the loop is steering on stale input.

The per-transfer timeout is not the nominal transfer time. A standard 8-byte CAN frame at 500 kbit/s is ~0.3 ms worst case with bit stuffing; a 4-byte I2C read at 400 kHz is ~140 µs. Set the timeout 10–50× nominal so it catches a stuck bus, not a slow one. The SMBus spec puts Ttimeout at 25–35 ms for exactly this reason.

Retries are bounded and must fit inside the control period: 2 retries × 3 ms = 6 ms < 10 ms. If they don't fit, don't retry in the control path: hand off to a lower-priority task.

Device. Isolate. On I2C a slave holding SDA low blocks the whole segment; recovery is to clock SCL manually nine times, then issue a STOP. On CAN, a node whose transmit error counter exceeds 255 goes bus-off and is removed by the controller; recovery is 128 occurrences of 11 recessive bits, and you rate-limit re-entry so a broken node doesn't flap the bus.

System. Pick the response by hazard:

responsewins whencost
hold last valueprocess is slow (temperature), hazard is nuisancestale value looks valid; must be bounded by the age limit
degrade (coarser rate/range)you can still control, just less preciselyneeds a defined degraded controller, and it must be tested
redundant inputhazard is high and the second sensor is independentcost, plus common-mode failure if both share a bus or supply
safe statetime-to-harm is shorter than the age limitavailability loss; the safe state must be reachable within the deadline

The deciding criterion is hazard severity × time-to-harm versus the cost of a false trip. If time-to-harm is under the age limit, hold is not an option: you need safe state.

Freshness gate, C99, monotonic clock:

C
#define AGE_LIMIT_MS 30
#define RETRY_MAX    2

bool read_sensor(uint16_t *out) {
    for (int i = 0; i <= RETRY_MAX; i++) {
        if (bus_read(out, /*timeout_ms=*/3)) {
            last_good_ms = now_ms();
            return true;
        }
    }
    return false;              // caller decides, this function does not
}

bool input_fresh(void) {
    return (now_ms() - last_good_ms) < AGE_LIMIT_MS;
}

Trace: at t=0 a read succeeds, last_good_ms=0. At t=10 three attempts fail (3 ms each, 9 ms total), read_sensor returns false, last_good_ms stays 0. At t=20, input_fresh() gives 20 < 30: still fresh, the loop uses the last value. At t=31 it gives 31 ≥ 30: stale, the caller switches to degraded mode. So the constants buy exactly three consecutive failed cycles before loss is declared.

Failure modes and how they show up.

  • Silent sensor: the device still ACKs but returns frozen values. Timeout never fires. Detect it with the sequence number not advancing or a rate-of-change plausibility limit. Cost: the loop acts on a constant.
  • I2C stuck bus: SDA held low, every device on the segment lost. Detected by timeout on all transfers. Cost: whole segment down until the nine-clock recovery.
  • CAN bus-off storm: a wiring fault makes a node retry, go bus-off, recover, repeat. Detected via TEC/REC counters and bus-off count. Cost: error frames spike load for every other node.
  • Blocking: a synchronous retry loop inside the control task. Detected by a loop-overrun counter. Cost: jitter and missed deadlines.

Recovery is controlled, not automatic forever. After five consecutive losses, stop auto-retry, latch a fault, and require an explicit re-init (peripheral reset, re-enumeration) plus a health check before the data is trusted again. Count recurrence: if it happens several times in an hour, escalate to maintenance instead of resetting on a loop.

Test by injection: pull the bus, jumper SDA low, freeze a sensor's value, and confirm the loop still meets its deadline and lands in the right state.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design power-up, reset, watchdog, and brownout behavior.

Answer

Assume a 3.3V MCU fed by an LDO from 5V, a motor driver with an enable pin, and configuration stored in the MCU's internal flash. The design is three layers: a hardware supervisor sets the voltage floor, firmware validates everything before it enables an output, and an independent watchdog bounds recovery.

Power-up. The LDO ramps and the MCU's internal POR releases the core around 1.7V. That is below the 1.8V the flash needs to program and below the 2.7V this part needs for full-speed operation, so I don't rely on it. An external supervisor: a MAX809S, threshold 2.93V, 200ms reset delay: holds the core in reset until VDD is above threshold long enough to cover the ramp and clock startup. A supervisor beats a software reset because software cannot run below the core's minimum voltage; the CPU may execute garbage. The supervisor has a defined threshold and hysteresis and does not care what the core is doing.

Brownout. The BOR threshold must sit above the regulator's dropout floor. If the LDO drops out at Vin = 3.5V, then below that Vout follows Vin down. I set the BOR interrupt at 2.7V, above the 1.8V flash minimum, so firmware gets an interrupt with 0.9V of headroom to abort a flash write and park outputs. At a 1V/ms sag that is 900µs. Faster than that and you lose the write, which is why config is CRC-checked on boot, not trusted.

Watchdog. Use an external watchdog with its own oscillator, e.g. a TPS3813, windowed at 100ms. An internal watchdog shares the clock tree, so a clock failure defeats it. A windowed watchdog also resets on a too-early kick, which catches a runaway loop that kicks in a tight loop. Bounded recovery means: on reset, read the reset cause, and if you have reset three times in ten seconds, enter safe mode (outputs off, actuator not driven) instead of looping forever.

Reset cause. Read RCC->CSR before clearing it:

C
uint32_t f = RCC->CSR;
if (f & RCC_CSR_BORRSTF)       cause = CAUSE_BROWNOUT;
else if (f & RCC_CSR_IWDGRSTF) cause = CAUSE_WATCHDOG;
else if (f & RCC_CSR_PORRSTF)  cause = CAUSE_POWERON;
else if (f & RCC_CSR_SFTRSTF)  cause = CAUSE_SOFTWARE;
__HAL_RCC_CLEAR_RESET_FLAGS();

Outputs. During reset, GPIOs are high-Z. The driver enable pin must have a 10k pull-down so the driver is off when the MCU pin floats: never rely on firmware to disable it.

Boot validation. CRC the config and calibration in flash; on mismatch, load defaults and flag it. A flash page write torn at 2.7V during a brownout leaves a half-written page; the CRC catches it. Use A/B pages so a torn write doesn't destroy the last good copy.

LayerSettingThresholdRationale
SupervisorMAX809S2.93V, 200msAbove MCU 2.7V min, covers ramp
BOR interruptBOR_LEV2.7V0.9V above flash 1.8V min
WatchdogTPS3813100ms windowIndependent oscillator
Driver EN10k pull-down—Off when MCU floats

Failure modes and tests. Brownout during flash write → torn page, detected by CRC, mitigated by A/B pages. Watchdog kicked by a runaway loop → windowed watchdog catches it. Reset loop → backup-register counter forces safe mode. Actuator stored energy → motor back-EMF or a charged cap keeps the driver alive after VDD drops; add a hardware brake or disable. Test slow ramps, dips, chatter, repeated reset, corrupted state, power return, and actuator stored energy, and measure the actual sag rate, because the 900µs budget is the number that decides whether the design works.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Integrate emergency stop and guarding with normal control.

Answer

The 90-second answer. Emergency stop and guard interlocks are a separate safety chain, not inputs to the standard PLC. The e-stop button, guard switches and light curtain wire into a dedicated safety relay or safety PLC (Pilz PNOZ, Allen-Bradley GuardLogix, Siemens 3SK). Its safety contacts sit in the motor contactor coil circuit, or assert STO on the drives per IEC 61800-5-2. The standard controller gets one non-safety status bit for sequencing and HMI. That separation is the point: the protective function must not depend on the same software, scan cycle or network as the process logic.

Assumptions I'd state up front: risk assessment calls for PL d / Cat 3, one operator access point, spindle run-down 1.5 s, EU and US compliance.

Stop category. ISO 13850 requires the e-stop to produce a Category 0 or Category 1 stop, and the risk assessment picks which. Category 0 removes power immediately: right when there's a mechanical brake or low inertia. Category 1 commands the drive to decelerate, then removes power once standstill is confirmed. On an 8-second coasting spindle, Category 0 just means the hazard keeps moving after the button is pressed; Category 1 plus guard locking is what actually protects.

Why dual channel. Cat 3 requires that no single fault loses the safety function. Two channels with cross-monitoring and periodic test pulses on the outputs detect a short between channels or a stuck-high output. Cat 4 goes further: accumulated faults must be detected before the next demand. PL d sits at PFHd 10⁻⁷–10⁻⁶ per hour with DCavg medium (60–90%); PL e needs DCavg high (≥99%).

Why monitored reset. A reset button stuck closed would let the machine restart the moment power returns. A monitored reset requires a rising edge: the relay checks the button opened before accepting the next press. IEC 60204-1 requires restart prevention after power restoration; the machine must not resume on its own.

Guard interlock. ISO 14119 Type 4 coded RFID actuator, guard locking with a rated locking force, unlock only after run-down is confirmed by a delay timer or zero-speed monitor. A tongue switch without locking is defeated by a spare key; a coded actuator isn't.

Where the safety function lives.

ApproachSafety function sits inTypical PL / CatWatch out for
Safety relay (PNOZ, 3SK)Hardwired relay; contacts in the contactor coil circuitPL d / Cat 3One relay per function; limited logic
Safety PLC (GuardLogix, F-CPU)Certified safety task with dual-channel I/OPL d–e / Cat 3–4Safety task must be isolated from the standard task; network reaction time adds to T
Drive STO (IEC 61800-5-2)Inside the drive; removes torquePL d / Cat 3 (drive-dependent)STO removes torque, not motion: a coasting load still moves

Safety logic (IEC 61131-3 Structured Text, safety task, not the standard task).

ESTOP_OK := DUAL_CH(Ch1 := %IX0.0, Ch2 := %IX0.1, Discrepancy := T#500MS);
GUARD_OK := DUAL_CH(Ch1 := %IX0.2, Ch2 := %IX0.3, Discrepancy := T#500MS);

(* Monitored reset: rising edge only, and only while inputs are healthy. *)
RESET_REQ  := %IX0.5 AND NOT RESET_PREV;
RESET_PREV := %IX0.5;

IF ESTOP_OK AND GUARD_OK AND NOT EDM_FAULT AND RESET_REQ THEN
    SAFE_RUN := TRUE;
END_IF;
IF NOT (ESTOP_OK AND GUARD_OK) THEN
    SAFE_RUN := FALSE;
END_IF;

(* EDM: after the chain drops, both contactors must report de-energised
   (NC aux closed) within 300 ms, or the fault latches and blocks reset. *)
EDM_TON(IN := NOT SAFE_RUN AND NOT %IX0.4, PT := T#300MS);
EDM_FAULT := EDM_FAULT OR EDM_TON.Q;

(* Guard lock releases only after zero speed is confirmed. *)
UNLOCK_TON(IN := NOT SAFE_RUN AND ZERO_SPEED, PT := T#1S5);
UNLOCK := UNLOCK_TON.Q;

K1_COIL := SAFE_RUN;   (* two contactors in series, both monitored *)
K2_COIL := SAFE_RUN;

Worked example: light curtain distance (ISO 13855). S = K × T + C.

  1. T = 15 ms curtain response + 20 ms safety relay + 220 ms contactor drop-out = 255 ms = 0.255 s.
  2. First pass with K = 2000 mm/s: S = 2000 × 0.255 = 510 mm. That exceeds 500 mm, so the standard says recalculate with K = 1600 mm/s.
  3. Second pass: S = 1600 × 0.255 = 408 mm. C = 8 × (d − 14) = 0 for a 14 mm resolution curtain.
  4. 408 mm is below the 500 mm floor, so mount the curtain at 500 mm.

(Figures are illustrative; substitute your measured stopping time.)

Failure modes.

FailureDetected byResidual risk
Welded contactorEDM reads the aux contact and refuses to resetOnly at the next demand: proof-test the chain on a schedule
Cross-channel shortTest pulses / discrepancy monitoring—
Stuck reset buttonMonitored reset (edge)—
Guard bypassCoded RFID actuator, tamper-resistant conduit—
Network loss (CIP Safety, PROFIsafe)Black-channel watchdog forces the safe stateWithin the safety reaction time (tens of ms)
Power loss and returnRestart prevention; manual reset required—

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Secure a network-connected actuator path.

Answer

What I need before designing anything

What the actuator drives, what it does when the command path dies, and the loop's latency budget. Assume a spring-return valve, fail-closed on power loss, a 200 ms loop, an operator on the plant network, and a controller inside one IEC 62443 zone that speaks only Modbus/TCP (port 502, no authentication in the protocol). Then answer three questions before the coil moves: who is asking, is this exact request fresh and valid for this exact device, and does the physical state allow it. The first two are enforced at the gateway next to the controller, the third in the controller itself. Hardwired interlocks and the local E-stop sit outside all of it: the network is never the safety function.

What each control buys you

ControlDefeatsConcrete setting
Mutual auth of device and operatorRogue client on the control VLAN, spoofed controllerOPC UA Basic256Sha256 / SignAndEncrypt, TCP 4840, per-device X.509 P-256 client certs, 90-day rotation
Signed command with sequence and nonceReplay, duplication, reorderingPer-session sequence, sliding window 32; HMAC-SHA-256 (DNP3 SAv5, IEEE 1815) where a device cannot do certificates
Issue time and TTLStale command replayed after a partition heals2 s expiry on a monotonic clock, PTP-synced
Local validation of mode, state, range, rateA well-formed command that is physically wrongAUTO mode, 0-100%, cap 10%/s, interlock checked in the controller, not the gateway
Ack bound to the command plus feedbackFire-and-forget, target substitutionAck carries the same sequence; read back actual position within 500 ms
Interlock and local E-stopAll of the above failingHardwired, rated to IEC 61508 / ISO 13849, independent of the network

One command, end to end

  • t=0 ms: operator clicks "V-12 to 60%".
  • t=3 ms: client signs {V-12, 60.0, AUTO, seq 4471, nonce, exp t+2000}, sends over mTLS.
  • t=11 ms: gateway validates the cert chain to the plant CA, maps CN to role operator with actuate on V-12, sees seq 4471 is one past high-water 4470 and inside the window, expiry in the future, mode AUTO, upstream pressure 6.2 bar against an 8 bar trip. Range is fine; 60% in one step exceeds 10%/s, so it ramps.
  • t=14 ms: writes Modbus holding register 40001 = 600 (tenths of a percent) to the controller.
  • t=490 ms: controller reports 59.8%, inside the 0.5% tolerance; the ack carries seq 4471 and is logged.
  • t=800 ms: an identical frame with seq 4471 arrives again, attacker or stuck retry. Rejected as at-or-below high-water; rejected-sequence counter increments.

Arithmetic that bounds the damage

Full stroke takes 15 s, so 6.7%/s. A 2 s TTL caps a stale command at roughly 13% of travel even before the rate limiter, and the 10%/s cap means no single command can slam the valve. Heartbeat every 250 ms; three misses (750 ms) drives fail-safe: correct here because fail-safe is closed. If the safe state were "hold last position", the same deadman would be the wrong action, and you alarm instead of de-energising.

Where I'd choose differently

  • mTLS with per-device certs versus a pre-shared key: an MCU with no real-time clock cannot check expiry, so per-device keys with DNP3 SAv5 HMAC-SHA-256 are the fallback. You keep integrity and lose revocation.
  • A broker (MQTT over TLS, 8883) centralises policy and fan-out but is a single point of compromise and adds roughly 10-50 ms; point-to-point OPC UA SignAndEncrypt avoids that and costs you a cert per pair.
  • Aggressive mode (HMAC every frame, a few hundred microseconds on a Cortex-M4) versus challenge-response on critical operations only: challenge-response saves CPU but adds a round trip and can miss a 200 ms deadline.
  • TLS terminates at the gateway because the controller cannot, leaving the last hop cleartext. Acceptable only inside one zone over a conduit, and it gets written down as accepted risk.
  • Drop the network controls entirely on an air-gapped skid with a rated hardware interlock. Spend the effort on the interlock.

Failure modes and how I'd see them

Replay and duplication: sequence cache, rejected-sequence counter. Target substitution: bind the command to device identity and compare commanded against reported position. Stale or delayed: TTL expiry plus PTP offset alarms. Partition: missed heartbeats. Gateway compromise: Modbus downstream is unauthenticated, so detect via interlock trips and register-write audit and cut the path with a data diode. Log actor, cert CN, command, sequence, outcome and timestamp to append-only storage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design useful and bounded observability for an embedded control channel.

Answer

Assumptions first. The channel is a 1 kHz current-control loop on a Cortex-M7 motor drive: samples arrive over a fieldbus, an ISR consumes them and must finish inside the 1 ms period. The diagnostic question is "why did the drive trip, or why is torque noisy", not "log everything". Budget: the ISR may spend roughly 5 µs on logging, and the diagnostic link is a 115200-baud UART.

Core answer. Bounded observability means three fixed things: a fixed-size record, a fixed-size buffer, and a fixed cost per sample in the control path. Useful means every field answers a question you will actually ask during a fault.

Record layout: 32 bytes, fixed, no pointers:

fieldbyteswhy it is there
raw ADC code2separates sensor/ADC faults from conversion faults
engineering value4the number you compare to spec
unit + channel id2disambiguates the stream
timestamp (µs)4ordering
age of sample2staleness at consumption
quality/fault bits2open, short, saturated, CRC
cal + fw version2a value is meaningless without the calibration that produced it
command, mode, limit4what the loop was asked to do
driver current/state, feedback4actuator side
reset cause1post-mortem
CRC2torn-record detection

Why age, not just timestamp. Timestamp says when the sample was taken; age = t_consume − t_sample says whether the loop acted on stale data. A 1 ms loop that consumes a sample with 3 ms age has a transport or scheduling problem that a timestamp alone hides. Log age per sample and alert when age exceeds one period.

Why the loop cannot just log. The ISR writes one 32-byte record into a single-producer/single-consumer ring buffer and returns; a lower-priority task drains it. At 1 kHz that is 32 kB/s. A 64 kB ring holds 2 s of history: enough to capture the pre-trip window. The UART at 115200 baud moves about 11.5 kB/s, so you cannot stream every sample: decimate to 100 Hz for the always-on stream (3.2 kB/s) and switch to full 1 kHz only on a trigger (fault bit, limit hit, or age overrun). That switch is what makes it bounded.

Trade-offs. Always-on decimated plus triggered full-rate beats always-full-rate (the link cannot carry it) and beats trigger-only (you lose the run-up to the fault). Overwrite-oldest ring beats stop-on-fault: stop-on-fault preserves the first fault but loses the recovery. Delta-plus-varint compression on the engineering value roughly halves the stream for slowly varying signals; skip it for the raw code, where every bit matters.

Failure modes and detection.

  • Ring overwrite before drain: detect with a monotonic sequence number and a drop counter; if drops are nonzero during a fault, your window is too short.
  • Timestamp drift between acquisition and consumption clocks: log both and compare; a growing offset is a clock-domain bug.
  • Logging starves control: measure ISR cycles with the DWT cycle counter; if the logging path exceeds budget you will see loop overruns, not a log message.
  • Torn records: per-record CRC; a bad CRC means the drain raced the write.

When not to do this. If the channel is a slow supervisory link (1 Hz setpoints), a full-rate stream is fine and the ring/decimation machinery is overhead. The design above is for a hard-real-time loop where the logging cost is itself a control-path risk.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

You have a pressure sensor and a proportional valve specified at ±0.5% of span accuracy, 0–10 bar range, and 50 ms step response. How do you verify the design meets those before it goes into service?

Answer

Core answer (first 90 seconds). Verification is three separate tests, because the three requirements fail for different reasons. Accuracy: compare the sensor's reported engineering value against a traceable reference at five points up and down the range, at 25 °C and at both temperature extremes, and express the worst-case deviation as a percentage of span. Range: drive the physical input past both endpoints, confirm the reading saturates cleanly, flags out-of-range, and returns without offset when you come back inside. Response time: step the actuator and measure the physical output with an independent transducer. Never the value the controller already believes.

Calibration is one step inside the accuracy test, not the test itself. A freshly calibrated sensor can still miss the requirement once temperature, hysteresis and the actuator's own lag are added in.

Assumptions. 0–10 bar, so ±0.5% of span = ±50 mbar; 50 ms step response; 12-bit ADC, 3.3 V, ratiometric 0.5–4.5 V sensor; 24 V proportional valve.

Error sources and what each costs.

SourceTypical figureCaught by
Quantization12-bit over 4 V span = 0.98 mV/LSB = 2.4 mbar = 0.024% spanarithmetic, not test
Zero and span error±0.25% span before calibration5-point sweep
Hysteresis0.1–0.2% spanup/down sweep
Thermal drift, sensor + reference0.02% span/°C → 0.6% over 0–70 °Csoak at extremes
Self-heating0.05% span after 30 min30-min soak at mid-range
Noise and grounding1–5 LSB RMSshorted-input test
Valve deadband and stiction1–3% of commandstep and small-step test

The arithmetic decides where to spend effort: quantization at 0.024% is 20× below the ±0.5% budget, so resolution is not the risk. Thermal drift and hysteresis are.

Test sequence.

  1. Shorted input, 30 minutes: record noise, offset and drift. This is the floor everything else sits on.
  2. Five-point sweep at 0/2.5/5/7.5/10 bar, up and down, three repeats, 25 °C. Compute zero error, span error, hysteresis, repeatability.
  3. Repeat at 0 °C and 70 °C after a 30-minute soak. Compare measured drift against the 0.02%/°C assumption.
  4. Overrange: 12 bar for 60 s, return to 5 bar, re-check zero. Must return within 0.1% span.
  5. Step response: command a 10%→90% step, log valve pressure with an independent transducer at 1 kHz, measure 10–90% rise. Budget: sensor 2 ms + ADC and filter 5 ms + control 1 ms + valve 30 ms = 38 ms, leaving 12 ms against the 50 ms limit.
  6. Endurance: 10,000 cycles, then re-run step 2. Drift must stay inside budget.

Failure modes and how they show up. Thermal drift appears as a slope across the temperature sweep; hysteresis as a loop between the up and down sweeps; valve stiction as a step that stalls then jumps; aliasing as a beat frequency when you sweep the input slowly; a ground loop as noise that changes when you touch the cable shield. If the design fails, guard-band the acceptance limit, shorten the calibration interval, or renegotiate the spec: do not average the failure away.

Curated: · Written: · Reviewed:

Difficulty: Hard