Was Sie bauen werden
- Eine CSV-Zeile pro Intervall —
timestamp, voltage, current, power, energy— auf eine Datei auf dem Pi angehängt. - Optional dieselben Zeilen in SQLite (
--sqlite energy.db), damit Sie späterSELECTausführen und grafisch darstellen können. - Echte Zeitstempel von der Systemuhr des Pi (per NTP synchronisiert) — keine RTC-Hardware nötig.
- Robust gegenüber einer fehlerhaften Messung und geleert, damit eine Zeile einen Stromausfall übersteht.
Stückliste
| Position | Menge | Hinweise |
|---|---|---|
| rbAmp BASIC SCT-UI1 | 1 | Spannung + Strom + Wirkleistung auf dem Chip · Produkt |
| SCT-013-CT | 1 | Nennwert passend zu Ihrem Stromkreis · Produkt |
| Raspberry Pi | 1 | jedes Modell mit der 40-poligen I²C-Leiste |
| Steckbrücken | — | der I²C-Bus (SDA / SCL / 5V / GND) |
(Kein SD-Kartenmodul, keine RTC — der Pi hat beides bereits.)
Verdrahten und installieren
Das rbAmp kommt an die I²C-Pins des Pi (SDA GPIO2 / SCL GPIO3, VCC 5 V — warum 5 V, aber ein 3.3-V-Bus?), CT um einen Leiter geklemmt. I²C aktivieren (sudo raspi-config) und installieren — CSV und SQLite sind beide in der Standardbibliothek von Python enthalten, daher keine zusätzlichen Abhängigkeiten:
pip install rbamp smbus2
Die CSV
Jedes Intervall hängt eine Zeile an; die Kopfzeile wird beim ersten Erstellen der Datei geschrieben:
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
(Der Zeitstempel enthält den lokalen Zeitzonen-Offset des Pi, sodass die Datei auch ein Jahr später auf einem anderen Host eindeutig bleibt. Wenn Ihr Pi offline und nicht per NTP synchronisiert ist, lauten die Zeitstempel 1970-…, bis Sie die Uhr stellen oder ihn verbinden.)
Öffnen Sie sie in einer Tabellenkalkulation oder — falls Sie --sqlite übergeben haben — fragen Sie die Datenbank ab: SELECT strftime('%H', timestamp), AVG(power_W) FROM energy GROUP BY 1;.
Das Skript
Führen Sie es unverändert für CSV aus, oder ergänzen Sie --sqlite energy.db, um zusätzlich eine abfragbare Datenbank zu schreiben:
"""
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.")
(Lauffähig geprüft gegen das Mock-Backend der rbAmp-Bibliothek sowie ein echtes CSV-Dateisystem und eine echte SQLite-Datenbank auf CPython 3.12 — drei Szenarien: CSV+SQLite-Schreiben, Anhänge-Idempotenz bei erneutem Lauf und ordnungsgemäßes SKIP bei eingespeisten Lesefehlern. Jede Zeile wird (CSV) geleert und (SQLite) committet, bevor die Schleife weiterläuft, sodass ein Stromausfall nie eine geschriebene Zeile verliert.)
Was das Skript macht
Drei Hilfsfunktionen — sample_row(), open_csv() und (optional) open_sqlite() — speisen eine einfache run()-Schleife.
sample_row() — eine Messung
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))
Liest die Live-V/I/P-Werte, latcht eine Periode, um die Wattstunden-Summe fortzuschreiben, und versieht sie mit der Systemzeit des Pi — ISO-8601 mit dem lokalen Zeitzonen-Offset, ohne RTC und ohne manuelle Uhreinstellung, da der Pi per NTP synchronisiert ist. Ein vorübergehender Lesefehler liefert None (die Schleife überspringt diese Zeile); ein veraltetes Energiefenster behält die V/I/P-Zeile, lässt aber Wh in diesem Intervall nicht fortschreiten.
open_csv() / open_sqlite() — die Senken
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
Die CSV wird im Anhängemodus geöffnet (Kopfzeile nur, wenn die Datei neu ist), zeilengepuffert, damit jede Zeile sofort auf der Platte liegt. Mit --sqlite wird außerdem eine SQLite-Datenbank geöffnet und die Tabelle energy erstellt, falls sie fehlt — beides aus der Standardbibliothek von Python, daher ist nichts Zusätzliches zu installieren.
Die run()-Schleife
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
Alle --interval Sekunden nimmt es eine Probe und — wenn die Messung gut war — schreibt eine CSV-Zeile (und eine SQLite-Zeile, falls aktiviert), wobei vor dem Schlafen geleert und committet wird, sodass ein Stromausfall nie eine geschriebene Zeile verliert. Ein finally-Block schließt Datei und Datenbank sauber bei Strg-C. Dieses Leeren/Committen pro Zeile ist die ganze Dauerhaftigkeitsgarantie.
Die Daten verwenden
Öffnen Sie die CSV-Datei in einer beliebigen Tabellenkalkulation — stellen Sie die Leistung über den Tag dar, summieren Sie die Energie pro Stunde, erkennen Sie das Takten des Kühlschranks. Oder führen Sie mit der SQLite-Option SQL direkt darauf aus — stündliche Mittelwerte, Tagessummen, alles. Da die Energiespalte echte, vom Host integrierte Wattstunden sind, stimmen die Summen mit dem überein, was Sie auf der Rechnung erwarten. Möchten Sie sie stattdessen live grafisch sehen? Binden Sie es in Home Assistant ein — für eine vollständig offline geführte Aufzeichnung gehören diese Dateien Ihnen.
Die Python-Reihe, Zusammenfassung
Sie haben jetzt das vollständige eigenständige Pi-Werkzeugset — ganz ohne Netzwerk:
- Lesen Sie es — ein Modul im Terminal.
- Skalieren Sie es — mehrere Stromkreise an einem Bus, kohärent.
- Handeln — ein GPIO-Relais bei Überstrom auslösen.
- Protokollieren — dieser Aufbau, in CSV / SQLite.