Projects / Temperature logger / Phase 2
Phase 2 of 4 · about 2.5 hours
Keep every reading
You end with a logger that takes a reading on a fixed schedule, refuses readings that make no sense, marks readings taken while the clock was wrong, keeps them all in SQLite, and an hourly report.
Step 2.1: What to keep (about 20 minutes)
Before writing code, decide what a reading is. For each one we keep:
- when it was taken, in UTC, so it means the same thing whatever time zone you read it in and does not jump twice a year for daylight saving,
- whether the clock was right at the time, which on this board is a real question (Step 2.5),
- the raw ADC number, so if you ever find a mistake in the conversion you can work every temperature out again,
- the temperature in degrees, so ordinary queries do not have to.
We store them in SQLite, a database that lives in one file and is part of Python's standard library. A plain CSV file is tempting, but SQLite gives you two things CSV does not: you can ask questions such as "the hottest hour this week" in one line, and a write either happens completely or not at all, even if the program dies halfway. Phase 4 leans on that.
Step 2.2: The table (about 25 minutes)
Create logger.py. It starts with its settings and the table:
"""Take a temperature reading every INTERVAL seconds and keep it in SQLite."""
import os
import sqlite3
import time
from datetime import datetime, timezone
import sensor
DB_PATH = os.environ.get("DB_PATH", "readings.db")
INTERVAL = float(os.environ.get("INTERVAL", "10"))
# systemd-timesyncd creates this file once the clock has been set from the network.
CLOCK_FLAG = os.environ.get("CLOCK_FLAG", "/run/systemd/timesync/synchronized")
SCHEMA = """
CREATE TABLE IF NOT EXISTS readings (
id INTEGER PRIMARY KEY,
taken_at TEXT NOT NULL, -- UTC, like 2026-11-24T09:30:00Z
clock_ok INTEGER NOT NULL, -- 1 if the clock had been set from the network
raw INTEGER NOT NULL,
celsius REAL NOT NULL
);
"""
id INTEGER PRIMARY KEY gives every row a number that counts up by itself. Times are stored as text in ISO 8601 form. Text sorts in time order, SQLite's date functions understand it, and a person can read it.
Step 2.3: Readings on a schedule (about 35 minutes)
Here is the whole of logger.py:
"""Take a temperature reading every INTERVAL seconds and keep it in SQLite."""
import os
import sqlite3
import time
from datetime import datetime, timezone
import sensor
DB_PATH = os.environ.get("DB_PATH", "readings.db")
INTERVAL = float(os.environ.get("INTERVAL", "10"))
# systemd-timesyncd creates this file once the clock has been set from the network.
CLOCK_FLAG = os.environ.get("CLOCK_FLAG", "/run/systemd/timesync/synchronized")
SCHEMA = """
CREATE TABLE IF NOT EXISTS readings (
id INTEGER PRIMARY KEY,
taken_at TEXT NOT NULL, -- UTC, like 2026-11-24T09:30:00Z
clock_ok INTEGER NOT NULL, -- 1 if the clock had been set from the network
raw INTEGER NOT NULL,
celsius REAL NOT NULL
);
"""
def open_db(path):
db = sqlite3.connect(path)
db.executescript(SCHEMA)
return db
def utc_now():
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def plausible(raw):
"""0 or 4095 means a loose wire or a short, not a temperature."""
return 10 < raw < 4085
def take_reading(db):
raw = sensor.read_steady()
if not plausible(raw):
print(f"sensor fault: raw={raw}, not saved", flush=True)
return
celsius = round(sensor.volts_to_celsius(sensor.raw_to_volts(raw)), 2)
clock_ok = 1 if os.path.exists(CLOCK_FLAG) else 0
taken_at = utc_now()
with db: # commits when the block ends
db.execute(
"INSERT INTO readings (taken_at, clock_ok, raw, celsius) VALUES (?, ?, ?, ?)",
(taken_at, clock_ok, raw, celsius),
)
print(f"{taken_at} {celsius:.2f} C (raw {raw}, clock_ok {clock_ok})", flush=True)
def main():
db = open_db(DB_PATH)
print(f"logging every {INTERVAL:g} s to {DB_PATH}", flush=True)
next_due = time.monotonic()
while True:
take_reading(db)
next_due += INTERVAL
now = time.monotonic()
if now > next_due: # we fell behind, say after a long pause: skip, do not catch up
missed = int((now - next_due) // INTERVAL) + 1
next_due += missed * INTERVAL
print(f"fell behind: skipped {missed} reading(s)", flush=True)
time.sleep(next_due - now)
if __name__ == "__main__":
main()
with db: wraps the insert in a transaction and commits it when the block ends. Until the commit, the row is not in the database. After it, the row is there for good.
The loop is careful about time. The obvious version, "take a reading, then sleep for INTERVAL", drifts: each reading takes 0.2 seconds, so the readings creep later and later. Instead, next_due moves forward by exactly INTERVAL each time, and we sleep only until it. We measure with time.monotonic(), a clock that only ever moves forward at a steady rate. The wall clock can jump when the network sets it, and a jump in the middle of a sleep calculation gives you a sleep of hours, or a negative one.
If the program falls a long way behind, for instance because the board was busy or the process was paused, it skips the readings it missed rather than taking them all at once. Readings of "now" taken in a burst would pretend to be readings from earlier.
Try it against the pretend ADC, with a reading every 2 seconds. Keep fake_adc.py running in its terminal:
ADC_PATH=/tmp/fake_adc INTERVAL=2 python3 logger.py
logging every 2 s to readings.db
2026-11-24T09:25:43Z 22.04 C (raw 1639, clock_ok 0)
2026-11-24T09:25:45Z 22.00 C (raw 1638, clock_ok 0)
2026-11-24T09:25:47Z 22.09 C (raw 1640, clock_ok 0)
2026-11-24T09:25:49Z 22.09 C (raw 1640, clock_ok 0)
Press Ctrl-C to stop it. Python prints a KeyboardInterrupt message as it stops. We will make that tidier in Phase 3.
To see it skip, run it again with INTERVAL=1, and in another terminal pause it for four seconds and let it go again:
pkill -STOP -f logger.py; sleep 4; pkill -CONT -f logger.py
2026-11-24T09:26:02Z 22.04 C (raw 1639, clock_ok 0)
2026-11-24T09:26:07Z 22.31 C (raw 1645, clock_ok 0)
fell behind: skipped 3 reading(s)
2026-11-24T09:26:07Z 22.18 C (raw 1642, clock_ok 0)
The first reading after the pause was overdue and was taken as soon as the program woke up. The next one is back on the one-second grid, which happened to fall within the same second.
Step 2.4: Readings that make no sense (about 20 minutes)
The median deals with one wild value among nine. It cannot help when every value is wrong, which is what a loose wire looks like. A disconnected or shorted input reads 0 or 4095. A TMP36 never gives either within its range, so plausible refuses anything within 10 counts of the ends, and the logger prints a warning instead of storing it.
Try it with a file stuck at 4095:
echo 4095 > /tmp/stuck
ADC_PATH=/tmp/stuck INTERVAL=1 python3 logger.py
logging every 1 s to readings.db
sensor fault: raw=4095, not saved
sensor fault: raw=4095, not saved
sensor fault: raw=4095, not saved
Storing nothing is better than storing 130 degrees. A gap in the data says "we do not know", and a wrong number says something false.
Step 2.5: The clock that starts in the past (about 30 minutes)
A laptop keeps the time with a small battery while it is off. The BeagleBone Black has no battery for its clock. Each time it boots, Linux starts with a time saved on the SD card at the last shutdown, or some other guess, and keeps it until it reaches a time server on the network. With no network, it can run for days with the wrong date.
You cannot fix that in software, but you can record it. On Debian, the time service systemd-timesyncd creates the file /run/systemd/timesync/synchronized once it has set the clock from the network, and /run is emptied at every boot. So the file's existence tells you whether the clock has been set since the board started. The logger stores that as clock_ok.
On your laptop that file probably does not exist, which is why every reading so far says clock_ok 0. Point CLOCK_FLAG at a file that exists to see the other case:
touch /tmp/synced
ADC_PATH=/tmp/fake_adc INTERVAL=2 CLOCK_FLAG=/tmp/synced python3 logger.py
logging every 2 s to readings.db
2026-11-24T09:25:50Z 22.26 C (raw 1644, clock_ok 1)
2026-11-24T09:25:52Z 22.13 C (raw 1641, clock_ok 1)
2026-11-24T09:25:54Z 22.31 C (raw 1645, clock_ok 1)
Look at what is in the database now. If you do not have the sqlite3 command, install it with sudo apt install sqlite3.
sqlite3 -header -column readings.db "SELECT * FROM readings;"
id taken_at clock_ok raw celsius
-- -------------------- -------- ---- -------
1 2026-11-24T09:25:43Z 0 1639 22.04
2 2026-11-24T09:25:45Z 0 1638 22.0
3 2026-11-24T09:25:47Z 0 1640 22.09
4 2026-11-24T09:25:49Z 0 1640 22.09
5 2026-11-24T09:25:50Z 1 1644 22.26
6 2026-11-24T09:25:52Z 1 1641 22.13
7 2026-11-24T09:25:54Z 1 1645 22.31
On the board: run timedatectl. The line "System clock synchronized" says whether the clock has been set. If your board's image uses a different time service, ls /run/systemd/timesync/ shows whether the flag file exists, and you can point CLOCK_FLAG at whatever yours uses.
Step 2.6: An hourly report (about 20 minutes)
Ten-second readings pile up fast: 360 an hour. Most questions want a summary. Create report.py:
"""Summarise the readings hour by hour."""
import os
import sqlite3
DB_PATH = os.environ.get("DB_PATH", "readings.db")
QUERY = """
SELECT substr(taken_at, 1, 13) || ':00' AS hour,
count(*), min(celsius), round(avg(celsius), 2), max(celsius)
FROM readings
WHERE clock_ok = 1
GROUP BY hour
ORDER BY hour
"""
db = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True) # read only: never get in the logger's way
print(f"{'hour (UTC)':<17} {'count':>5} {'min':>6} {'avg':>6} {'max':>6}")
for hour, count, low, avg, high in db.execute(QUERY):
print(f"{hour:<17} {count:>5} {low:>6.2f} {avg:>6.2f} {high:>6.2f}")
untimed = db.execute("SELECT count(*) FROM readings WHERE clock_ok = 0").fetchone()[0]
if untimed:
print(f"({untimed} readings taken before the clock was set are not shown)")
substr(taken_at, 1, 13) keeps 2026-11-24T09, the hour, and GROUP BY collapses each hour into one row. Readings with clock_ok = 0 are left out, since we do not know which hour they belong to, but the report says how many there were. The database is opened read only, so the report can never change it or get in the logger's way.
python3 report.py
hour (UTC) count min avg max
2026-11-24T09:00 3 22.13 22.23 22.31
(4 readings taken before the clock was set are not shown)
Leave the logger running against the pretend ADC for a couple of hours, and the report fills in.
Phase 2 done
You have a logger that keeps time without drifting, refuses nonsense, is honest about what it does not know, and stores everything in a form you can ask questions of.