All courses

Arduino C++ · Lesson 39 of 40

Design a sensor alarm with a clear safe state

Integrated Builds and Next Steps

Write requirements that can be checked

Prototype a sensor alarm using a potentiometer as a repeatable input, then substitute a real sensor only after its own minimal example works. Use the A0 potentiometer wiring from the dimmer and the onboard LED as the alarm; no high-current output is needed.

Requirements: sample every 100 ms, use separate on/off thresholds, report every second, and reserve a FAULT state for missing or invalid data. A generic analog pin cannot detect every disconnected sensor: an open pin can float anywhere in its valid range. A production sensor needs device-specific plausibility checks, timeout handling, or a separate connection-detection circuit.

Build a transition table with NORMAL, ALARM, and FAULT. Decide which condition clears each state. Do not call a potentiometer simulation a tested temperature alarm.

Integrate incrementally

  1. Log raw A0 readings at fixed intervals. Verify endpoints and midpoint.
  2. Put threshold logic in a pure function as shown in Reliable Embedded C++.
  3. Add hysteresis. Confirm that slow motion around a threshold does not cause rapid toggling.
  4. Derive the LED output from the current state in one place.
  5. Add a serial diagnostic line containing time, raw value, state, and validity.
  6. Introduce a simulated invalid-data flag and confirm transition to FAULT.
  7. Replace the simulated input with one sensor driver; preserve the same application interface.

Keep a lastGoodSample timestamp only when a real reading is valid. Compare elapsed time to a documented freshness limit. A failed transaction must not refresh that timestamp. Choose a safe output suitable for your real application, not a universal assumption that on or off is always safe.

Deliverable: Include a parts list, pin table, state diagram, source code, test table, and known limitations. Record threshold units and sampling intervals. Demonstrate normal startup, alarm entry, alarm release, and recovery from a simulated fault.

Official references for further study

A useful reminder

Clean Code: Use descriptive constants instead of magic numbers

Instead of calling digitalWrite(13, HIGH) directly in your code, define descriptive constants like const int LED_PIN = 13; at the top of your file. This makes your code self-documenting and extremely easy to update if you change your wiring.