rbAmp
IT
Negozio

Progetto · · 12 min di lettura

Logger di energia Arduino su scheda SD: CSV con timestamp, senza cloud

Un modulo rbAmp e un Arduino come logger autonomo: volt, ampere, watt e kWh con timestamp su scheda microSD in CSV, più la seriale verso il suo PC.

Cosa costruirà

  • Una riga CSV per intervallo — timestamp, voltage, current, power, energy — aggiunta a un file su una scheda microSD.
  • Le stesse righe inviate via seriale, così può registrare direttamente su un PC (o su un plotter seriale) senza la scheda.
  • Timestamp reali da un RTC DS3231 opzionale sul bus I²C — oppure l'uptime millis() se non usa l'RTC.
  • Robusto contro una scheda mancante o una lettura errata — continua e segnala il problema invece di bloccarsi.

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
Scheda di sviluppo ESP32 (framework Arduino) 1 il target verificato in compilazione (portabile ad altre schede Arduino)
Modulo scheda microSD 1 SPI; una scheda formattata FAT
RTC DS3231 (opzionale) 1 timestamp reali dall'orologio; condivide il bus I²C (indirizzo 0x68). Richiede la libreria RTClib (Adafruit). Se la salta, le righe avranno come timestamp l'uptime.

Lo cablili

Due bus, nessun conflitto:

  • I²C porta il modulo rbAmp (0x50) — e l'RTC (0x68) se ne monta uno — su SDA/SCL. Alimenti il modulo a 5 V, massa comune; il bus è a logica 3.3 V (perché?).

  • SPI porta il modulo microSD sui pin VSPI hardware dell'ESP32: SCK → GPIO18, MISO → GPIO19, MOSI → GPIO23, CS → GPIO5. Tenga i due bus sui loro pin — nessun conflitto con I²C.

I TA SCT-013 si stringono attorno al conduttore del circuito — non invasivi sul lato corrente.

Il CSV

A ogni intervallo il logger aggiunge una riga; l'intestazione viene scritta alla prima creazione del file:

Text
timestamp,voltage_V,current_A,power_W,energy_Wh
2026-07-30 14:05:00,230.4,0.211,48.2,12.345
2026-07-30 14:05:30,230.1,0.208,47.6,12.477

(Con l'RTC montato ottiene date reali; senza, la colonna del timestamp mostra l'uptime up+.)

Lo apra con un qualsiasi foglio di calcolo o strumento di grafici — è solo testo.

Lo sketch

Imposti MY_CT, inserisca una scheda microSD e faccia il flash. ESP32 (framework Arduino) a 50 kHz; SD sui pin VSPI, RTC DS3231 sul bus I²C condiviso:

C++
/**
 * SdCsvLogger.ino — log energy to microSD as CSV (standalone, no network).
 *
 * One rbAmp module meters a circuit; every interval the Arduino writes a
 * timestamped CSV row to a microSD card AND mirrors it over Serial (redirect to
 * a file, or watch in a serial plotter). A data logger you own — no HA, no cloud.
 *
 * Columns: timestamp,voltage_V,current_A,power_W,energy_Wh
 *
 * Board:  ESP32 (Arduino framework); I2C @ 50 kHz. Non-ESP32 host = 100 kHz.
 * Timestamps: a DS3231 RTC on the SAME I2C bus (addr 0x68, coexists with rbAmp
 *             @0x50) gives real wall-clock time. No RTC -> millis() uptime.
 * Wiring:  I2C  SDA->GPIO21 SCL->GPIO22; rbAmp VCC->5 V; DS3231 VCC->3.3 V; GND
 *               common; ~4.7 kOhm pull-ups to 3.3 V.
 *          SD   (VSPI) SCK->GPIO18 MISO->GPIO19 MOSI->GPIO23 CS->GPIO5.
 *
 * Accuracy: per clamp rating — the class and the sensor's own tolerance are both in the accuracy table on the BASIC page.
 */
#include 
#include 
#include 
#include 
#include 

/* ---- configuration — the reader edits these ------------------------------ */
static const uint8_t      RBAMP_ADDR = 0x50;
static const uint8_t      METER_CH   = 0;
static const uint32_t     I2C_HZ     = 50000;    /* ESP32-Arduino: 50 kHz */
static const uint8_t      SD_CS      = 5;        /* microSD chip-select (VSPI default) */
static const char*        CSV_PATH   = "/energy.csv";
static const uint32_t     LOG_MS     = 30000;    /* one CSV row every 30 s */

/* Match to your clamp: Sct013_005 / _010 / _030 / _050 / _020. */
static const RbAmpCTModel MY_CT      = RbAmpCTModel::Sct013_030;

static const char CSV_HEADER[] = "timestamp,voltage_V,current_A,power_W,energy_Wh";

