12 · Esempi MicroPython e CircuitPython
Questo capitolo è l'equivalente Python di arduino-examples.md: gli stessi dieci scenari, portati su MicroPython per ESP32 / RP2040 / ESP8266 / Pyboard, con le differenze di CircuitPython dove i due dialetti divergono.
Questi esempi comunicano con rbAmp direttamente tramite l'API grezza dei registri I²C. Sono pensati per integrazioni native, embedded o comunque con risorse limitate, dove serve il controllo diretto e ogni byte sul bus conta.
Per un'interfaccia più comoda e strutturata — usare la libreria MicroPython rbamp (vedi la tabella delle librerie client nel README). La libreria incapsula i dettagli a livello di registro in una classe RbAmp di alto livello con metodi con nome (dev.voltage, dev.latch_period(), dev.read_period_snapshot(), ecc.), API sincrone e uasyncio, un accumulatore Wh automatico per canale, helper multi-modulo e la disciplina di retry + controllo di coerenza SPEC §B.5 per i port ESP32 tramite MachineI2CBackend(retry_attempts=…). Lo stesso pacchetto funziona senza modifiche su CPython — vedi la tabella delle librerie client nel README. La maggior parte dei progetti dovrebbe partire dalla libreria e ricorrere all'API grezza solo quando necessario.
MicroPython vs CircuitPython — riferimento rapido
Il linguaggio Python è lo stesso; differiscono i moduli di accesso ai dispositivi. La tabella seguente associa ogni concetto usato negli esempi al modulo / classe equivalente in ciascun dialetto.
| Concetto | MicroPython | CircuitPython |
|---|---|---|
| Bus I2C | from machine import I2C, Pini2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000) |
import board, busioi2c = busio.I2C(board.SCL, board.SDA, frequency=50000) |
| Lettura di un singolo byte | i2c.readfrom_mem(addr, reg, 1)[0] |
with i2c_device: i2c_device.write_then_readinto(bytes([reg]), buf, in_end=1) (usando adafruit_bus_device.I2CDevice) |
| Scrittura di un singolo byte | i2c.writeto_mem(addr, reg, bytes([val])) |
i2c_device.write(bytes([reg, val])) |
| Ingresso GPIO + IRQ | pin = Pin(15, Pin.IN, Pin.PULL_UP)pin.irq(trigger=Pin.IRQ_FALLING, handler=fn) |
import digitalio, countiobtn = countio.Counter(board.D15, edge=countio.Edge.FALL)oppure keypad.Keys([board.D15], ...) |
| Sospensione (sec / ms) | time.sleep(s) / time.sleep_ms(ms) |
time.sleep(s) (non sleep_ms) |
| ms / µs monotoni | time.ticks_ms(), time.ticks_us(), time.ticks_diff(a, b) |
time.monotonic_ns() / time.monotonic() (non ticks_diff) |
| WiFi | import networkwlan = network.WLAN(network.STA_IF) |
import wifiwifi.radio.connect(ssid, pwd) (ESP32-S2/S3/C3 con CP nativo) |
| MQTT | from umqtt.simple import MQTTClient |
import adafruit_minimqtt.adafruit_minimqtt as mqtt |
| NTP | import ntptime; ntptime.settime() |
import adafruit_ntp; ntp = adafruit_ntp.NTP(socketpool, server="...") |
| Deep sleep | import machine; machine.deepsleep(ms) |
import alarm; alarm.exit_and_deep_sleep_until_alarms(time_alarm) |
| Memoria RTC conservata | machine.RTC().memory(buf) |
import alarm; alarm.sleep_memory[...] |
| Asincrono | import uasyncio as asyncio |
import asyncio (CircuitPython 8+) |
Ogni esempio qui sotto è scritto in MicroPython. Dove l'equivalente CircuitPython differisce per più di una singola riga di import, è riportato un blocco esplicito «Differenze per CircuitPython».
Indice degli esempi
| # | Titolo | Difficoltà | Uscita | MQTT | DRDY | Più moduli | Bidirezionale | Caso d'uso |
|---|---|---|---|---|---|---|---|---|
| 1 | Lettura rapida | minimo | REPL | — | — | — | — | Test di funzionamento |
| 2 | Misuratore di energia a 60 secondi su OLED | basso | SSD1306 | — | — | — | — | Contatore Wh in custodia |
| 3 | Monitor a più moduli | basso | REPL | — | — | sì (3) | — | Monitoraggio dell'intera abitazione |
| 4 | Monitoraggio energetico per singolo apparecchio (UI3) | medio | — | sì | — | — | — | Sotto-misura in HA |
| 5 | Bidirezionale lato master su un modulo BASIC | medio | REPL | — | sì | — | sì (master) | Casa solare su livello BASIC |
| 6 | Bilancio energetico domestico | alta | — | sì | — | sì (3) | sì | Bilancio domestico completo |
| 7 | Rilevazione di eventi di alimentazione | medio | REPL + SD | — | sì | — | — | Registro eventi degli apparecchi |
| 8 | Publisher MQTT con HA Auto-discovery | medio | — | sì (+disco) | — | — | facoltativo | Integrazione HA pronta all'uso |
| 9 | Registratore remoto alimentato a batteria con deep sleep | medio | — | sì | — | — | — | Misuratore fuori rete / per esterni |
| 10 | Tariffa a fasce orarie (TOU) con orologio NTP | medio | REPL | sì | — | — | facoltativo | Misura con tariffa di punta / fuori punta |
Intestazione comune per tutti gli esempi
Ogni esempio presuppone che questi helper siano presenti nello stesso file .py (o importati da un helpers.py). Per risparmiare spazio, il blocco non viene ripetuto in ogni sketch.
"""
rbAmp raw-I2C helpers for MicroPython.
For CircuitPython, replace the I2C bring-up:
import board, busio
from adafruit_bus_device.i2c_device import I2CDevice
i2c_bus = busio.I2C(board.SCL, board.SDA, frequency=50000)
# then use I2CDevice(i2c_bus, addr) for each rbAmp, see notes in each example.
"""
import struct
import time
from machine import I2C, Pin # MicroPython
def rb_read_u8(i2c, addr, reg):
"""Read one byte from an rbAmp slave register.
:param i2c: machine.I2C instance.
:param addr: 7-bit slave address (e.g. 0x50).
:param reg: register address inside the slave.
:returns: the byte stored in the register.
"""
return i2c.readfrom_mem(addr, reg, 1)[0]
def rb_read_float_le(i2c, addr, reg):
"""Read a little-endian float32 from four consecutive registers.
rbAmp supports READ auto-increment (a single burst-read is valid for
atomicity). The per-byte form below is shown for clarity. WRITE
transactions, by contrast, are byte-at-a-time only. See chapter 11.
"""
b = bytes([rb_read_u8(i2c, addr, reg + i) for i in range(4)])
return struct.unpack('> 8) & 0xFF]))
return True
except OSError:
return False
def rb_wait_ready(i2c, addr, timeout_ms=2000):
"""Block until DATA_VALID bit 0 is 1, or raise OSError on timeout."""
t0 = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms:
if rb_read_u8(i2c, addr, 0xCE) & 0x01:
return
time.sleep_ms(50)
raise OSError("rbAmp at 0x{:02X} not ready".format(addr))
Differenze per CircuitPython — header comune
CircuitPython usa adafruit_bus_device.i2c_device.I2CDevice (wrapper per slave) e non ha time.ticks_ms. Helper equivalenti:
import time
import struct
import board, busio
from adafruit_bus_device.i2c_device import I2CDevice
def cp_read_u8(dev, reg):
"""Read one byte from one register (CircuitPython)."""
buf = bytearray(1)
with dev:
dev.write_then_readinto(bytes([reg]), buf)
return buf[0]
def cp_read_float_le(dev, reg):
b = bytes(cp_read_u8(dev, reg + i) for i in range(4))
return struct.unpack('> 8) & 0xFF]))
return True
except OSError:
return False
finally:
i2c_bus.unlock()
def cp_wait_ready(dev, timeout_s=2.0):
t0 = time.monotonic()
while time.monotonic() - t0 < timeout_s:
if cp_read_u8(dev, 0xCE) & 0x01:
return
time.sleep(0.05)
raise OSError("rbAmp not ready")
Esempio 1 — Lettura rapida (minima)
Obiettivo: stampare U, I, P, PF in una REPL una volta al secondo. Hardware: ESP32 / RP2040 / Pico W + un rbAmp UI1.
from machine import I2C, Pin
import time
# I2C bus 0 on ESP32 default pins.
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
RB_ADDR = 0x50
# Wait until the first RT window has been computed.
rb_wait_ready(i2c, RB_ADDR)
ver = rb_read_u8(i2c, RB_ADDR, 0x03)
print("rbAmp version: 0x{:02X}".format(ver))
while True:
u = rb_read_float_le(i2c, RB_ADDR, 0x86) # RMS voltage, V
i_ = rb_read_float_le(i2c, RB_ADDR, 0x8E) # RMS current, A
p = rb_read_float_le(i2c, RB_ADDR, 0xA6) # active power, W (signed)
pf = rb_read_float_le(i2c, RB_ADDR, 0xB2) # power factor, signed
print("U={:.1f}V I={:.3f}A P={:+.1f}W PF={:+.3f}".format(u, i_, p, pf))
time.sleep(1)
Differenza CircuitPython
import board, busio, time
from adafruit_bus_device.i2c_device import I2CDevice
i2c_bus = busio.I2C(board.SCL, board.SDA, frequency=50000)
dev = I2CDevice(i2c_bus, 0x50)
cp_wait_ready(dev)
print("rbAmp version: 0x{:02X}".format(cp_read_u8(dev, 0x03)))
while True:
u = cp_read_float_le(dev, 0x86)
i_ = cp_read_float_le(dev, 0x8E)
p = cp_read_float_le(dev, 0xA6)
pf = cp_read_float_le(dev, 0xB2)
print("U={:.1f}V I={:.3f}A P={:+.1f}W PF={:+.3f}".format(u, i_, p, pf))
time.sleep(1)
Esempio 2 — contatore energetico a 60 secondi su OLED
Obiettivo: contatore Wh aggiornato una volta al minuto, mostrato su un OLED SSD1306 128×64. Hardware: ESP32 + rbAmp + OLED SSD1306 sullo stesso bus. Contabilità: unidirezionale (livello BASIC). Libreria: ssd1306.py dagli esempi MicroPython (un driver standard in un solo file).
from machine import I2C, Pin
import time
import ssd1306
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
RB_ADDR = 0x50
oled = ssd1306.SSD1306_I2C(128, 64, i2c) # OLED typically at 0x3C
rb_wait_ready(i2c, RB_ADDR)
# Primer snapshot — discard its result.
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27)
t_prev_ms = time.ticks_ms()
total_wh = 0.0
while True:
time.sleep(60)
# 1) Final snapshot — closes the period [t_prev_ms .. now].
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27)
t_now_ms = time.ticks_ms()
time.sleep_ms(50) # let firmware finalise the snapshot
# 2) Verify the snapshot is fresh.
if (rb_read_u8(i2c, RB_ADDR, 0x07) & 0x01) == 0:
print("WARN: stale snapshot")
t_prev_ms = time.ticks_ms()
continue
# 3) Read time-averaged power, channel 0.
avg_p = rb_read_float_le(i2c, RB_ADDR, 0xDC)
# 4) Energy uses the MASTER clock (authoritative).
dt_s = time.ticks_diff(t_now_ms, t_prev_ms) / 1000.0
e_wh = avg_p * dt_s / 3600.0
total_wh += e_wh
t_prev_ms = t_now_ms
# 5) Render on OLED.
oled.fill(0)
oled.text("P: {:6.1f} W".format(avg_p), 0, 0)
oled.text("dt: {:6.1f} s".format(dt_s), 0, 16)
oled.text("E: {:.2f} Wh".format(total_wh), 0, 32)
oled.show()
print("avg_P={:.1f} E_period={:.3f} total={:.3f}".format(avg_p, e_wh, total_wh))
: usi adafruit_ssd1306 (variante displayio oppure variante framebuf). Il costruttore dell'OLED è diverso, ma il resto del ciclo resta invariato — sostituisca le chiamate rb_* con le funzioni di supporto cp_* e usi time.monotonic() per dt_s.
Esempio 3 — Monitor multi-modulo
Obiettivo: interrogare tre moduli (alimentazione principale, scaldabagno, condizionatore) e stampare il totale. Hardware: ESP32 + 3 × rbAmp UI1 a 0x50, 0x51, 0x52.
from machine import I2C, Pin
import time
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
modules = ((0x50, "Mains "), (0x51, "Boiler"), (0x52, "AC "))
# I2C scan — confirm every module is present.
present = i2c.scan()
for addr, label in modules:
if addr not in present:
raise RuntimeError("{} at 0x{:02X} not on bus".format(label, addr))
print("All modules OK:", [hex(a) for a in present])
while True:
total_p = 0.0
print("---")
for addr, label in modules:
u = rb_read_float_le(i2c, addr, 0x86)
p = rb_read_float_le(i2c, addr, 0xA6)
print("[{}] U={:.1f} P={:+.1f} W".format(label, u, p))
total_p += p
print("TOTAL: {:.1f} W".format(total_p))
time.sleep(2)
Esempio 4 — Monitoraggio energetico per singolo apparecchio (UI3)
Obiettivo: un modulo UI3 con tre pinze TA su tre carichi diversi sulla stessa fase. Contatori Wh indipendenti per carico, pubblicati via MQTT ogni minuto. Hardware: ESP32 + 1 × rbAmp UI3. Libreria: umqtt.simple (MicroPython) o umqtt.robust per la riconnessione automatica.
from machine import I2C, Pin
import network, time
from umqtt.simple import MQTTClient
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
RB_ADDR = 0x50
CH_NAMES = ("main", "heatpump", "lights")
# --- Wi-Fi ---
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("ssid", "password")
while not wlan.isconnected():
time.sleep(0.5)
# --- MQTT ---
mqtt = MQTTClient(client_id="rbamp-ui3", server="192.168.1.10")
mqtt.connect()
def mqtt_publish(ch_name, avg_p, e_wh):
"""Publish one channel's state to MQTT.
:param ch_name: short channel name (used in the topic).
:param avg_p: time-averaged power, W.
:param e_wh: accumulated channel energy, Wh.
"""
topic = "rbamp/{}/state".format(ch_name).encode()
payload = '{{"power":{:.1f},"energy":{:.4f}}}'.format(avg_p, e_wh).encode()
mqtt.publish(topic, payload)
rb_wait_ready(i2c, RB_ADDR)
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27) # primer snapshot
t_prev_ms = time.ticks_ms()
total_wh = [0.0, 0.0, 0.0]
while True:
time.sleep(60)
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27)
t_now_ms = time.ticks_ms()
time.sleep_ms(50)
if (rb_read_u8(i2c, RB_ADDR, 0x07) & 0x01) == 0:
t_prev_ms = time.ticks_ms()
continue
# PERIOD_AVG_P_W per channel: I0 at 0xDC, I1 at 0xC2, I2 at 0xC6.
avg_p = (rb_read_float_le(i2c, RB_ADDR, 0xDC),
rb_read_float_le(i2c, RB_ADDR, 0xC2),
rb_read_float_le(i2c, RB_ADDR, 0xC6))
dt_s = time.ticks_diff(t_now_ms, t_prev_ms) / 1000.0
t_prev_ms = t_now_ms
for ch in range(3):
e = avg_p[ch] * dt_s / 3600.0
total_wh[ch] += e
print("[{}] avg_P={:+.1f} W E_total={:.3f} Wh".format(
CH_NAMES[ch], avg_p[ch], total_wh[ch]))
mqtt_publish(CH_NAMES[ch], avg_p[ch], total_wh[ch])
: sostituire umqtt.simple.MQTTClient con adafruit_minimqtt.MQTT(...) (richiede un socket_pool e un ssl_context — vedi la guida WiFi di Adafruit). La logica di misura resta invariata.
Esempio 5 — Bidirezionale lato master su un modulo BASIC
Obiettivo: implementare la contabilità bidirezionale sul master mentre il firmware del modulo è BASIC (l'accumulatore di periodo azzera i campioni negativi). Leggere P_real RT a ogni fronte DRDY e separare consumo ed esportazione. Hardware: ESP32 + rbAmp UI1 su un carico con inverter solare + DRDY collegato a un GPIO.
from machine import I2C, Pin
import time
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
drdy = Pin(15, Pin.IN, Pin.PULL_UP)
RB_ADDR = 0x50
_data_ready = False
_e_consumed_wh = 0.0
_e_exported_wh = 0.0
_t_last_sample_ms = 0
def _drdy_isr(pin):
"""ISR for DRDY falling edge — only sets a flag (no I2C inside ISR)."""
global _data_ready
_data_ready = True
drdy.irq(trigger=Pin.IRQ_FALLING, handler=_drdy_isr)
rb_wait_ready(i2c, RB_ADDR)
_t_last_sample_ms = time.ticks_ms()
_last_print = time.ticks_ms()
print("Bidirectional accumulator started")
while True:
if not _data_ready:
time.sleep_ms(10)
continue
_data_ready = False
t_now = time.ticks_ms()
# Signed instantaneous P_real: + consume, − export.
p = rb_read_float_le(i2c, RB_ADDR, 0xA6)
dt_s = time.ticks_diff(t_now, _t_last_sample_ms) / 1000.0
_t_last_sample_ms = t_now
if p > 0:
_e_consumed_wh += p * dt_s / 3600.0
else:
_e_exported_wh += -p * dt_s / 3600.0
# Summary print every 5 s — not on every RT window.
if time.ticks_diff(t_now, _last_print) >= 5000:
_last_print = t_now
print("P={:+8.1f}W consumed={:.4f} Wh exported={:.4f} Wh net={:+.4f} Wh"
.format(p, _e_consumed_wh, _e_exported_wh,
_e_consumed_wh - _e_exported_wh))
: CircuitPython sconsiglia in genere le IRQ GPIO definite dall'utente. Usare countio.Counter(board.D15, edge=countio.Edge.FALL) e interrogare il suo count dal loop principale, oppure keypad.Keys(...) per gli eventi di fronte. La logica dell'accumulatore è identica.
Esempio 6 — Bilancio energetico domestico
Obiettivo: un cruscotto completo del bilancio. Tre moduli:
- rbAmp #1 sulla linea principale (STD — bidirezionale)
- rbAmp #2 sull'uscita dell'inverter solare
- rbAmp #3 UI3 su tre grandi carichi (HP, AC, EV)
Il master calcola total_consumed = solar_self_used + grid_consumed e solar_generated = solar_self_used + grid_exported. Hardware: ESP32 + 3 × rbAmp + Wi-Fi + MQTT.
from machine import I2C, Pin
import network, time, ujson as json
from umqtt.simple import MQTTClient
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
ADDR_MAINS = 0x50 # bidirectional (STD)
ADDR_SOLAR = 0x51 # generation only
ADDR_LOADS = 0x52 # UI3
# PERIOD_AVG_P_NEG address for the mains module — see the SKU datasheet
# of the STD product. Set to None on BASIC modules.
REG_PERIOD_AVG_P_NEG_MAINS = None
wlan = network.WLAN(network.STA_IF); wlan.active(True); wlan.connect("ssid", "password")
while not wlan.isconnected():
time.sleep(0.5)
mqtt = MQTTClient("home-balance", "192.168.1.10"); mqtt.connect()
# Wait until all three modules report DATA_VALID.
for addr in (ADDR_MAINS, ADDR_SOLAR, ADDR_LOADS):
rb_wait_ready(i2c, addr)
totals = {
"mains_in_wh": 0.0,
"mains_out_wh": 0.0,
"solar_total_wh": 0.0,
"loads_wh": [0.0, 0.0, 0.0],
}
gc_tick = 0
if not rb_broadcast_latch(i2c, gc_tick):
# GC NACK → fall back to per-module sequential snapshot.
for addr in (ADDR_MAINS, ADDR_SOLAR, ADDR_LOADS):
rb_write_u8(i2c, addr, 0x01, 0x27)
gc_tick += 1
t_prev_ms = time.ticks_ms()
print("Home balance started")
while True:
time.sleep(60)
if not rb_broadcast_latch(i2c, gc_tick):
for addr in (ADDR_MAINS, ADDR_SOLAR, ADDR_LOADS):
rb_write_u8(i2c, addr, 0x01, 0x27)
gc_tick = (gc_tick + 1) & 0xFFFF
t_now_ms = time.ticks_ms()
time.sleep_ms(50)
dt_s = time.ticks_diff(t_now_ms, t_prev_ms) / 1000.0
t_prev_ms = t_now_ms
# --- MAINS (bidirectional, STD) ---
if rb_read_u8(i2c, ADDR_MAINS, 0x07) & 0x01:
avg_p_consume = rb_read_float_le(i2c, ADDR_MAINS, 0xDC)
avg_p_export = (rb_read_float_le(i2c, ADDR_MAINS, REG_PERIOD_AVG_P_NEG_MAINS)
if REG_PERIOD_AVG_P_NEG_MAINS is not None else 0.0)
totals["mains_in_wh"] += avg_p_consume * dt_s / 3600.0
totals["mains_out_wh"] += avg_p_export * dt_s / 3600.0
# --- SOLAR (generation only) ---
if rb_read_u8(i2c, ADDR_SOLAR, 0x07) & 0x01:
avg_p = rb_read_float_le(i2c, ADDR_SOLAR, 0xDC)
totals["solar_total_wh"] += avg_p * dt_s / 3600.0
# --- LOADS (UI3, three channels) ---
if rb_read_u8(i2c, ADDR_LOADS, 0x07) & 0x01:
for i, reg in enumerate((0xDC, 0xC2, 0xC6)): # I0, I1, I2
p = rb_read_float_le(i2c, ADDR_LOADS, reg)
totals["loads_wh"][i] += p * dt_s / 3600.0
# --- Derived balance figures ---
total_consumed = (totals["mains_in_wh"] + totals["solar_total_wh"]
- totals["mains_out_wh"])
solar_self_used = max(0.0, totals["solar_total_wh"] - totals["mains_out_wh"])
print("MAINS in={:.2f} out={:.2f}".format(totals["mains_in_wh"],
totals["mains_out_wh"]))
print("SOLAR gen={:.2f} self-used={:.2f} exported={:.2f}".format(
totals["solar_total_wh"], solar_self_used, totals["mains_out_wh"]))
print("LOADS HP={:.2f} AC={:.2f} EV={:.2f}".format(*totals["loads_wh"]))
print("TOTAL household consumed={:.2f} Wh".format(total_consumed))
payload = json.dumps({
"mains_in": totals["mains_in_wh"],
"mains_out": totals["mains_out_wh"],
"solar": totals["solar_total_wh"],
"self_used": solar_self_used,
"total_consumed": total_consumed,
"hp": totals["loads_wh"][0],
"ac": totals["loads_wh"][1],
"ev": totals["loads_wh"][2],
})
mqtt.publish(b"home/energy/balance", payload.encode(), retain=True)
Notes:
rb_broadcast_latch(i2c, tick)garantisce che tutti e tre i moduli acquisiscano l'istantanea nello stesso istante — fondamentale per un saldo accurato. La ricezione GC è opzionale (FLEET_CONFIG.bit0, predefinito OFF, vedere capitolo 02). In caso di NACK, si passa all'istantanea sequenziale per modulo (sfasamento di circa 1 ms per modulo a 50 kHz).solar_self_used = solar_total − grid_exported; limiti a zero per assorbire il rumore di misura.
Esempio 7 — Rilevazione di eventi di alimentazione
Obiettivo: a ogni fronte DRDY, confrontare la potenza istantanea P con una EMA e registrare su scheda SD gli scostamenti significativi. Hardware: ESP32 + rbAmp + scheda SD (pilotata via SPI, ad es. tramite il driver MicroPython sdcard.py). Caso d'uso: rilevazione automatica di eventi di carichi elevati (forno a microonde, climatizzatore, bollitore).
from machine import I2C, Pin, SPI
import time, os, sdcard
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
drdy = Pin(15, Pin.IN, Pin.PULL_UP)
RB_ADDR = 0x50
# Mount the SD card on /sd (SPI bus 1, CS = GPIO 5).
spi = SPI(1, baudrate=1_000_000, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
sd = sdcard.SDCard(spi, Pin(5))
os.mount(sd, "/sd")
EMA_ALPHA = 0.05 # ~2 s time constant at 10 Hz
EVENT_THRESHOLD_W = 200.0
_data_ready = False
def _drdy_isr(pin):
global _data_ready
_data_ready = True
drdy.irq(trigger=Pin.IRQ_FALLING, handler=_drdy_isr)
rb_wait_ready(i2c, RB_ADDR)
# Seed the EMA with the current power so we do not log a spurious startup event.
p_ema = rb_read_float_le(i2c, RB_ADDR, 0xA6)
print("Event detector started")
logfile = open("/sd/events.log", "a")
while True:
if not _data_ready:
time.sleep_ms(10)
continue
_data_ready = False
p = rb_read_float_le(i2c, RB_ADDR, 0xA6)
delta = p - p_ema
p_ema = (1 - EMA_ALPHA) * p_ema + EMA_ALPHA * p
if abs(delta) > EVENT_THRESHOLD_W:
event = "TURN_ON" if delta > 0 else "TURN_OFF"
line = "{} {} delta={:+.1f} W P={:.1f} W EMA={:.1f} W\n".format(
time.ticks_ms(), event, delta, p, p_ema)
print(line, end="")
logfile.write(line)
logfile.flush() # ensure the line hits the card
: usare adafruit_sdcard.SDCard + storage.mount(VfsFat(sdcard), "/sd"). Sostituire l'IRQ con countio.Counter(board.D15, edge=countio.Edge.FALL) interrogato dal loop principale.
Esempio 8 — Publisher MQTT con auto-discovery di Home Assistant
Obiettivo: integrazione HA pronta all'uso. L'ESP32 si connette a Wi-Fi e a un broker MQTT, pubblica le configurazioni HA Auto-discovery (così le entità compaiono senza alcuno YAML) ed emette uno stato JSON ogni minuto. Hardware: ESP32 + un rbAmp UI1 + rete Wi-Fi con broker MQTT. Contabilizzazione: unidirezionale.
from machine import I2C, Pin
import network, time, ujson as json
from umqtt.simple import MQTTClient
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
RB_ADDR = 0x50
WIFI_SSID = "ssid"
WIFI_PASS = "password"
MQTT_HOST = "192.168.1.10"
MQTT_USER = "ha"
MQTT_PASS = "secret"
DEVICE_ID = "rbamp_main"
DEVICE_NAME = "Mains rbAmp"
# Bring up WiFi.
wlan = network.WLAN(network.STA_IF); wlan.active(True); wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print("WiFi up:", wlan.ifconfig()[0])
mqtt = MQTTClient(DEVICE_ID, MQTT_HOST, user=MQTT_USER, password=MQTT_PASS)
mqtt.connect()
DEVICE = {
"identifiers": [DEVICE_ID],
"name": DEVICE_NAME,
"manufacturer": "rbAmp",
"model": "rbAmp UI*",
}
def publish_discovery_sensor(key, friendly, unit, dev_class, state_class):
"""Publish one HA discovery config (retained).
:param key: short id used in the topic and value_template.
:param friendly: HA friendly-name suffix.
:param unit: unit_of_measurement, or None.
:param dev_class: HA device_class string, or None.
:param state_class: 'measurement' or 'total_increasing'.
"""
cfg = {
"name": "{} {}".format(DEVICE_NAME, friendly),
"unique_id": "{}_{}".format(DEVICE_ID, key),
"state_topic": "rbamp/{}/state".format(DEVICE_ID),
"value_template": "{{{{ value_json.{} }}}}".format(key),
"state_class": state_class,
"device": DEVICE,
}
if unit: cfg["unit_of_measurement"] = unit
if dev_class: cfg["device_class"] = dev_class
topic = "homeassistant/sensor/{}/{}/config".format(DEVICE_ID, key).encode()
mqtt.publish(topic, json.dumps(cfg).encode(), retain=True)
def publish_discovery_all():
"""Publish the full set of HA discovery configs for one rbAmp module."""
publish_discovery_sensor("voltage", "Voltage", "V", "voltage", "measurement")
publish_discovery_sensor("current", "Current", "A", "current", "measurement")
publish_discovery_sensor("power", "Power", "W", "power", "measurement")
publish_discovery_sensor("energy", "Energy", "Wh", "energy", "total_increasing")
publish_discovery_sensor("frequency", "Frequency", "Hz", "frequency", "measurement")
publish_discovery_sensor("power_factor", "Power Factor", None, "power_factor", "measurement")
publish_discovery_sensor("apparent_power", "Apparent Power", "VA", "apparent_power", "measurement")
publish_discovery_sensor("reactive_power", "Reactive Power", "var", "reactive_power", "measurement")
publish_discovery_all()
rb_wait_ready(i2c, RB_ADDR)
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27) # primer snapshot
t_prev_ms = time.ticks_ms()
total_wh = 0.0
while True:
time.sleep(60)
# Snapshot + read period snapshot.
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27)
t_now_ms = time.ticks_ms()
time.sleep_ms(50)
if (rb_read_u8(i2c, RB_ADDR, 0x07) & 0x01) == 0:
t_prev_ms = time.ticks_ms()
continue
avg_p = rb_read_float_le(i2c, RB_ADDR, 0xDC)
dt_s = time.ticks_diff(t_now_ms, t_prev_ms) / 1000.0
total_wh += avg_p * dt_s / 3600.0
t_prev_ms = t_now_ms
# Live RT values.
u = rb_read_float_le(i2c, RB_ADDR, 0x86)
i_ = rb_read_float_le(i2c, RB_ADDR, 0x8E)
pf = rb_read_float_le(i2c, RB_ADDR, 0xB2)
q = rb_read_float_le(i2c, RB_ADDR, 0xD0)
freq = rb_read_u8(i2c, RB_ADDR, 0x20)
payload = json.dumps({
"voltage": u,
"current": i_,
"power": avg_p,
"energy": total_wh,
"frequency": freq,
"power_factor": pf,
"apparent_power": u * i_,
"reactive_power": q,
})
mqtt.publish("rbamp/{}/state".format(DEVICE_ID).encode(), payload.encode())
print("Published:", payload)
: usi adafruit_minimqtt.MQTT con un socket pool da wifi.radio. I payload di discovery si costruiscono allo stesso modo. Per il codice di socket, consulti la guida di Adafruit su MQTT + HA discovery.
Esempio 9 — Registratore remoto alimentato a batteria con deep sleep
Obiettivo: un registratore per esterni / fuori rete che si risveglia ogni 10 minuti, acquisisce un periodo, pubblica via MQTT e torna in deep sleep. Assorbimento medio di pochi mA — una singola cella Li-ion dura mesi. Hardware: ESP32 (o ESP32-S3) + un rbAmp UI1 + Li-ion piccola + Wi-Fi. Contabilità: unidirezionale. L'energia sopravvive al deep sleep tramite la memoria RTC.
from machine import I2C, Pin, RTC, deepsleep
import network, time, struct, ujson as json
from umqtt.simple import MQTTClient
SLEEP_MS = 10 * 60 * 1000 # 10-minute wake interval
RB_ADDR = 0x50
# RTC retained memory layout (with a magic-marker sentinel so garbage RTC RAM
# after a brown-out or watchdog reset is NOT mistaken for valid state):
# uint32 magic == 0xCAFEFEED (4 bytes)
# double total_wh (8 bytes)
# uint32 wake_count (4 bytes)
# uint8 primer_done (1 byte) + 3 bytes pad
#
# NOTE on dt: we do NOT persist a microsecond counter because time.ticks_us()
# is monotonic SINCE BOOT — it resets to 0 on every deep-sleep wake, so
# carrying the previous value across sleep is meaningless. dt is approximated
# by the configured SLEEP_MS interval; for tighter accuracy use machine.RTC()
# .datetime() which DOES survive deep sleep.
_MAGIC = 0xCAFEFEED
_FMT = " timeout_s * 1000:
return None
time.sleep_ms(100)
return wlan
def publish_measurement(wake_count, dt_s, avg_p, total_e):
"""Publish one period sample via MQTT, retained."""
mqtt = MQTTClient("rbamp-remote", "192.168.1.10")
mqtt.connect()
payload = json.dumps({
"wake": wake_count,
"dt_s": round(dt_s, 1),
"avg_p": round(avg_p, 1),
"energy_wh": round(total_e, 3),
})
mqtt.publish(b"rbamp/remote/state", payload.encode(), retain=True)
mqtt.disconnect()
print("Published:", payload)
# ===== Main wake-handler — runs on every wake-up =====
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
total_wh, wake_count, primer_done = _rtc_load()
wake_count += 1
rb_wait_ready(i2c, RB_ADDR)
# First wake-up after a cold boot: primer snapshot only.
if not primer_done:
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27)
_rtc_save(total_wh, wake_count, 1)
print("Primer done — sleeping until first real period")
deepsleep(SLEEP_MS)
# Subsequent wake-ups: close the period and read its average power.
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27)
time.sleep_ms(50)
if (rb_read_u8(i2c, RB_ADDR, 0x07) & 0x01) == 0:
print("WARN: stale snapshot — skipping this cycle")
_rtc_save(total_wh, wake_count, 1)
deepsleep(SLEEP_MS)
avg_p = rb_read_float_le(i2c, RB_ADDR, 0xDC)
# dt approximation: deep sleep + boot ≈ SLEEP_MS. time.ticks_us() resets
# every wake so a stored "previous" value would be meaningless; the
# configured interval is accurate to single-digit-% on the ESP32 RTC.
dt_s = SLEEP_MS / 1000.0
total_wh += avg_p * dt_s / 3600.0
_rtc_save(total_wh, wake_count, 1)
# Publish; fall back gracefully if WiFi is unreachable.
if wifi_connect(timeout_s=8):
try:
publish_measurement(wake_count, dt_s, avg_p, total_wh)
except Exception as e:
print("MQTT failed, value buffered in RTC:", e)
else:
print("WiFi failed — value buffered in RTC, retry next wake")
print("Deep sleep")
deepsleep(SLEEP_MS)
Bilancio energetico (tipico, ESP32-WROOM):
- Durata della veglia per ogni risveglio: circa 3 s.
- Corrente in veglia: ~80 mA medi → ~0.07 mAh per risveglio.
- Corrente in sleep: ~10 µA (domini RTC conservati).
- Un risveglio ogni 10 min → circa 10 mAh al giorno → una singola Li-ion da 2000 mAh dura circa 6 mesi.
: usi alarm.time.TimeAlarm(monotonic_time=...) + alarm.exit_and_deep_sleep_until_alarms(alarm) invece di machine.deepsleep. Salvi total_wh in alarm.sleep_memory (un bytearray sopravvive al deep sleep). La NVM (microcontroller.nvm) sopravvive anche alla perdita di alimentazione, ma ha un numero limitato di scritture.
Esempio 10 — Tariffa a fasce orarie (TOU) con orologio NTP
Obiettivo: fatturare l'energia secondo una tariffa a fasce orarie (tariffe diverse per le ore di punta e fuori punta). L'ESP32 mantiene un orologio reale tramite NTP, assegna ogni periodo chiuso alla fascia tariffaria corretta, azzera i totali giornalieri a mezzanotte e pubblica i payload con timestamp ISO. Hardware: ESP32 + un rbAmp UI1 + Wi-Fi. Contabilizzazione: unidirezionale. La logica delle fasce funziona su STD — basta farvi passare entrambi gli accumulatori.
from machine import I2C, Pin
import network, ntptime, time, ujson as json
from umqtt.simple import MQTTClient
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50000)
RB_ADDR = 0x50
WIFI_SSID = "ssid"
WIFI_PASS = "password"
MQTT_HOST = "192.168.1.10"
# Local UTC offset in hours. For DST, recompute on roll-over or use a TZ library.
# Example: Central European Summer Time = UTC+2.
TZ_OFFSET_HOURS = 2
# Time-of-use schedule: peak hours [PEAK_START_HOUR .. PEAK_END_HOUR), local time.
PEAK_START_HOUR = 8
PEAK_END_HOUR = 22
def wifi_connect():
wlan = network.WLAN(network.STA_IF); wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print("WiFi up:", wlan.ifconfig()[0])
def ntp_sync():
"""Synchronise the on-board RTC with NTP (UTC).
Returns True on success, False on persistent failure. DOES NOT raise —
a TOU meter that crashes when NTP is unreachable is worse than one that
skips bucketing for the current period and retries later.
"""
ntptime.host = "pool.ntp.org"
for _ in range(5):
try:
ntptime.settime()
t = time.gmtime()
print("NTP sync: {:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d} UTC".format(*t[:6]))
return True
except Exception as e:
print("NTP retry:", e)
time.sleep(2)
print("WARN: NTP sync failed — tariff bucketing paused until next sync")
return False
def local_time():
"""Return current local time as a 9-tuple struct_time (year, mon, ..., wday, yday)."""
return time.gmtime(time.time() + TZ_OFFSET_HOURS * 3600)
def is_peak_hour(hour):
"""True if `hour` (0..23 local) is inside the peak tariff window.
For schedules that cross midnight (peak 22..6), change to
return hour >= PEAK_START_HOUR or hour < PEAK_END_HOUR
"""
return PEAK_START_HOUR <= hour < PEAK_END_HOUR
def iso_now():
"""Return the current local time as an ISO 8601 string with offset."""
t = local_time()
sign = "+" if TZ_OFFSET_HOURS >= 0 else "-"
return "{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}{}{:02d}00".format(
t[0], t[1], t[2], t[3], t[4], t[5], sign, abs(TZ_OFFSET_HOURS))
wifi_connect()
ntp_sync()
mqtt = MQTTClient("rbamp-tou", MQTT_HOST); mqtt.connect()
rb_wait_ready(i2c, RB_ADDR)
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27) # primer snapshot
t_prev_ms = time.ticks_ms()
print("TOU started: peak {:02d}:00..{:02d}:00 local".format(PEAK_START_HOUR, PEAK_END_HOUR))
# Tariff buckets.
today = {"peak_wh": 0.0, "off_peak_wh": 0.0, "yday": -1}
lifetime = {"peak_wh": 0.0, "off_peak_wh": 0.0}
def accumulate(e_wh, tm):
"""Add one period's energy to the right bucket; roll over the day at midnight.
:param e_wh: Wh in this period.
:param tm: local struct_time at the snapshot instant.
"""
yday = tm[7] # struct_time.tm_yday is index 7
if today["yday"] != yday:
if today["yday"] >= 0:
payload = json.dumps({
"yday": today["yday"],
"peak_wh": today["peak_wh"],
"off_peak_wh": today["off_peak_wh"],
"total_wh": today["peak_wh"] + today["off_peak_wh"],
})
mqtt.publish(b"rbamp/tou/day_close", payload.encode(), retain=True)
print("Day closed:", payload)
today["peak_wh"] = 0.0
today["off_peak_wh"] = 0.0
today["yday"] = yday
hour = tm[3] # struct_time.tm_hour is index 3
if is_peak_hour(hour):
today["peak_wh"] += e_wh
lifetime["peak_wh"] += e_wh
else:
today["off_peak_wh"] += e_wh
lifetime["off_peak_wh"] += e_wh
while True:
time.sleep(60)
rb_write_u8(i2c, RB_ADDR, 0x01, 0x27)
t_now_ms = time.ticks_ms()
time.sleep_ms(50)
if (rb_read_u8(i2c, RB_ADDR, 0x07) & 0x01) == 0:
t_prev_ms = time.ticks_ms()
continue
avg_p = rb_read_float_le(i2c, RB_ADDR, 0xDC)
dt_s = time.ticks_diff(t_now_ms, t_prev_ms) / 1000.0
e_wh = avg_p * dt_s / 3600.0
t_prev_ms = t_now_ms
tm = local_time()
accumulate(e_wh, tm)
peak = is_peak_hour(tm[3])
payload = json.dumps({
"ts": iso_now(),
"tariff": "peak" if peak else "off_peak",
"avg_p": round(avg_p, 1),
"period_wh": round(e_wh, 4),
"today_peak_wh": round(today["peak_wh"], 3),
"today_off_peak_wh": round(today["off_peak_wh"], 3),
"life_peak_wh": round(lifetime["peak_wh"], 3),
"life_off_peak_wh": round(lifetime["off_peak_wh"], 3),
})
mqtt.publish(b"rbamp/tou/state", payload.encode())
print(payload)
Notes:
- Il modulo
timedi MicroPython è basato su UTC nella maggior parte dei port — converta contime.gmtime(time.time() + offset_seconds). Per la gestione completa dell'ora legale, una piccola tabella TZ o la libreriautimezonepossono sostituireTZ_OFFSET_HOURS. - Errore di confine: un periodo di 60 s che attraversa le 22:00 viene attribuito interamente alla fascia fuori punta (marca temporale all'istante dell'acquisizione). Al massimo ~30 s di errata attribuzione al giorno — trascurabile per la contabilità di una tariffa residenziale.
- Per la misura bidirezionale STD, chiamare
accumulate()due volte — una per il lato consumo e una per il lato esportazione — e pubblicare entrambi gli insiemi di totali di punta / fuori punta.
: usi adafruit_ntp.NTP(socketpool, server="pool.ntp.org", tz_offset=2) + rtc.RTC().datetime = ntp.datetime per impostare l'orologio di sistema, poi lo legga via time.localtime(). La logica delle fasce è identica.
Confronto degli esempi
| # | Complessità | Uscita | MQTT | DRDY | Più moduli | Bidirezionale | Persistenza | Caso d'uso |
|---|---|---|---|---|---|---|---|---|
| 1 | minimo | REPL | — | — | — | — | — | test di base (smoke test) |
| 2 | basso | OLED | — | — | — | — | RAM | contatore in custodia |
| 3 | basso | REPL | — | — | sì (3) | — | — | monitoraggio domestico |
| 4 | medio | — | sì | — | — | — | RAM | per singolo apparecchio in HA |
| 5 | medio | REPL | — | sì | — | sì (master) | RAM | casa solare su livello BASIC |
| 6 | alta | — | sì | — | sì (3) | sì | RAM | bilancio domestico completo |
| 7 | medio | REPL + SD | — | sì | — | — | Scheda SD | rilevamento di eventi |
| 8 | medio | — | sì (+disco) | — | — | facoltativo | RAM + MQTT | HA Auto-discovery |
| 9 | medio | — | sì | — | — | — | Memoria RTC | registratore fuori rete / per esterni |
| 10 | medio | REPL | sì | — | — | facoltativo | RAM + MQTT | TOU punta / fuori punta con NTP |
Buone pratiche
- Controllare sempre
DATA_VALID(bit 0 del registro0xCE) dopo l'avvio ePERIOD_VALID(bit 0 di0x07) dopo ogniCMD_LATCH_PERIOD. - Attendere almeno 50 ms dopo un'acquisizione prima di leggerla.
- Per i Wh il clock master fa fede — non usi
PERIOD_LATCH_MS(0xEC) per il calcolo dell'energia. rb_broadcast_latch(i2c, tick)via general call garantisce una sincronizzazione precisa per configurazioni multi-modulo. La ricezione GC è opt-in per modulo (FLEET_CONFIG.bit0, predefinito OFF). In caso di NACK ripiegare sull'acquisizione sequenziale per modulo conCMD_LATCH_PERIOD.- La persistenza lato master è obbligatoria per la contabilità nel lungo periodo — rbAmp non memorizza internamente i Wh. Usi la memoria RTC (Esempio 9), la scheda SD (Esempio 7) oppure i payload retained su MQTT (Esempio 6).
- Gli handler IRQ di MicroPython devono essere minimi (impostare un flag, nessuna operazione I²C). Svolga tutto il lavoro I²C nel ciclo principale.
- Per CircuitPython, preferisca
countio.Counterokeypad.Keysper gli eventi di fronte invece di IRQ definite dall'utente.
Cosa segue
Dopo aver svolto questi dieci esempi:
- Per il pacchetto di alto livello
rbamp, consulti la tabella delle librerie client nel README. - Per l'integrazione ESPHome (YAML dichiarativo), vedere
tools/esphome-rbamp/docs/en/. - Per un ambiente SBC più ricco (Raspberry Pi, CPython completo), consulti la tabella delle librerie client nel README.
- Driver Tasmota Berry — rinviato (nessuna libreria distribuita).
- La specifica formale dei registri I²C usata qui si trova in api-reference.md.