Greenhouse: calibrated soil moisture
Turn a soil probe reading into a percentage using the probe's own calibration. A medium embedded C problem (ADC), run and graded in the browser.
medium · ADC · adc · calibration · product
Product: Smart greenhouse controller (Agriculture)
Requirement. Every probe is different, so each is calibrated when installed: dry is its reading in dry air and wet its reading in water. A higher reading means drier soil.
Return the moisture from 0 (at dry or drier) to 100 (at wet or wetter), linear between and rounded to the nearest percent.
A calibration where dry is not at least 100 counts above wet is broken (the probe was never calibrated, or the two were swapped): return 255 so the controller can show a fault instead of watering by a wrong number.
Starter code
uint8_t soil_percent(uint16_t raw, uint16_t dry, uint16_t wet) {
return (uint8_t)((1023 - raw) * 100 / 767);
}Example tests
The bench probe (dry 1023, wet 256)
printf("%u %u %u\n", soil_percent(1023, 1023, 256), soil_percent(256, 1023, 256), soil_percent(640, 1023, 256));Expected output:
0 100 50A probe on a 12-bit ADC
printf("%u %u\n", soil_percent(2100, 3000, 1200), soil_percent(1290, 3000, 1200));Expected output:
50 95Learn 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.
- Detect an open or shorted sensor · Report a sensor fault when readings sit at a rail for three samples in a row.
- Fix: a random battery voltage at power-up · An average starts from whatever was in memory.