What you will learn
  • Convert a TMP36 reading into an approximate temperature.
  • Separate an anomaly score from a hazard claim.
  • Fit an Isolation Forest to a recorded baseline.
  • Test missing, unusual and ordinary measurements.

Before you begin

Complete the LED bridge and understand training data and analog readings.

Unusual is a statistical description

Imagine a room that is usually near22°C. A reading of31°C may deserve attention, but it does not explain what happened. Sunlight may hit the sensor, someone may have moved it, the room may have warmed, or the wiring may be wrong. An anomaly detector asks whether a measurement differs from its reference data; it does not diagnose a cause.

This project puts measurements on the Arduino and pattern detection on a computer. We will use Isolation Forest, which learns how easily examples can be separated by randomly chosen splits. Unusual points often require fewer splits to isolate. That idea works beyond temperature, but one simple temperature feature keeps our first experiment inspectable.

For a known requirement such as ‘warn above30°C,’ a threshold is usually clearer. The learned detector adds a different question: ‘is this unlike the normal situations we recorded?’ Keep those meanings separate in your dashboard and never advertise this educational prototype as fire, medical or equipment protection.

Prepare the computer and the LED bridge

The reference board is an Arduino Uno R3 connected by USB. Start with its built-in LED, so this output needs no external circuit. A laptop performs inference; the Arduino accepts a tiny set of commands. A Raspberry Pi can replace the laptop after its Python setup works. No cloud service is required.

Download bridge.py beside your Python script and the LED sketch. Save the sketch in a folder named led_bridge, open it in Arduino IDE, select Uno and your port, then upload. Close Serial Monitor before opening the port from Python. The kit guide supplies Windows and Raspberry Pi setup alternatives.

On macOS or Linux, create an environment with python3 -m venv .venv, activate it with source .venv/bin/activate, and install the serial library using python -m pip install pyserial. Find your port with python -m serial.tools.list_ports; replace the sample port in the code. Never install a package called bridge: that module is the downloaded file.

Commands are newline-terminated text at 115200 baud. LED_ON means illuminate the indicator; LED_OFF and STOP turn it off. The firmware acknowledges valid messages and turns the LED off after 600 milliseconds without a refreshed light command. Bridge.hold refreshes a requested action for a bounded interval and then sends STOP. An acknowledgement proves a message was parsed; looking at the board checks the physical output.

PartPurpose
Uno R3 and data-capable USB cableLow-voltage output and communication
Computer with Python 3Inference and command validation
Built-in LEDSafe visible actuator substitute

Wire and calibrate one temperature sensor

Add a TMP36 in a TO-92 package, a100nF bypass capacitor and breadboard wires. With USB disconnected and the sensor's flat face toward you, leads pointing down, connect its left supply lead to Uno5V, middle output to A1 and right ground lead to GND. Verify the package diagram in the manufacturer datasheet; a different package or sensor is not pin-compatible by assumption. Place the capacitor across supply and ground near the sensor.

The TMP36 output includes a500mV offset and changes by about10mV per°C. With the Uno's default reference, estimate voltage as raw×supply/1023 and temperature as(voltage−0.5)×100. The nominal5.0V in the example is an approximation. Measure the actual reference supply for calibration and compare a stable reading with a trusted room thermometer. Avoid warming components with flames or high-temperature sources.

A1 is the useful input here. A0 remains unused; do not label its floating readings as light measurements. Keep wire lengths short, give the sensor time to settle and record its location. An anomaly model cannot repair a systematically wrong voltage conversion.

Additional partConnection
TMP36 TO-92Supply5V, outputA1, groundGND; verify pin diagram
100nF capacitorAcross sensor supply and ground
Room thermometerIndependent reference check

Record normal data before fitting

Create baseline.csv with one column headed temperature_c, followed by normal readings collected over several sessions. For a quick classroom check, start with at least30 readings and label the result a small demonstration. A useful baseline should cover the ordinary variation you expect, not thirty copies of a single moment. Keep another session aside for evaluation.

Use the bridge's read() method to obtain the raw temperature channel and apply the same conversion both while collecting and while predicting. Record timestamps and sensor placement in your notebook even though this small model uses only temperature. Do not add an unusual reading to training merely to make its warning disappear.

Compare the new reading with its baseline

Install scikit-learn in your environment. Save the program beside bridge.py and baseline.csv, set the real port, then run it. This example evaluates one new measurement and flashes the LED for an unusual result; a later dashboard can run a bounded sampling loop.