/* ---- state --------------------------------------------------------------- */
static RbAmp       dev(Wire, RBAMP_ADDR, RbAmpTopology::Single);
static RTC_DS3231  rtc;
static bool        rtc_ok = false;
static bool        sd_ok  = false;
static uint32_t    next_log_ms = 0;
static uint32_t    rows = 0, skipped = 0, sd_fail = 0;

/* Apply the CT model only if it differs (setCTModel() persists to flash). */
static void ensureCtModel() {
    uint8_t applied = 0;
    if (dev.readCTModelCh(METER_CH, applied) && applied == static_cast(MY_CT)) {
        return;
    }
    Serial.println(F("configuring CT model (persists to flash)..."));
    if (!dev.setSensorClass(RbAmpSensorClass::Sct013) || !dev.setCTModel(MY_CT)) {
        Serial.print(F("CT config failed: "));
        Serial.println(RbAmp::errorString(dev.lastError()));
    }
}

/* Wall-clock from the RTC, or uptime if no RTC. Primitive args only. */
static void makeTimestamp(char* buf, size_t n) {
    if (rtc_ok) {
        DateTime now = rtc.now();
        snprintf(buf, n, "%04u-%02u-%02u %02u:%02u:%02u",
                 now.year(), now.month(), now.day(),
                 now.hour(), now.minute(), now.second());
    } else {
        snprintf(buf, n, "up+%lus", static_cast(millis() / 1000UL));
    }
}

/* Create the file with a header row the first time it doesn't exist. */
static void ensureHeader() {
    if (!sd_ok || SD.exists(CSV_PATH)) return;
    File f = SD.open(CSV_PATH, FILE_WRITE);
    if (f) {
        f.println(CSV_HEADER);
        f.close();
        Serial.print(F("created "));
        Serial.println(CSV_PATH);
    } else {
        Serial.println(F("could not create CSV header on SD"));
    }
}

/* Append one row: persist to SD (open/append/flush/close so a row is never
 * lost on power-off) and mirror to Serial. Primitive args only. */
static void logRow(const char* ts, float v, float a, float p, double wh) {
    char line[96];
    snprintf(line, sizeof(line), "%s,%.1f,%.3f,%.1f,%.3f",
             ts, v, a, p, wh);

    Serial.println(line);

    if (!sd_ok) return;
    File f = SD.open(CSV_PATH, FILE_APPEND);
    if (!f) {
        sd_fail++;
        if (sd_fail % 10 == 1)
            Serial.println(F("SD append failed - still logging to Serial"));
        return;
    }
    f.println(line);
    f.flush();
    f.close();
    rows++;
}

/* ---- lifecycle ----------------------------------------------------------- */
void setup() {
    Serial.begin(115200);
    while (!Serial && millis() < 2000) {}

    Wire.begin();
    Wire.setClock(I2C_HZ);

    /* rbAmp */
    dev.setLogStream(&Serial);
    uint8_t tries = 0;
    while (!dev.begin()) {
        Serial.print(F("rbAmp begin failed: "));
        Serial.println(RbAmp::errorString(dev.lastError()));
        if (++tries % 5 == 0)
            Serial.println(F("check wiring: SDA/SCL/5V/GND + external pull-ups"));
        delay(1000);
    }
    Serial.println(F("rbAmp online"));
    ensureCtModel();

    /* RTC (optional) */
    rtc_ok = rtc.begin();
    if (rtc_ok) {
        if (rtc.lostPower()) {
            /* First power-up / dead backup cell: seed from build time. Replace
             * with a known-good time or a set-clock sketch for real accuracy. */
            rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
            Serial.println(F("RTC lost power - seeded from build time (set it properly)"));
        }
        Serial.println(F("timestamp source: DS3231 RTC"));
    } else {
        Serial.println(F("no DS3231 RTC - timestamps fall back to millis() uptime"));
    }

    /* SD (optional) */
    sd_ok = SD.begin(SD_CS);
    if (sd_ok) {
        ensureHeader();
    } else {
        Serial.println(F("no SD card - logging to Serial only"));
    }

    Serial.println(CSV_HEADER);   /* so the Serial stream is a self-describing CSV too */
    next_log_ms = millis();
}

void loop() {
    uint32_t now = millis();
    if (static_cast(now - next_log_ms) < 0) {
        delay(5);
        return;
    }
    next_log_ms = now + LOG_MS;

    /* Latch a period so energy().wh() advances for this row. A stale period is
     * noted but not fatal — the row still carries the live V/I/P + the current
     * Wh total (energy simply does not advance that interval). */
    RbAmpPeriodSnapshot snap;
    if (!dev.readPeriodSnapshot(snap)) {
        Serial.print(F("period stale/failed: "));
        Serial.println(RbAmp::errorString(dev.lastError()));
    }

    float v = dev.readVoltage();
    float a = dev.readCurrent(METER_CH);
    float p = dev.readPower(METER_CH);

    /* Skip the row on a transient bad read rather than write garbage. */
    if (isnan(v) || isnan(a) || isnan(p)) {
        skipped++;
        Serial.println(F("skip row - transient bad read"));
        return;
    }

    char ts[24];
    makeTimestamp(ts, sizeof(ts));
    logRow(ts, v, a, p, dev.energy().wh(METER_CH));
}

