knaxuslearn · build · ship

Projects / Temperature logger / Phase 1

Phase 1 of 4 · about 2.5 hours

From a wire to a number

You end with a sensor wired to the board, its reading in degrees on your screen, and a test that shows one wild reading cannot spoil a result.

Step 1.1: The plan, and the sensor (about 15 minutes)

The TMP36 is a temperature sensor in a small black package with three legs. Give it power and its middle leg puts out a voltage that rises steadily with temperature: 0.5 volts at 0 degrees, plus 10 millivolts for every degree. At 25 degrees it gives 0.75 volts. It works from −40 to 125 degrees, which is 0.1 to 1.75 volts.

The BeagleBone's processor, an AM335x, has an ADC (analog-to-digital converter) with seven inputs a user can reach. It measures a voltage between 0 and 1.8 volts and gives a number from 0 to 4095, its 12 bits. So one step is 1.8 / 4095 volts, about 0.44 millivolts, which is 0.044 degrees on a TMP36.

From a wire to a number in a file to degrees, in four hops.

Pitfall: 1.8 volts is a hard limit. More than that on an analog pin can destroy the input, and those pins go straight into the processor. The TMP36 never goes above 1.75 volts within its range, which is why it is a good first sensor. Never wire an analog pin to the board's 3.3 V or 5 V pins.

Step 1.2: Get onto the board (about 25 minutes)

Plug the BeagleBone into your laptop with the USB cable. It powers up from USB, and after a minute or so it also shows up as a network connection: the board gives itself the address 192.168.7.2 on that link. Log in with SSH:

ssh [email protected]

The default password on the BeagleBoard Debian images is temppwd. Change it now with passwd, since anyone on your network who reads this guide knows the default.

You are now typing commands on the board. Check what you are running on:

cat /etc/debian_version
python3 --version

Note the Python version. Anything from 3.9 up is fine for this project.

Step 1.3: Find the ADC (about 20 minutes)

Linux shows many devices as files. The kernel's driver for this kind of converter is part of the IIO (industrial I/O) system, and each converter appears as a folder:

ls /sys/bus/iio/devices/
cat /sys/bus/iio/devices/iio:device0/name

You should see iio:device0, and its name should mention am335x-adc. Inside it, each input has a file:

ls /sys/bus/iio/devices/iio:device0/

Look for in_voltage0_raw up to in_voltage6_raw. Reading one of those files makes the driver do a fresh conversion and gives you the number:

cat /sys/bus/iio/devices/iio:device0/in_voltage0_raw

With nothing connected, the input floats, and the number wanders about at random. That is normal. If the folder is missing, your image has not loaded the ADC driver. On the BeagleBoard images that is controlled by the "cape overlays" in /boot/uEnv.txt, and their documentation explains how to enable BB-ADC.

Step 1.4: Wire the sensor (about 30 minutes)

Unplug the board first. Hold the TMP36 with its flat face towards you and its legs pointing down. From left to right, the legs are power, output and ground.

The BeagleBone's two long headers are called P8 and P9. The pins are numbered in pairs along each header, and pin 1 is at the end marked with a small number on the board. Connect:

TMP36 legGoes toPin
Left (power)3.3 VP9_3
Middle (output)Analog input 0 (AIN0)P9_39
Right (ground)Analog ground (GNDA_ADC)P9_34

The TMP36 needs at least 2.7 volts to run, so it takes its power from 3.3 V. Its output stays below 1.8 V, so it can go straight to the analog input. The analog ground pin is the reference the ADC measures against, so using it gives cleaner readings than the ordinary ground pins.

Check the wiring twice against the board's pin diagram, then plug the board back in, log in, and read the input a few times:

cat /sys/bus/iio/devices/iio:device0/in_voltage0_raw

At room temperature, around 22 degrees, you should see about 1640. Hold the sensor between two fingers for half a minute and read again. The number should climb by 20 or 30. If it reads near 0 or near 4095, a wire is loose or in the wrong place.

