EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 30
Connecting Sensors
From the real world to a number.
Sensors come as analog voltage outputs (read with an ADC), digital pulses, or chips that speak I2C or SPI. Check which type you have before wiring.
Weak analog signals may need an amplifier, and noisy ones need a low-pass filter. Calibrate by comparing readings with a trusted reference and applying an offset and scale factor.
Smooth jittery readings with an average or a running filter.
EXAMPLE
/* running average of 4 samples */
static int buf[4]; static int i = 0;
int filter(int x) {
buf[i] = x; i = (i + 1) & 3;
return (buf[0] + buf[1] + buf[2] + buf[3]) / 4;
}