Python
import csv
from sklearn.ensemble import IsolationForest
from bridge import Bridge

with open('baseline.csv', newline='') as handle:
    values = [[float(row['temperature_c'])] for row in csv.DictReader(handle)]
if len(values) < 30:
    raise ValueError('Collect at least30 baseline measurements')
model = IsolationForest(contamination=0.05, random_state=0)
model.fit(values)
with Bridge('/dev/ttyACM0') as board:
    _, raw_temperature, _ = board.read()
    temperature = (raw_temperature * 5.0 / 1023 - 0.5) * 100
    unusual = model.predict([[temperature]])[0] == -1
    print(f'{temperature:.1f} C; unusual={unusual}')
    board.hold('LED_ON' if unusual else 'LED_OFF', 1.0)

csv reads a named column, and the nested lists provide one feature per row. contamination sets the expected outlier fraction used to choose the training threshold; it is not a measured probability that a reading is dangerous. predict returns−1 for an outlier and1 for an inlier. The output remains an indicator, with an automatic return to off.

Expected result: A temperature and True/False anomaly flag are printed. Results depend on your baseline and real sensor. A flagged measurement lights the LED briefly.

Evaluate errors in both directions

Apply the fitted model to your held-out ordinary session and count false alarms. Then test copied values in software, such as a plausible increase above your baseline, without physically heating the circuit. Record whether the detector flags them. Synthetic test values check software behavior; they do not establish real-world detection accuracy.

If every reading is unusual, first inspect units and reference voltage, then baseline coverage. If nothing is unusual, check whether the training file already contains the test events. A disconnected analog wire can produce a plausible number, so add an explicit sensor-health procedure instead of assuming the model notices every electrical fault.

Important terms

Anomaly
An observation that differs from a chosen reference pattern.
Baseline data
Examples representing the normal conditions for a task.
Offset
A constant amount added to a sensor's output relationship.
Calibration
Comparing and adjusting measurements against a reference.
False alarm
A warning produced for a condition considered normal.

Mini project: Make a small evaluation log

  1. Collect baseline temperatures with location and time recorded.
  2. Reserve a separate ordinary session before training.
  3. Compare its warnings with software-injected unusual values.
  4. Write down at least two physical causes of an odd reading that are not room heating.

Common mistakes and debugging

  • Mixing Celsius and Fahrenheit in one column: normalize units before training.
  • Calling the contamination value a confidence percentage: it controls a threshold, not a hazard probability.
  • Using every sample for training: keep a separate session for evaluation.

Independent challenge

Compare Isolation Forest with a rule based on a fixed temperature range. Explain which gives more understandable warnings for your actual room and why.

Check your understanding: 10 questions

  1. Does an anomaly identify its cause?

  2. What happens if the assumed supply voltage is wrong?

  3. Which Uno input is used?

  4. What does a prediction of−1 mean here?

  5. Why keep a separate normal session?

  6. In your own words, what does “Anomaly” mean?

  7. In your own words, what does “Baseline data” mean?

  8. In your own words, what does “Offset” mean?

  9. In your own words, what does “Calibration” mean?

  10. In your own words, what does “False alarm” mean?

Quiz answers

Reveal all 10 answers after your attempt
  1. No. It identifies a difference from baseline, which may have several explanations.
  2. The converted temperature is biased, even if the ADC reading is consistent.
  3. A1, connected to the TMP36 output.
  4. The fitted Isolation Forest classifies the value as an outlier.
  5. It reveals false alarms on data the model did not fit.
  6. An observation that differs from a chosen reference pattern.
  7. Examples representing the normal conditions for a task.
  8. A constant amount added to a sensor's output relationship.
  9. Comparing and adjusting measurements against a reference.
  10. A warning produced for a condition considered normal.

Summary

An intelligent monitor starts with trustworthy measurements and a clearly defined baseline. A learned anomaly flag can support investigation, but it cannot replace calibration, explicit limits or an explanation of uncertainty.

Continue learning

Next, use camera measurements as inputs and learn how visual gestures become bounded Arduino commands.

Choose a connected learning path

Sources and further reading

Prepared 2026-09-18. Editorial draft. Primary documentation checked; hardware, camera and audio behavior still require a physical test.

GO DEEPER

Extra reading & source documents

Optional reading alongside the lessons. These sources do not add to your course lesson count.

Explore the AI model guides →