Step 1.5: Volts and degrees, tested on your laptop (about 35 minutes)

Back on your laptop. You do not want to edit code over SSH while you are still finding mistakes, so we write a pretend ADC that runs anywhere. Create fake_adc.py:

"""Pretend to be the BeagleBone's ADC on a laptop: a file whose number changes like a TMP36's."""
import math
import os
import random
import sys
import time

path = sys.argv[1] if len(sys.argv) > 1 else "fake_adc"
random.seed(1)
start = time.monotonic()

while True:
    t = time.monotonic() - start
    celsius = 22 + 2 * math.sin(t / 60)            # a room warming and cooling slowly
    raw = (0.5 + celsius / 100) / 1.8 * 4095       # what a TMP36 would give
    raw += random.gauss(0, 6)                      # ADC noise: a few counts
    if random.random() < 0.02:
        raw = random.choice([0, 4095])             # now and then, a reading that makes no sense
    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        f.write(f"{int(raw)}\n")
    os.replace(tmp, path)                          # swap it in whole, so a reader never sees half
    time.sleep(0.01)                               # a new value every 10 ms

It writes the number a TMP36 at around 22 degrees would give, with a few counts of noise, and now and then a value of 0 or 4095, the kind of nonsense a loose wire gives. os.replace swaps the new file in all at once, so a reader never catches it half written.

Now the code that matters. Create sensor.py with the conversions. Here are its first lines:

"""Read a TMP36 temperature sensor through the BeagleBone's ADC."""
import os
import statistics
import sys
import time

# The ADC's channel 0 (pin P9_39), as the kernel shows it. Set ADC_PATH to read somewhere else.
ADC_PATH = os.environ.get("ADC_PATH", "/sys/bus/iio/devices/iio:device0/in_voltage0_raw")

SAMPLES = int(os.environ.get("SAMPLES", "9"))  # raw readings behind each steady one

ADC_MAX = 4095      # 12 bits
ADC_VOLTS = 1.8     # the AM335x ADC measures 0 to 1.8 V, and no more


def read_raw(path=ADC_PATH):
    """One reading from the ADC, 0 to 4095."""
    with open(path) as f:
        return int(f.read())


def raw_to_volts(raw):
    return raw * ADC_VOLTS / ADC_MAX


def volts_to_celsius(volts):
    """A TMP36 gives 0.5 V at 0 degrees and 10 mV more for every degree."""
    return (volts - 0.5) * 100

The path to read comes from the ADC_PATH environment variable, with the real ADC as the default. That one line is what lets the same code run on the board and on your laptop. You will use SAMPLES in the next step.

Check the maths by hand once. A reading of 1640 is 1640 × 1.8 / 4095 = 0.721 volts, and (0.721 − 0.5) × 100 = 22.1 degrees.

Step 1.6: One wild reading (about 25 minutes)

Every ADC is noisy, and loose wires and electrical spikes make it worse. If you store every raw reading, one bad one shows up as a sudden 130 degrees in your data. A simple fix that works well is to take several readings quickly and keep the median, the middle one when they are sorted. One or two wild values end up at the ends of the sorted list and never in the middle. An average would let them drag the result.

Sort the readings and keep the middle one. Wild values end up at the ends.

Here is the whole of sensor.py, with the median added:

"""Read a TMP36 temperature sensor through the BeagleBone's ADC."""
import os
import statistics
import sys
import time

# The ADC's channel 0 (pin P9_39), as the kernel shows it. Set ADC_PATH to read somewhere else.
ADC_PATH = os.environ.get("ADC_PATH", "/sys/bus/iio/devices/iio:device0/in_voltage0_raw")

SAMPLES = int(os.environ.get("SAMPLES", "9"))  # raw readings behind each steady one

ADC_MAX = 4095      # 12 bits
ADC_VOLTS = 1.8     # the AM335x ADC measures 0 to 1.8 V, and no more


