⚠️ Legga prima questo — che cosa è e che cosa non è. Questo è uno strato di comodità, non un dispositivo di protezione. Il suo interruttore automatico resta il dispositivo di sicurezza — non dimensioni mai un circuito o un carico supponendo che questa automazione interverrà. E il relè che commuta deve essere dimensionato per il carico: un relè piccolo o un interruttore intelligente non può interrompere direttamente 30–50 A. Per un circuito ad alta corrente, usi il relè a bassa corrente per pilotare un contattore dimensionato correttamente. Per lavori all'interno di un quadro elettrico, si rivolga a un elettricista qualificato.
Cosa costruirà
- Un modulo rbAmp che misura la corrente di un circuito.
-
Un relè che scatta quando la corrente resta sopra
LIMIT_ONampere, e rilascia sottoLIMIT_OFF(isteresi, così non oscilla sul setpoint). -
Debounce dello spunto — un breve ritardo di sovraccarico sostenuto così lo spunto di avviamento di un motore o di un bollitore non causa scatti fastidiosi.
- Allarme cicalino / LED opzionale. Tutto locale, nel ciclo Arduino.
Distinta dei materiali
| Voce | Q.tà | Note |
|---|---|---|
| rbAmp BASIC SCT-I1 | 1 | solo corrente I1 è la scelta leggera — un UI1 funziona anche (il suo canale di tensione resta inutilizzato) · prodotto |
| TA SCT-013 | 1 | portata da adattare al circuito · prodotto |
| Scheda di sviluppo ESP32 (framework Arduino) | 1 | il target verificato in compilazione (portabile ad altre schede Arduino) |
| Modulo relè | 1 | isolato, dimensionato per il carico — oppure che pilota un contattore per correnti elevate |
| Cicalino / LED (opzionale) | 1 | allarme locale |
Lo cablili
Il modulo rbAmp si trova sul bus I²C (SDA→GPIO21, SCL→GPIO22, VCC rbAmp 5 V, massa comune — perché 5 V con un bus a 3.3 V?). L'ingresso di controllo della scheda relè va su GPIO26; imposti RELAY_ACTIVE_HIGH nello sketch per adattarlo alla sua scheda (molte schede optoisolate sono attive LOW). Colleghi il carico attraverso il contatto NO del relè, così un relè diseccitato significa carico SPENTO. Un LED/cicalino su GPIO25 opzionale si accende quando scatta. I TA si stringono attorno al conduttore del circuito — non invasivi sul lato corrente.
La logica: soglia, isteresi, debounce
Tre concetti evitano che si comporti male:
-
Isteresi — scatta a
LIMIT_ON(ad es. 18 A) ma rilascia solo sottoLIMIT_OFF(ad es. 15 A). Un unico setpoint farebbe oscillare il carico ogni volta che si trova vicino ad esso; il divario gli dà lo spazio per stabilizzarsi. -
Debounce dello spunto — richiede che la corrente resti sopra il limite per qualche secondo prima di far scattare. Motori, pompe e bollitori assorbono un grande spunto di avviamento che supera il limite per una frazione di secondo — non si vuole far scattare per quello.
-
Il componente rbAmp legge il registro RMS della corrente del modulo a ogni ciclo (il modulo calcola internamente l'RMS a circa 5 Hz, quindi ogni lettura è il valore finestrato più recente) — l'Arduino lo confronta con i limiti e pilota il relè.
Lo sketch
Imposti LIMIT_ON / LIMIT_OFF sui suoi ampere e MY_CT sul suo TA, faccia corrispondere RELAY_ACTIVE_HIGH alla sua scheda relè, e faccia il flash. ESP32 (framework Arduino) a 50 kHz; relè su GPIO26, allarme su GPIO25:
/**
* LoadLimitRelay.ino — local current-limit -> relay / alert (standalone, no network).
*
* One rbAmp current module meters a circuit; when the current stays over a limit
* for a sustained interval, the Arduino trips a relay to shed the load and lights
* an alert. Everything runs in the loop, so the reaction is sub-second once the
* overload is confirmed — no network, no HA round-trip.
*
* =========================== SAFETY — READ FIRST ===========================
* * The relay/switch MUST be rated for the load. A small hobby relay or
* smart-plug CANNOT break 30-50 A directly. Switch a high-current circuit
* with a properly rated CONTACTOR that this low-current relay drives.
* * This is a COMFORT / CONVENIENCE layer, NOT a protection device. The circuit
* BREAKER remains the safety device. Never size a circuit or a load assuming
* this automation will act. For a hard cut-off use a hardware overcurrent
* device (breaker / fuse / thermal cut-out).
* * The relay reaction is deliberately delayed by OVERLOAD_MS to ride through
* inrush — it is NOT instantaneous overcurrent protection.
* ===========================================================================
*
* Module: a current-only rbAmp I-module (I1) at the default address 0x50. Only
* current is needed, so no voltage-sensing variant is required;
* readCurrent(0) is the metered channel. (A UI1 works too — its voltage
* channel simply goes unused.)
*
* Board: ESP32 (Arduino framework); I2C @ 50 kHz. Non-ESP32 host = 100 kHz.
* Wiring: SDA->GPIO21, SCL->GPIO22; rbAmp VCC->5 V; common GND; ~4.7 kOhm
* pull-ups to 3.3 V; RELAY_PIN(GPIO26)->opto-isolated relay IN;
* ALERT_PIN(GPIO25)->LED(+resistor)/buzzer. Wire the load through the
* relay NO contact so de-energised = load OFF.
*
* Accuracy: per clamp rating — the class and the sensor's own tolerance are both in the accuracy table on the BASIC page.
*/
#include
#include
/* ---- configuration — the reader edits these ------------------------------ */
static const uint8_t RBAMP_ADDR = 0x50;
static const uint8_t METER_CH = 0; /* current channel on the module */
static const uint32_t I2C_HZ = 50000; /* ESP32-Arduino: 50 kHz */
/* Match to your clamp: Sct013_005 / _010 / _030 / _050 / _020. */
static const RbAmpCTModel MY_CT = RbAmpCTModel::Sct013_030;
/* Threshold with hysteresis (amps). Trip when the current stays at/above
* LIMIT_ON; a pending overload clears only when it falls below LIMIT_OFF, so
* the relay does not chatter around the setpoint. Keep LIMIT_OFF < LIMIT_ON. */
static const float LIMIT_ON = 10.0f;
static const float LIMIT_OFF = 8.0f;
/* Debounce / timing. */
static const uint32_t SAMPLE_MS = 200; /* current sample cadence */
static const uint32_t OVERLOAD_MS = 3000; /* sustained over-limit before trip (rides inrush) */
static const uint32_t COOLDOWN_MS = 10000; /* stay shed before an auto re-arm attempt */
/* ---- relay / alert GPIO -------------------------------------------------- */
static const uint8_t RELAY_PIN = 26;
static const uint8_t ALERT_PIN = 25;
#define RELAY_ACTIVE_HIGH 1 /* 1: HIGH energises. Set 0 for active-LOW opto modules. */
static inline void relayLoadOn(bool on) {
bool level = (RELAY_ACTIVE_HIGH ? on : !on);
digitalWrite(RELAY_PIN, level ? HIGH : LOW);
}
static inline void alertOn(bool on) {
digitalWrite(ALERT_PIN, on ? HIGH : LOW);
}
/* ---- state machine ------------------------------------------------------- */
enum LoadState { ARMED, OVER_PENDING, TRIPPED };
static LoadState state = ARMED;
static RbAmp dev(Wire, RBAMP_ADDR, RbAmpTopology::Single);
static uint32_t next_sample_ms = 0;
static uint32_t over_since_ms = 0; /* when the current first crossed LIMIT_ON */
static uint32_t tripped_at_ms = 0;
static uint32_t trip_count = 0;
static uint32_t bad_reads = 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()));
}
}
/* Params are uint8_t (not LoadState) so the Arduino .ino auto-prototype
* generator — which inserts prototypes above the enum definition — compiles. */
static const char* stateName(uint8_t s) {
switch (s) {
case ARMED: return "ARMED";
case OVER_PENDING: return "OVER_PENDING";
case TRIPPED: return "TRIPPED";
}
return "?";
}
static void enter(uint8_t s, float a) {
Serial.print(F("["));
Serial.print(millis());
Serial.print(F("ms] "));
Serial.print(stateName(state));
Serial.print(F(" -> "));
Serial.print(stateName(s));
Serial.print(F(" (I="));
Serial.print(a, 3);
Serial.println(F(" A)"));
state = static_cast(s);
}
/* ---- lifecycle ----------------------------------------------------------- */
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 2000) {}
/* Drive the outputs to the SAFE armed state FIRST (load powered, no alert),
* before any bus traffic, so a slow begin() never leaves the pin floating. */
pinMode(RELAY_PIN, OUTPUT);
pinMode(ALERT_PIN, OUTPUT);
relayLoadOn(true);
alertOn(false);
Wire.begin();
Wire.setClock(I2C_HZ);
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();
Serial.print(F("armed: trip>="));
Serial.print(LIMIT_ON, 1);
Serial.print(F("A for "));
Serial.print(OVERLOAD_MS / 1000.0f, 1);
Serial.print(F("s, clear<"));
Serial.print(LIMIT_OFF, 1);
Serial.println(F("A"));
next_sample_ms = millis();
}
void loop() {
uint32_t now = millis();
if (static_cast(now - next_sample_ms) < 0) {
delay(2);
return;
}
next_sample_ms = now + SAMPLE_MS;
float a = dev.readCurrent(METER_CH);
/* Graceful: a transient bad/NaN read must not cause a false trip or a false
* release. Hold the current state and skip this sample. */
if (isnan(a)) {
bad_reads++;
if (bad_reads % 10 == 1) {
Serial.print(F("read failed ("));
Serial.print(RbAmp::errorString(dev.lastError()));
Serial.println(F(") - holding state"));
}
return;
}
switch (state) {
case ARMED:
/* Load powered; watch for the current crossing the trip limit. */
if (a >= LIMIT_ON) {
over_since_ms = now;
enter(OVER_PENDING, a);
}
break;
case OVER_PENDING:
/* Load still powered. Clear on a drop below the release threshold
* (inrush/transient passed); trip on sustained overload. */
if (a < LIMIT_OFF) {
enter(ARMED, a);
} else if (static_cast(now - over_since_ms) >= static_cast(OVERLOAD_MS)) {
relayLoadOn(false);
alertOn(true);
tripped_at_ms = now;
trip_count++;
enter(TRIPPED, a);
Serial.print(F(" LOAD SHED (trip #"));
Serial.print(trip_count);
Serial.println(F(")"));
}
break;
case TRIPPED:
/* Load shed (current is ~0 now). Hold for the cooldown, then re-arm
* and re-close; if the overload persists it will trip again. */
if (static_cast(now - tripped_at_ms) >= static_cast(COOLDOWN_MS)) {
relayLoadOn(true);
alertOn(false);
enter(ARMED, a);
Serial.println(F(" cooldown elapsed - load re-energised"));
}
break;
}
}
(Verificato in compilazione su ESP32 con Arduino-CLI — solo Wire + RbAmp. Il pin del relè viene portato allo stato sicuro di carico acceso in setup() prima di qualsiasi traffico sul bus, così un begin() lento non lo lascia fluttuante.)
Cosa fa lo sketch
Il cuore è una macchina a tre stati — ARMED → OVER_PENDING → TRIPPED — valutata a ogni campione in loop(). Un paio di piccoli helper la mantengono pulita.
L'uscita sicura per impostazione predefinita
static inline void relayLoadOn(bool on) {
bool level = (RELAY_ACTIVE_HIGH ? on : !on); // one #define handles both board polarities
digitalWrite(RELAY_PIN, level ? HIGH : LOW);
}
relayLoadOn() nasconde la differenza active-high/active-low dietro un #define, così il resto del codice dice solo "carico acceso" o "carico spento". E setup() chiama relayLoadOn(true) prima di qualsiasi traffico I²C, così un begin() lento non lascia mai il pin del relè fluttuante.
La macchina a stati — loop()
float a = dev.readCurrent(METER_CH);
if (isnan(a)) { /* hold state, skip this sample */ return; }
switch (state) {
case ARMED: if (a >= LIMIT_ON) { over_since_ms = now; enter(OVER_PENDING, a); } break;
case OVER_PENDING: if (a < LIMIT_OFF) enter(ARMED, a);
else if (now - over_since_ms >= OVERLOAD_MS) { relayLoadOn(false); enter(TRIPPED, a); } break;
case TRIPPED: if (now - tripped_at_ms >= COOLDOWN_MS) { relayLoadOn(true); enter(ARMED, a); } break;
}
Dall'alto in basso:
-
ARMED — carico alimentato, in osservazione. Nel momento in cui la corrente raggiunge
LIMIT_ON, registra l'istante del superamento e passa aOVER_PENDING. Non è ancora scattato. -
OVER_PENDING — ancora alimentato, ora a cronometro. Se la corrente torna sotto
LIMIT_OFF(uno spunto che passa, o il carico che cala) torna ad ARMED — nessuno scatto. Se resta sopra il limite perOVERLOAD_MS, disinserisce: relè spento, allarme attivo, → TRIPPED. -
TRIPPED — carico disinserito. Dopo
COOLDOWN_MSsi riarma e richiude; se il sovraccarico persiste, scatta di nuovo.
Questo è l'intero comportamento rilevante per la sicurezza. L'isteresi sono le due soglie diverse (LIMIT_ON per lo scatto, LIMIT_OFF più bassa per il rilascio); il debounce dello spunto è l'attesa di OVERLOAD_MS, che lo spunto di avviamento di un motore o di un bollitore attraversa senza problemi. Una lettura NaN transitoria mantiene lo stato attuale e salta il campione, così una lettura errata non può mai causare uno scatto né un rilascio falsi. enter() registra ogni transizione sulla seriale con un timestamp e la corrente.
Quanto è veloce?
Locale e rapido. Il modulo aggiorna la sua corrente RMS circa ogni 200 ms (~5 Hz); l'Arduino la legge a ogni ciclo e, una volta che il superamento è durato oltre la finestra di debounce, commuta il relè nel passaggio successivo del ciclo — ben sotto il secondo di latenza decisionale, senza HA o cloud nel percorso. Questo è il vantaggio di fare il controllo sullo stesso microcontrollore che legge il contatore.
Lo personalizzi
-
Metta a punto —
LIMIT_ON/LIMIT_OFF/OVERLOAD_MS/COOLDOWN_MSsono tutte costanti in cima; le imposti per il suo circuito. -
Reset manuale — invece del riarmo automatico dopo il cooldown, attenda un pulsante così che una persona azzeri lo scatto.
-
Priorità — misuri più circuiti (la build multi-modulo) e disinserisca per primo il carico a priorità più bassa per restare sotto un limite dell'intera abitazione.
-
Registri gli scatti — scriva ogni transizione su una scheda SD per vedere quando e quante volte è scattato (la build del logger).
-
Controllo proporzionale — invece di un relè on/off netto, pilota un dimmer TRIAC e mantiene una corrente obiettivo con un loop PID (un progetto più grande — un assaggio per dopo).
Qualunque cosa aggiunga, mantenga la premessa qui sopra: questo resta uno strato di comodità, non un dispositivo di protezione.
Cosa segue
-
Registri ciò che è successo — scriva gli eventi di scatto e la corrente periodica su una scheda SD o su CSV via seriale (il prossimo in questa serie).
-
Lo vuole in Home Assistant? La versione HA — cursori, allarmi, disinserimento per priorità su un intero quadro — è il controllo dei carichi in tempo reale con rbAmp.