(Verificato in compilazione su ESP32 con Arduino-CLI — RbAmp + RTClib + i SD/SPI/Wire inclusi. Ogni riga viene aperta, scritta, sottoposta a flush e chiusa subito, così una riga non va mai persa per un buffer non scaricato allo spegnimento. L'RTC DS3231 e rbAmp condividono il bus I²C; la scheda SD è su pin SPI separati.)

Cosa fa lo sketch

Tre piccoli helper si occupano del logging — makeTimestamp(), ensureHeader() e logRow() — e loop() li collega alle letture del misuratore.

makeTimestamp() — ora reale, oppure uptime

C++
if (rtc_ok) snprintf(buf, n, "%04u-%02u-%02u %02u:%02u:%02u", now.year(), ...);
else        snprintf(buf, n, "up+%lus", millis()/1000UL);

Se all'avvio viene trovato un DS3231 (rtc.begin()), le righe ricevono un timestamp reale dell'orologio; se no, ricorrono all'uptime up+ e lo sketch lo segnala sulla seriale. In ogni caso il CSV è valido — senza RTC si perdono solo le date assolute.

ensureHeader() e logRow() — il percorso di scrittura CSV

C++
File f = SD.open(CSV_PATH, FILE_APPEND);
f.println(line);
f.flush();
f.close();          // open -> append -> flush -> close, every single row

ensureHeader() scrive l'intestazione delle colonne una sola volta, solo quando il file viene creato per la prima volta. logRow() formatta una riga e fa la cosa importante: apre il file in modalità append, scrive la riga, poi esegue flush e chiude subito. Quell'apertura/flush/chiusura per riga è deliberata — la riga è sulla scheda nell'istante in cui viene scritta, quindi togliere la corrente (o la scheda) non perde mai dati in buffer. La stessa riga va prima a Serial.println(), così il flusso seriale è un CSV autodescrittivo che può reindirizzare direttamente su un file del PC.

loop() — leggi, proteggi, registra

C++
dev.readPeriodSnapshot(snap);              // latch a window so energy().wh() advances
float v = dev.readVoltage(); float a = dev.readCurrent(0); float p = dev.readPower(0);
if (isnan(v) || isnan(a) || isnan(p)) { skipped++; return; }   // skip a bad read, don't log garbage
makeTimestamp(ts, sizeof(ts));
logRow(ts, v, a, p, dev.energy().wh(0));

Ogni LOG_MS (30 s) fa il latch di un periodo di misura così che il totale in wattora avanza, legge V/I/P live e — se nessuna è tornata NaN — applica il timestamp e scrive la riga. Una lettura errata transitoria viene saltata invece di scritta come spazzatura; un periodo non aggiornato viene annotato ma la riga viene comunque scritta (con V/I/P live e i Wh attuali), perché scartare un intero campione per un passo di energia non aggiornato sarebbe peggio.

Uso dei dati

Inserisca la scheda in un PC e apra il CSV in un foglio di calcolo — tracci la potenza nel corso della giornata, sommi l'energia per ora, individui i cicli del frigorifero o il ciclo di lavoro dello scaldabagno. Poiché la colonna energia è costituita da wattora reali integrati dall'host, i totali corrispondono a ciò che si aspetterebbe in bolletta. Preferisce un grafico in tempo reale invece che a posteriori? Lo porti in Home Assistant — ma per un registro completamente offline, questo file è suo.

Lo personalizzi

  • Più colonne — il modulo fornisce anche fattore di potenza e frequenza; li aggiunga a CSV_HEADER e alla stringa di formato di logRow.

  • File giornalieri — inizi un nuovo file al giorno (/2026-07-30.csv) dalla data dell'RTC, così un log non cresce senza limite.

  • Imposti l'orologio correttamente — l'RTC prende l'ora dalla build alla prima accensione; aggiunga una riga rtc.adjust() con un'ora nota, oppure si sincronizzi via NTP se mette l'ESP32 sul Wi-Fi.

  • Più circuiti — registri una riga per modulo per intervallo combinando con la build multi-modulo.

  • Lo porti in un server — su un ESP32 può anche inviare ogni riga via POST a un server o pubblicarla via MQTT, mantenendo la scheda SD come backup offline.

La serie Arduino, riepilogo

Ora ha l'intero kit autonomo — senza bisogno di rete:

  • Lo legga — un modulo su un OLED.
  • Lo scali — più circuiti su un bus, in modo coerente.
  • Agisca — faccia scattare un relè per sovracorrente.
  • Registri — questa build, su SD/CSV.

Leggi anche