rbAmp
ES
Tienda

Proyecto · · 12 min de lectura

Registrador de energía con Arduino en tarjeta SD: CSV con marca de tiempo, sin nube

Un módulo rbAmp y un Arduino como registrador autónomo: voltios, amperios, vatios y kWh con marca de tiempo en una tarjeta microSD como CSV, más el puerto serie a su PC.

Lo que va a construir

  • Una fila CSV por intervalo: timestamp, voltage, current, power, energy, añadida a un archivo en una tarjeta microSD.
  • Las mismas filas se envían por el puerto serie, de modo que puede registrar directamente en un PC (o en un trazador serie) sin la tarjeta.
  • Marcas de tiempo reales desde un RTC DS3231 opcional en el bus I²C, o el tiempo de funcionamiento millis() si omite el RTC.
  • Robusto ante una tarjeta ausente o una lectura mala: sigue adelante y señala el problema en lugar de colgarse.

Lista de materiales

Elemento Cant. Notas
rbAmp BASIC SCT-UI1 1 tensión + corriente + potencia real en el chip · producto
CT SCT-013 1 calibre según su circuito · producto
Placa de desarrollo ESP32 (framework Arduino) 1 el objetivo verificado por compilación (portable a otras placas Arduino)
Módulo de tarjeta microSD 1 SPI; una tarjeta con formato FAT
RTC DS3231 (opcional) 1 marcas de tiempo de reloj real; comparte el bus I²C (dirección 0x68). Necesita la biblioteca RTClib (Adafruit). Si lo omite, las filas llevan marca de tiempo de tiempo de funcionamiento.

Conéctelo

Dos buses, sin conflicto:

  • I²C transporta el módulo rbAmp (0x50), y el RTC (0x68) si instala uno, sobre SDA/SCL. Alimente el módulo a 5 V, masa común; el bus es lógica de 3.3 V (¿por qué?).

  • SPI lleva el módulo de microSD en los pines VSPI de hardware del ESP32: SCK → GPIO18, MISO → GPIO19, MOSI → GPIO23, CS → GPIO5. Mantenga los dos buses en sus propios pines: sin conflicto con I²C.

Las pinzas SCT-013 se colocan alrededor del conductor del circuito: no invasivas en el lado de corriente.

El CSV

En cada intervalo, el registrador añade una fila; la cabecera se escribe al crear el archivo por primera vez:

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 el RTC instalado obtiene fechas reales; sin él, la columna de marca de tiempo muestra el tiempo de funcionamiento up+.)

Ábralo en cualquier hoja de cálculo o herramienta de representación: es solo texto.

El boceto

Ajuste MY_CT, inserte una tarjeta microSD y grabe. ESP32 (framework Arduino) a 50 kHz; SD en los pines VSPI, RTC DS3231 en el bus I²C compartido:

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));
}

(Verificado por compilación en ESP32 con Arduino-CLI: RbAmp + RTClib + las bibliotecas incluidas SD/SPI/Wire. Cada fila se abre, escribe, vuelca y cierra de inmediato, así que una fila nunca se pierde por un búfer sin volcar al apagar. El RTC DS3231 y rbAmp comparten el bus I²C; la tarjeta SD va en pines SPI aparte.)

Lo que hace el boceto

Tres pequeños auxiliares se encargan del registro: makeTimestamp(), ensureHeader() y logRow(), y loop() los vincula a las lecturas del medidor.

makeTimestamp() — hora real, o tiempo de funcionamiento

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

Si se detecta un DS3231 al arrancar (rtc.begin()), las filas reciben una marca de tiempo de reloj real; si no, recurren al tiempo de funcionamiento up+ y el boceto lo indica por Serial. En ambos casos el CSV es válido; solo pierde las fechas absolutas sin el RTC.

ensureHeader() y logRow(): la ruta de escritura del 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() escribe la cabecera de columnas una sola vez, solo cuando el archivo se crea por primera vez. logRow() da formato a una línea y hace lo importante: abre el archivo en modo añadir, escribe la fila y luego vuelca y cierra de inmediato. Esa apertura/volcado/cierre por fila es deliberada: la fila está en la tarjeta en el instante en que se escribe, así que quitar la alimentación (o la tarjeta) nunca pierde datos en búfer. La misma línea va primero a Serial.println(), así que el flujo serie es un CSV autodescriptivo que puede redirigir directamente a un archivo en un PC.

loop(): leer, proteger, registrar

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));

Cada LOG_MS (30 s) fija un periodo de medida para que avance el total de vatios-hora, lee la V/I/P en vivo y, si ninguna llegó como NaN, sella y escribe la fila. Una lectura transitoria mala se omite en lugar de escribirse como basura; un periodo obsoleto se anota pero la fila se escribe igual (con la V/I/P en vivo y los Wh actuales), porque descartar una muestra entera por un paso de energía que no avanzó sería peor.

Uso de los datos

Saque la tarjeta, conéctela a un PC y abra el CSV en una hoja de cálculo: represente la potencia a lo largo del día, sume la energía por hora, detecte los ciclos del frigorífico o el ciclo de trabajo del calentador de agua. Como la columna de energía son vatios-hora reales integrados en el host, los totales cuadran con lo que cabría esperar en la factura. ¿Lo quiere graficado en directo en lugar de a posteriori? Introdúzcalo en Home Assistant; pero para un registro totalmente sin conexión, este archivo es suyo.

Adáptelo a su instalación

  • Más columnas: el módulo también da el factor de potencia y la frecuencia; añádalos a CSV_HEADER y a la cadena de formato de logRow.

  • Archivos diarios: empiece un archivo nuevo cada día (/2026-07-30.csv) a partir de la fecha del RTC, para que un registro no crezca sin límite.

  • Ponga bien el reloj: el RTC toma la hora de compilación en el primer encendido; añada una línea rtc.adjust() con una hora conocida, o sincronice por NTP si pone el ESP32 en Wi-Fi.

  • Varios circuitos: registre una fila por módulo y por intervalo combinándolo con la versión multimódulo.

  • Envíelo a algún sitio: en un ESP32 también puede enviar por POST cada fila a un servidor o publicarla por MQTT, manteniendo la tarjeta SD como copia de seguridad sin conexión.

Resumen de la serie Arduino

Ahora dispone del conjunto completo de herramientas autónomo; no se necesita red:

  • Léalo: un módulo en una OLED.
  • Escálelo: varios circuitos en un bus, de forma coherente.
  • Actúe: dispare un relé por sobrecorriente.
  • Regístrelo: esta construcción, a SD/CSV.

Lea a continuación