def read_raw(path=ADC_PATH):
    """One reading from the ADC, 0 to 4095."""
    with open(path) as f:
        return int(f.read())


def raw_to_volts(raw):
    return raw * ADC_VOLTS / ADC_MAX


def volts_to_celsius(volts):
    """A TMP36 gives 0.5 V at 0 degrees and 10 mV more for every degree."""
    return (volts - 0.5) * 100


def read_steady(path=ADC_PATH, samples=SAMPLES, gap=0.02):
    """Take several readings and keep the middle one, so one wild value cannot win."""
    values = []
    for _ in range(samples):
        values.append(read_raw(path))
        time.sleep(gap)
    return int(statistics.median(values))


def read_celsius(path=ADC_PATH):
    return volts_to_celsius(raw_to_volts(read_steady(path)))


if __name__ == "__main__":
    for _ in range(int(sys.argv[1]) if len(sys.argv) > 1 else 5):
        raw = read_steady()
        print(f"raw={raw:4d}  {raw_to_volts(raw):.3f} V  {volts_to_celsius(raw_to_volts(raw)):.1f} C")
        time.sleep(1)

read_steady takes nine readings 20 milliseconds apart, so a steady reading takes about 0.2 seconds. On the board each read is a fresh conversion. The pretend ADC only changes its number every 10 ms, which is why the gap is a little longer than that.

Write a test. Create test_sensor.py:

import unittest
from unittest import mock

import sensor


class Conversions(unittest.TestCase):
    def test_full_scale_is_1_8_volts(self):
        self.assertAlmostEqual(sensor.raw_to_volts(4095), 1.8)
        self.assertEqual(sensor.raw_to_volts(0), 0)

    def test_tmp36_points(self):
        self.assertAlmostEqual(sensor.volts_to_celsius(0.5), 0)
        self.assertAlmostEqual(sensor.volts_to_celsius(0.75), 25)
        self.assertAlmostEqual(sensor.volts_to_celsius(0.4), -10)

    def test_median_ignores_one_wild_reading(self):
        readings = iter([1650, 1652, 4095, 1648, 1651, 0, 1649, 1650, 1653])
        with mock.patch.object(sensor, "read_raw", lambda path: next(readings)):
            self.assertEqual(sensor.read_steady("unused", gap=0), 1650)


if __name__ == "__main__":
    unittest.main()

mock.patch.object swaps read_raw for a function that hands out a fixed list, so the test does not need any ADC at all. The list has one 4095 and one 0 in it, and the median should ignore both.

python3 -m unittest -v test_sensor
test_full_scale_is_1_8_volts (test_sensor.Conversions.test_full_scale_is_1_8_volts) ... ok
test_median_ignores_one_wild_reading (test_sensor.Conversions.test_median_ignores_one_wild_reading) ... ok
test_tmp36_points (test_sensor.Conversions.test_tmp36_points) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

Now run it for real against the pretend ADC. Start fake_adc.py in one terminal:

python3 fake_adc.py /tmp/fake_adc

And in a second terminal:

ADC_PATH=/tmp/fake_adc python3 sensor.py 8
raw=1637  0.720 V  22.0 C
raw=1642  0.722 V  22.2 C
raw=1639  0.720 V  22.0 C
raw=1642  0.722 V  22.2 C
raw=1640  0.721 V  22.1 C
raw=1640  0.721 V  22.1 C
raw=1640  0.721 V  22.1 C
raw=1646  0.724 V  22.4 C

The pretend ADC throws in a 0 or a 4095 about once every 50 values, and none of them got through.

On the board: copy the files across and run it there. From your laptop:

scp sensor.py test_sensor.py [email protected]:
ssh [email protected] python3 sensor.py 8

No ADC_PATH this time, so it reads the real ADC. Expect numbers near your room temperature, moving by a tenth of a degree or two from one reading to the next.

Phase 1 done

A voltage from a sensor now arrives in your program as degrees, steadied against wild values, and the same code runs against the real ADC or a pretend one.