Detect an open or shorted sensor
Report a sensor fault when readings sit at a rail for three samples in a row. An easy embedded C problem (ADC), run and graded in the browser.
easy · ADC · adc · diagnostics
A thermistor in a voltage divider never reads exactly 0 or 1023 in normal use. A broken wire (open circuit) pulls the 10-bit ADC to the top rail; a short pulls it to the bottom.
sensor_check(s, raw) takes each new reading and returns:
SENSOR_OPENonce the last three readings in a row were 1020 or more,SENSOR_SHORTonce the last three in a row were 3 or less,SENSOR_OKotherwise.
One normal reading ends a run, so a single glitch never raises a fault.
Starter code
sensor_state_t sensor_check(sensor_t *s, uint16_t raw) {
if (raw >= 1020) return SENSOR_OPEN;
if (raw <= 3) return SENSOR_SHORT;
return SENSOR_OK;
}Example tests
A broken wire, then repaired
sensor_t s = { 0 };
const uint16_t r[] = { 512, 1023, 1023, 1023, 1023, 600 };
feed(&s, r, 6);Expected output:
000110A short circuit
sensor_t s = { 0 };
const uint16_t r[] = { 0, 0, 2, 500 };
feed(&s, r, 4);Expected output:
0020Learn it first
- ADC · Resolution, sampling, noise, oversampling and DMA.
More ADC problems
- Median of five samples · Reject a single spike by taking the median instead of the average.
- Oversample for extra bits · Gain resolution from a noisy ADC by summing and shifting.
- Compensate for the supply voltage · Convert a reading to millivolts using the internal reference instead of an assumed 3.3 V.
- Scan the multiplexer channels · Convert each enabled ADC channel in turn from the conversion-complete interrupt.
- Fix: a random battery voltage at power-up · An average starts from whatever was in memory.
- Greenhouse: calibrated soil moisture · Turn a soil probe reading into a percentage using the probe's own calibration.