Building a reliable sensor pipeline
Designing sensor code that notices when something is wrong: range and plausibility checks, timeouts, status flags and safe responses to failure.
Lesson 6 of 6 · 30 min · Self-paced · Free
Sensors fail, and they rarely announce it
A sensor that stops working completely is the easy case. Much more common, and much more dangerous, is a sensor that keeps producing numbers that are wrong. A loose connector can make an analogue input float and read random values. A distance sensor can report 0 cm when it sees nothing. A sensor on a communication bus can lock up and keep returning its last value forever. If the rest of the robot believes those numbers, a gripper might squeeze too hard or a wheel might drive into a wall.
A reliable sensor pipeline is code that turns raw readings into values the rest of the system can trust, and says clearly when it cannot. Everything in this module so far, calibration, filtering, sampling and fixed-point scaling, fits into it.
The stages of a pipeline
A typical pipeline has these stages, in this order:
- Acquire the raw reading and record when it was taken.
- Validate the raw data: did the read succeed, is it within the possible range of the device?
- Convert to physical units using the calibration.
- Check plausibility against physics and recent history.
- Filter to reduce noise, using only values that passed the checks.
- Publish the value together with a status and a timestamp, so users know how far to trust it.
Separating these stages makes each one simple and testable, and makes it obvious where a problem was detected.
Range checks
The simplest check: is the value possible at all? Every sensor has a stated measuring range, and an ADC has a known count range. A raw count pinned at exactly 0 or exactly the maximum often means a short circuit, an open circuit or saturation rather than a real measurement. Many designers deliberately arrange the circuit so that a broken wire produces an obviously impossible value, which makes the fault detectable.
Plausibility checks
A reading can be in range and still impossible. Physics limits how fast real things change. If a robot moves at most 2 m/s, a distance sensor read every 0.1 s cannot honestly change by more than 20 cm between readings. A rate-of-change check rejects bigger jumps.
Here is a small example with made-up readings:
# Made-up distance readings (cm) for illustration, one every 0.1 s.
readings = [82.0, 81.5, 80.9, 0.0, 80.1, 79.6, 312.0, 78.8, 78.3, 650.0]
MIN_CM, MAX_CM = 2.0, 400.0 # the sensor's stated range
MAX_STEP_CM = 20.0 # most the distance can change in 0.1 s
def check(reading, last_good):
if not (MIN_CM <= reading <= MAX_CM):
return "OUT_OF_RANGE"
if last_good is not None and abs(reading - last_good) > MAX_STEP_CM:
return "IMPLAUSIBLE_JUMP"
return "OK"
last_good = None
for k, r in enumerate(readings):
status = check(r, last_good)
if status == "OK":
last_good = r
print(f"{k}: {r:6.1f} cm {status}")Output:
0: 82.0 cm OK
1: 81.5 cm OK
2: 80.9 cm OK
3: 0.0 cm OUT_OF_RANGE
4: 80.1 cm OK
5: 79.6 cm OK
6: 312.0 cm IMPLAUSIBLE_JUMP
7: 78.8 cm OK
8: 78.3 cm OK
9: 650.0 cm OUT_OF_RANGEThe 312 cm reading is inside the sensor's range, so a range check alone would have accepted it. Only the plausibility check, knowing the robot cannot move 2.3 m in a tenth of a second, catches it.
Plausibility checks have a trap. Suppose an object suddenly moves out of the way and the true distance really does jump from 80 cm to 300 cm. A check that always compares with the last good value will reject every new reading forever. Practical code counts consecutive rejections and, after a few in a row that agree with each other, either accepts the new value or raises a fault for a human to look at. Always ask: how does my check recover?
Other useful plausibility tests:
- Stuck-value detection: a real, noisy sensor almost never returns exactly the same value hundreds of times in a row. Perfectly constant output can mean a frozen device.
- Cross-checks: compare sensors that should agree, such as a wheel encoder's speed and a motor current, or two independent temperature sensors.
- Consistency with commands: if the motor is commanded forward but the encoder shows no movement, something is jammed, slipping or disconnected.
Timeouts and stale data
Data has a shelf life. A distance reading from two seconds ago says little about a moving robot now. Every published value should carry the time it was measured, and anything that uses it should check its age. Using the wrap-safe elapsed-time pattern from the non-blocking timing lesson:
#include <stdint.h>
#include <stdbool.h>
typedef enum { SENSOR_OK, SENSOR_OUT_OF_RANGE, SENSOR_IMPLAUSIBLE, SENSOR_STALE } SensorStatus;
typedef struct {
float value_cm; /* last value that passed every check */
uint32_t stamp_ms; /* when that value was measured */
SensorStatus status; /* the result of the most recent check */
} DistanceReading;
#define MIN_CM 2.0f
#define MAX_CM 400.0f
#define MAX_STEP_CM 20.0f
#define TIMEOUT_MS 300u
/* Called whenever a new raw reading arrives. */
void distance_update(DistanceReading *d, float raw_cm, uint32_t now_ms, bool have_previous)
{
if (raw_cm < MIN_CM || raw_cm > MAX_CM) {
d->status = SENSOR_OUT_OF_RANGE;
} else if (have_previous && (raw_cm - d->value_cm > MAX_STEP_CM || d->value_cm - raw_cm > MAX_STEP_CM)) {
d->status = SENSOR_IMPLAUSIBLE;
} else {
d->value_cm = raw_cm;
d->stamp_ms = now_ms;
d->status = SENSOR_OK;
}
}
/* Called every loop, even when no reading arrived. Wrap-safe subtraction. */
bool distance_is_fresh(const DistanceReading *d, uint32_t now_ms)
{
return (uint32_t)(now_ms - d->stamp_ms) <= TIMEOUT_MS;
}Notice that the value and its status travel together in one struct. Code that uses the distance cannot easily forget to check whether it is trustworthy. The freshness check runs every loop, so a sensor that silently stops sending is detected within 300 ms even though no "error" ever arrived.
Deciding what to do about a fault
Detecting a problem is only half the job. The system must respond in a way that is safe, which depends on the machine:
- Hold the last good value briefly, for short glitches, but only for a bounded time and with the status marked accordingly.
- Fall back to another sensor, as fusion does when a camera drops out.
- Degrade gracefully: slow down, reduce force, or switch to a more cautious mode.
- Stop safely: for a moving robot, stopping its motors is often the safe state. For some machines, such as a robot holding a load, stopping suddenly is not safe, and the safe response must be designed specifically.
Whatever happens, log it: what was detected, when, and what the system did. Faults that are silently "fixed" in firmware cannot be investigated later.
Recap
A reliable pipeline acquires, validates, converts, checks plausibility, filters and publishes, attaching a status and a measurement timestamp to every value. Range checks catch impossible numbers; plausibility checks catch possible-but-wrong ones, provided they can recover from genuine jumps. Timeouts catch sensors that go quiet. Decide in advance what safe response each fault gets, and record every fault rather than hiding it.
Project
Paper and Python project: design a fault table
Choose a sensor from this module, for example the load cell in a gripper or a distance sensor on a small wheeled robot.
- List at least five ways it could fail or mislead (for example: broken wire, saturation, frozen bus device, electrical noise, sensor knocked out of alignment).
- For each failure, write how your pipeline would detect it (which check, with what threshold and why) and what the safe response would be.
- Extend the Python example so that after three consecutive rejected readings that agree with each other to within 5 cm, the new value is accepted and a message is printed. Test it with a made-up list containing a genuine jump.
This is a paper-and-computer activity. No hardware is required.
Deliverables
- A fault list with detection method, threshold and safe response for each item
- Extended Python code with its test data and output
- Two sentences on one fault your checks could still miss
Knowledge check
Check your understanding
Go further
- Fail-safe — Wikipedia ↗
The engineering idea of designing failures so they lead to a safe state.
- Watchdog timer — Wikipedia ↗
A hardware timer that resets a processor if its software stops responding, a common companion to the checks in this lesson.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.