Cosa costruirà
- Una riga CSV per intervallo —
timestamp, voltage, current, power, energy— aggiunta a un file sul Pi. - Facoltativamente le stesse righe in SQLite (
--sqlite energy.db), così può fareSELECTe tracciare grafici in seguito. - Timestamp reali dall'orologio di sistema del Pi (sincronizzato via NTP) — nessun hardware RTC necessario.
- Robusto contro una lettura errata, e con flush così una riga sopravvive a un'interruzione di corrente.
Distinta dei materiali
| Voce | Q.tà | Note |
|---|---|---|
| rbAmp BASIC SCT-UI1 | 1 | tensione + corrente + potenza reale a bordo · prodotto |
| TA SCT-013 | 1 | portata da adattare al suo circuito · prodotto |
| Raspberry Pi | 1 | qualsiasi modello con l'header I²C a 40 pin |
| Cavetti jumper | — | il bus I²C (SDA / SCL / 5V / GND) |
(Nessun modulo SD, nessun RTC — il Pi ha già entrambi.)
Cablaggio e installazione
Il rbAmp va sui pin I²C del Pi (SDA GPIO2 / SCL GPIO3, VCC 5 V — perché 5 V con un bus a 3.3 V?), TA stretto attorno a un conduttore. Abiliti I²C (sudo raspi-config) e installi — CSV e SQLite fanno entrambi parte della libreria standard di Python, quindi nessuna dipendenza extra:
pip install rbamp smbus2
Il CSV
Ogni intervallo aggiunge una riga; l'intestazione viene scritta alla prima creazione del file:
timestamp,voltage_V,current_A,power_W,energy_Wh
2026-07-30T14:05:00+01:00,230.70,3.793,875.00,0.0120
2026-07-30T14:05:30+01:00,230.65,3.788,873.40,1.4700
(Il timestamp riporta l'offset del fuso orario locale del Pi, così il file resta non ambiguo un anno dopo su un altro host. Se il Pi è offline e non sincronizzato via NTP, i timestamp mostrano 1970-… finché non imposta l'orologio o non lo connette.)
Lo apra in un foglio di calcolo, oppure — se ha passato --sqlite — interroghi il database: SELECT strftime('%H', timestamp), AVG(power_W) FROM energy GROUP BY 1;.
Lo script
Lo esegua così com'è per il CSV, oppure aggiunga --sqlite energy.db per scrivere anche un database interrogabile:
"""
T-P4 -- Log energy to CSV (and optionally SQLite) on a Raspberry Pi.
One rbAmp module meters a circuit; every interval this script writes a
timestamped row to a CSV file, mirrors it to stdout so you can watch, and
-- if you pass `--sqlite path.db` -- also inserts the same row into an
SQLite table for easy querying (`SELECT AVG(power_W) FROM energy WHERE ...`).
Compared to the Arduino data-logger equivalent this is much simpler: the
Pi has a real filesystem and an NTP-synchronised system clock, so there
is no microSD-card module and no external RTC. Timestamps are just
`datetime.now().astimezone().isoformat(...)` -- the Pi is already telling
you the correct wall-clock time.
CSV columns:
timestamp,voltage_V,current_A,power_W,energy_Wh
Wiring (Raspberry Pi, hardware I2C):
rbAmp SDA -> GPIO2 (Pi pin 3)
rbAmp SCL -> GPIO3 (Pi pin 5)
rbAmp GND -> any GND pin
rbAmp VCC -> 5V (Pi pin 2 or 4)
^ rbAmp needs 5V for its analog front-end. Only the I2C
logic level is 3.3V (handled internally).
Enable I2C once on the Pi (same as T-P1/P2/P3):
sudo raspi-config # Interface Options -> I2C -> Enable
Install:
pip install rbamp smbus2
# `csv` and `sqlite3` are Python stdlib; no extra pip deps.
Run:
python tp4_pi_csv_sqlite_logger.py # CSV only, every 30 s
python tp4_pi_csv_sqlite_logger.py --sqlite energy.db # CSV + SQLite
python tp4_pi_csv_sqlite_logger.py --interval 10 --ct 3
Accuracy: per clamp rating — the class and the sensor's own tolerance are both in the accuracy table on the BASIC page.
Ctrl-C to stop -- the CSV file + SQLite DB are flushed and closed cleanly.
Data is safe against power cuts: every CSV row is flushed and every SQLite
insert is committed before the loop moves on.
"""
import argparse
import csv
import os
import sqlite3
import sys
import time
from datetime import datetime
from smbus2 import SMBus
from rbamp import (
RbAmp,
RbAmpError,
RbAmpStaleError,
RbAmpSensorClass,
)
# ---- configuration --------------------------------------------------------
RBAMP_ADDR = 0x50
METER_CH = 0
MY_CT = 3 # SCT-013-030
CSV_PATH = "energy.csv"
LOG_S = 30.0 # one CSV row every 30 s
CSV_HEADER = ["timestamp", "voltage_V", "current_A", "power_W", "energy_Wh"]
SQLITE_DDL = """
CREATE TABLE IF NOT EXISTS energy (
timestamp TEXT NOT NULL,
voltage_V REAL,
current_A REAL,
power_W REAL,
energy_Wh REAL
)
"""
SQLITE_INSERT = "INSERT INTO energy (timestamp, voltage_V, current_A, power_W, energy_Wh) VALUES (?, ?, ?, ?, ?)"
def ensure_ct_preset(dev, ct_code):
"""Verify-then-set CT preset (same pattern as T-P1/P2/P3)."""
try:
applied = dev.read_ct_model_ch(0)
except RbAmpError:
applied = -1
if applied == ct_code:
return False
dev.set_sensor_class(RbAmpSensorClass.SCT_013)
dev.set_ct_model_ch(0, ct_code)
return True
def sample_row(dev):
"""Read one V/I/P + latch a period + roll Wh. Returns a row tuple or None
on any RbAmpError (transient hiccup / stale snapshot). The energy tick
silently skips on stale but V/I/P are still reported."""
try:
v = dev.voltage
i = dev.current[METER_CH]
p = dev.power[METER_CH]
except RbAmpError:
return None
try:
dev.read_period_snapshot() # library auto-rolls the Wh accumulator
except RbAmpStaleError:
pass # keep the V/I/P row; skip the energy tick
except RbAmpError:
pass
wh = dev.energy.wh(METER_CH)
# ISO-8601 with local tz offset; Pi is NTP-synced.
ts = datetime.now().astimezone().isoformat(timespec="seconds")
return (ts, v, i, p, wh)
def open_csv(path):
"""Open (or create) the CSV, write the header only if new, return
(file, writer). Line-buffered so each row hits disk immediately."""
is_new = not os.path.exists(path) or os.path.getsize(path) == 0
f = open(path, "a", newline="", encoding="utf-8", buffering=1)
w = csv.writer(f)
if is_new:
w.writerow(CSV_HEADER)
f.flush()
return f, w
def open_sqlite(path):
"""Open SQLite (create tables if missing), return connection. Explicit
commit per insert gives crash-safe single-row durability."""
con = sqlite3.connect(path)
con.execute(SQLITE_DDL)
con.commit()
return con
def run(bus, addr=RBAMP_ADDR, ct_code=MY_CT,
csv_path=CSV_PATH, sqlite_path=None, log_s=LOG_S,
max_iters=None, stdout=sys.stdout):
"""Core loop. `sqlite_path=None` = CSV only."""
with RbAmp(bus, addr=addr) as dev:
ensure_ct_preset(dev, ct_code)
print(f"rbAmp @ 0x{dev.address:02X} fw=0x{dev.firmware_version:02X} "
f"topology={dev.topology_name} ch={dev.channels}", file=stdout)
print(f"logging every {log_s:.1f} s -> {csv_path}"
+ (f" + sqlite:{sqlite_path}" if sqlite_path else ""),
file=stdout)
print("Accuracy: per clamp rating — see the BASIC page. Ctrl-C stops.\n",
file=stdout)
csv_file, csv_writer = open_csv(csv_path)
con = open_sqlite(sqlite_path) if sqlite_path else None
rows = 0
skipped = 0
iters = 0
try:
while True:
t_start = time.monotonic()
row = sample_row(dev)
if row is None:
skipped += 1
print(f"[SKIP #{skipped}] read failed -- holding, no row written",
file=stdout)
else:
ts, v, i, p, wh = row
csv_writer.writerow([
ts,
f"{v:.2f}", f"{i:.3f}", f"{p:.2f}", f"{wh:.4f}",
])
csv_file.flush() # crash-safe row
if con is not None:
con.execute(SQLITE_INSERT, (ts, v, i, p, wh))
con.commit() # crash-safe row
rows += 1
print(f"row#{rows:>4d} {ts} U={v:6.1f}V I={i:6.3f}A "
f"P={p:7.1f}W E={wh:9.4f}Wh", file=stdout)
iters += 1
if max_iters is not None and iters >= max_iters:
return {"rows": rows, "skipped": skipped,
"csv": csv_path, "sqlite": sqlite_path}
sleep_for = log_s - (time.monotonic() - t_start)
if sleep_for > 0:
time.sleep(sleep_for)
finally:
csv_file.close()
if con is not None:
con.close()
def main():
ap = argparse.ArgumentParser(
description="Log rbAmp energy to CSV (and optionally SQLite) on a Raspberry Pi."
)
ap.add_argument("--bus", type=int, default=1)
ap.add_argument("--addr", type=lambda s: int(s, 0), default=RBAMP_ADDR)
ap.add_argument("--ct", type=int, default=MY_CT)
ap.add_argument("--csv", type=str, default=CSV_PATH)
ap.add_argument("--sqlite", type=str, default=None,
help="Optional path to an SQLite DB file (adds `energy` table).")
ap.add_argument("--interval", type=float, default=LOG_S,
help="Seconds between rows (default 30).")
args = ap.parse_args()
with SMBus(args.bus) as bus:
run(bus, addr=args.addr, ct_code=args.ct,
csv_path=args.csv, sqlite_path=args.sqlite, log_s=args.interval)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nstopped.")
(Verificato in esecuzione con il backend mock della libreria rbAmp + un CSV su filesystem reale e un DB SQLite reale su CPython 3.12 — tre scenari: scrittura CSV+SQLite, idempotenza in append al riavvio, e SKIP controllato in caso di errori di lettura iniettati. Ogni riga viene sottoposta a flush (CSV) e commit (SQLite) prima che il ciclo prosegua, così un'interruzione di corrente non perde mai una riga scritta.)
Cosa fa lo script
Tre helper — sample_row(), open_csv() e (facoltativamente) open_sqlite() — alimentano un semplice ciclo run().
sample_row() — una lettura
v = dev.voltage; i = dev.current[0]; p = dev.power[0] # RbAmpError here -> return None (skip the row)
dev.read_period_snapshot() # roll the Wh accumulator (stale -> keep V/I/P, skip tick)
ts = datetime.now().astimezone().isoformat(timespec="seconds")
return (ts, v, i, p, dev.energy.wh(0))
Legge V/I/P live, fa il latch di un periodo per far avanzare il totale in wattora, e lo marca con l'orologio di sistema del Pi — ISO-8601 con l'offset del fuso orario locale, senza RTC e senza impostazione manuale dell'orologio perché il Pi è sincronizzato via NTP. Un errore di lettura transitorio restituisce None (il ciclo salta quella riga); una finestra di energia non aggiornata mantiene la riga V/I/P ma non fa avanzare i Wh in quell'intervallo.
open_csv() / open_sqlite() — i sink
f = open(path, "a", newline="", encoding="utf-8", buffering=1) # line-buffered -> each row hits disk
if is_new: writer.writerow(CSV_HEADER) # header written once
con.execute("CREATE TABLE IF NOT EXISTS energy (...)") # SQLite, only if --sqlite given
Il CSV si apre in modalità append (intestazione solo se il file è nuovo), con buffer di riga così ogni riga è subito su disco. Passando --sqlite apre anche un DB SQLite e crea la tabella energy se manca — entrambi dalla libreria standard di Python, quindi non c'è nulla da installare.
Il ciclo run()
row = sample_row(dev)
if row is None: skipped += 1 # bad read -> log a SKIP, no row
else:
csv_writer.writerow([...]); csv_file.flush() # crash-safe CSV row
if con: con.execute(INSERT, row); con.commit() # crash-safe SQLite row
Ogni --interval secondi prende un campione e — se la lettura è valida — scrive una riga CSV (e una riga SQLite se abilitato), eseguendo flush e commit prima di andare in sospensione, così un'interruzione di corrente non perde mai una riga scritta. Un blocco finally chiude pulitamente file e DB con Ctrl-C. Quel flush/commit per riga è tutta la garanzia di durabilità.
Uso dei dati
Apra il CSV con un qualsiasi foglio di calcolo — tracci la potenza nel corso della giornata, sommi l'energia per ora, individui i cicli del frigorifero. Oppure, con l'opzione SQLite, esegua SQL direttamente sui dati — medie orarie, totali giornalieri, tutto. Poiché la colonna energia è costituita da wattora integrati dall'host, i totali corrispondono a ciò che si aspetterebbe in bolletta. Preferisce un grafico in tempo reale? Lo porti in Home Assistant — ma per un registro completamente offline, questi file sono suoi.
La serie Python, riepilogo
Ora ha l'intero kit Pi autonomo — senza bisogno di rete:
- Lo legga — un modulo nel terminale.
- Lo scali — più circuiti su un bus, in modo coerente.
- Agisca — faccia scattare un relè GPIO per sovracorrente.
- Registri — questa build, su CSV / SQLite.