Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: Sensor Data Logger with Filtering and Alarms

Build a temperature data logger in C: convert ADC counts with integer math, smooth noise with a moving average, add a hysteresis alarm, store samples in a ring buffer and send CRC-protected packets.

This project combines many ideas from the course into one realistic firmware pipeline: a temperature sensor feeds an ADC; the firmware converts the counts to a physical value, filters out noise, decides whether to raise an alarm, stores the history in a fixed-size log and finally sends the data over a serial link in packets with a checksum. Every stage is a small function with no hardware access, so the whole pipeline runs on a PC. Replacing the simulated ADC with a real driver is the only change needed on a board.

flowchart LR
    A["ADC (12-bit raw)"] --> B["Convert: counts to millivolts to tenths of a degree"]
    B --> C["Filter: moving average"]
    C --> D["Alarm with hysteresis"]
    C --> E["Ring-buffer log"]
    E --> F["Packet + CRC-8"]
    F --> G["UART / radio"]

The data path of the logger. Each box is a separate, testable function.

Stage 1: convert with integers

Small microcontrollers often have no floating-point unit, and software floats are slow and large. Use fixed-point integers: store temperature in tenths of a degree Celsius (so 24.5 ยฐC is the integer 245). Our sensor is TMP36-like: 500 mV at 0 ยฐC and 10 mV for each degree, so one millivolt equals 0.1 ยฐC, which is why tenths of a degree are convenient.

With a 12-bit ADC and a 3.3 V reference: mv = raw * 3300 / 4095, then tenths = mv - 500. Multiply before dividing and widen to 32 bits so intermediate values do not overflow (the bug from testing embedded code).

Stage 2: a moving average filter

Real ADC readings jitter by a few counts. A moving average over the last N samples smooths this at the cost of a little delay. Choosing N as a power of two replaces the division with a shift. The cheapest implementation keeps a running sum: add the new sample, subtract the one that falls out of the window.

Stage 3: an alarm with hysteresis

If an alarm turns on above 30.0 ยฐC and off below 30.0 ยฐC, a signal hovering around 30 chatters on and off with every noise spike. Hysteresis uses two thresholds: switch on above 30.0 ยฐC, but switch off only below 28.0 ยฐC. The gap between them absorbs noise. This is the same idea as debouncing (see debouncing and software timers), applied to an analog value.

The program feeds a slow temperature triangle (rising to 32.7 ยฐC and back) with noise through the pipeline. It compares a naive alarm (raw value, one threshold) with the real one (filtered value, two thresholds) by counting how many times each toggles.

C ADC to filtered temperature with a hysteresis alarm

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The naive alarm chatters when the true temperature passes 30.0 ยฐC, because noise of ยฑ8 counts is about ยฑ0.65 ยฐC; the filtered one toggles only twice, on and then off. Notice also that the filtered value lags the true signal by a few samples. That delay is the price of smoothing, so pick the window by asking how fast the real signal can change.

Stage 4: a fixed-size log in a ring buffer

A logger cannot grow forever: RAM or flash is finite. A ring buffer keeps the most recent N records and overwrites the oldest when full, exactly what you want for "the last hour of history before the fault". The same structure appeared in the shared data lesson; here it overwrites instead of dropping new data.

Stage 5: packets with a checksum

To send records over a UART, wrap each in a frame, as in the UART lesson: a start byte, a length, the payload (serialized byte by byte in a fixed order, never by copying a struct, because padding and endianness differ between machines) and a CRC-8 so the receiver can detect corruption.

C Ring-buffer log and CRC-protected packets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The negative temperature survives the round trip because the signed 16-bit value is split into bytes via its unsigned bit pattern and rebuilt with a cast back to int16_t. Test negative values in every serialization routine: it is the commonest bug here.

Putting it on a real board

  1. ADC. Start the conversion from a timer (a fixed sample rate, say 10 Hz) and read the result from the end-of-conversion interrupt or DMA. Do the conversion math in the main loop, not in the ISR.
  2. Scheduler. Use the cooperative scheduler or RTOS tasks: one task samples and filters, one handles alarms and an LED, one transmits the log when the link is free.
  3. Storage. For logs that must survive a power loss, write records to flash or an EEPROM in pages and keep a sequence number plus CRC in each record, so a half-written record can be detected and skipped after a reboot. Count write cycles: flash wears out.
  4. Power. Sleep between samples (low-power design). Powering the sensor only during the conversion saves more current than any software trick.
  5. Calibration. Real sensors have offset and gain errors. Add a two-point calibration (two known temperatures) and store the coefficients in non-volatile memory.

Extensions to try

  • Replace the moving average with an exponential filter y += (x - y) >> 3 and compare delay and noise.
  • Add a median-of-three filter in front to remove single-sample spikes.
  • Log only when the value changes by more than 0.2 ยฐC (change-based logging), or use a timestamp delta to save space.
  • Add a sequence number so the receiver detects lost packets.
  • Compute min, max and average over the log.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store temperature as tenths of a degree in an integer?

    Fixed-point integer math is cheap and deterministic on small microcontrollers.
  2. 2. What does hysteresis do for an alarm?

    The gap between the thresholds absorbs noise, so the alarm toggles once per real crossing.
  3. 3. Why serialize a record byte by byte instead of sending the struct's memory directly?

    Compilers insert padding and chips differ in endianness, so explicit packing defines one portable format.
  4. 4. What happens to a ring buffer log when it is full and a new record arrives?

    The logger variant overwrites the oldest data so the most recent history is always available.

Summary

  • Build the logger as small, testable stages: convert, filter, alarm, log, packetize.
  • Fixed-point integer math, widened before multiplication, replaces floats on small chips.
  • A moving average smooths noise with some delay; hysteresis prevents alarm chatter.
  • A ring buffer keeps the latest history; packets with length and CRC protect it on the wire, and signed fields need explicit, tested serialization.

Next: Embedded C Practice Problems