14 · Ejemplos de STM32 HAL
Este capítulo es el equivalente en STM32 de arduino-examples.md, micropython-examples.md y esp-idf-examples.md: los mismos diez escenarios, portados a STM32 HAL (C generado por CubeMX) con FreeRTOS / CMSIS-OS2 opcional.
Estos ejemplos hablan con rbAmp directamente mediante la API de registros I²C sin procesar. Están pensados para firmware embebido de producción en STM32: control directo de la HAL, huella de RAM/flash predecible e integración con LwIP, FATFS, FreeRTOS y la generación de HAL de CubeMX.
Configure el periférico I²C en CubeMX a 50 kHz (recomendado; vea el capítulo 11 §2.2) y envuelva las lecturas de registros en un reintento corto.
Familias soportadas y cadena de herramientas
| Familia | Validado | Periférico I²C | Notas |
|---|---|---|---|
| Familia STM32F1 | ✓ | I2C1, I2C2 | Destino habitual para bricolaje |
| STM32F4 (Nucleo-F411, Discovery) | ✓ | I2C1..3 | Reloj alto, mucha RAM |
| STM32L4 / L4+ | ✓ | I2C1..4 | Bajo consumo, registros de respaldo RTC, STOP / STANDBY |
| STM32G0 / G4 | ✓ | I2C1..3 | Periféricos modernos |
| STM32H7 (Nucleo-H743) | ✓ | I2C1..4 | PHY Ethernet integrado → MQTT directamente mediante LwIP |
Cadena de herramientas: CubeMX 6.x + CubeIDE o un proyecto con Makefile (arm-none-eabi-gcc). Los ejemplos suponen una versión de la HAL que coincida con su proyecto generado por CubeMX. La nueva firma de I²C de la HAL (HAL_I2C_Mem_Read/Write) está soportada en todas las familias modernas.
Nota sobre la red
La mayoría de chips STM32 no tienen Wi-Fi integrado. Los ejemplos que dependen de MQTT (4, 6, 8, 9) asumen una de las siguientes rutas de red:
- Ethernet: placas STM32F4 / F7 / H7 con PHY integrado (LAN8742, DP83848) que ejecutan LwIP + una pequeña biblioteca MQTT (Paho Embedded C, MQTT-C o una bifurcación compatible con HAL). Es la vía más sencilla.
- Ethernet SPI W5500: para STM32F1 / L4 / G4 (sin MAC integrada). Usa la ioLibrary de WIZnet.
- ESP32-AT por UART: un módulo ESP-AT actúa como puente Wi-Fi. Envíe comandos AT desde el bucle principal del STM32.
Los ejemplos siguientes muestran la lógica de rbAmp con todo detalle; la puesta en marcha de la red se abstrae tras dos funciones stub que usted implementa en su proyecto:
extern HAL_StatusTypeDef Net_Init(void); // bring up the chosen stack
extern HAL_StatusTypeDef Net_MqttPublish(const char *topic,
const uint8_t *payload, uint32_t len,
uint8_t qos, uint8_t retain);
Las implementaciones de referencia de cada ruta de red quedan fuera del alcance de este capítulo; elija la que se ajuste a su hardware y sustituya los stubs.
Estructura del proyecto
Estructura de proyecto generada por CubeMX:
example_NN/
├── example_NN.ioc ← CubeMX project (pins, peripherals, clock)
├── Makefile ← (or *.eww / *.uvprojx for IAR / STM32CubeIDE)
├── Core/
│ ├── Inc/main.h
│ ├── Inc/rbamp_io.h ← common helpers
│ ├── Src/main.c ← USER CODE inside CubeMX markers
│ ├── Src/rbamp_io.c
│ └── Src/stm32xxxx_it.c ← EXTI handlers (CubeMX-generated)
├── Drivers/
│ └── STM32xxxx_HAL_Driver/ ← HAL sources
└── Middlewares/ ← FreeRTOS, LwIP, FATFS (optional)
Configuración de pines de CubeMX usada en todos los ejemplos salvo indicación contraria:
- I2C1: SCL = PB6, SDA = PB7 (valores por defecto típicos de STM32F1 / Nucleo-F411)
- UART1: TX = PA9, RX = PA10, para depuración con
printf - EXTI: PA0 = DRDY (flanco de bajada, pull-up)
- Velocidad de I²C: 100 kHz
Índice de ejemplos
| # | Título | Dificultad | Salida | MQTT | DRDY | Multimódulo | Bidireccional | Caso de uso |
|---|---|---|---|---|---|---|---|---|
| 1 | Lectura rápida | mínimo | printf por UART | — | — | — | — | Prueba de humo |
| 2 | Medidor de energía de 60 segundos en OLED | bajo | SSD1306 | — | — | — | — | Contador Wh encapsulado |
| 3 | Monitor multimódulo | bajo | printf por UART | — | — | sí (3) | — | Monitorización de toda la vivienda |
| 4 | Medidor de energía por aparato (UI3) | medio | — | sí | — | — | — | Submedición en HA |
| 5 | Bidireccional en el maestro con un módulo BASIC | medio | printf por UART | — | sí | — | sí (maestro) | Vivienda solar en nivel BASIC |
| 6 | Balance energético de la vivienda | alta | — | sí | — | sí (3) | sí | Balance energético de la vivienda |
| 7 | Detección de eventos de corriente | medio | UART + SD | — | sí | — | — | Registro de eventos de electrodomésticos |
| 8 | Publicador MQTT con auto-descubrimiento de HA | medio | — | sí (+disco) | — | — | opcional | Integración de HA lista para usar |
| 9 | Registrador alimentado por batería con modo STANDBY | medio | — | sí | — | — | — | Medidor exterior / autónomo |
| 10 | Tarifa por franjas horarias (TOU) con hora de pared SNTP | medio | printf por UART | sí | — | — | opcional | Medición por tarifa punta / valle |
Auxiliares comunes (rbamp_io.h / rbamp_io.c)
Coloque estos archivos en Core/Inc y Core/Src de su proyecto de CubeMX. Para ahorrar espacio, la línea #include "rbamp_io.h" se omite en cada ejemplo siguiente.
rbamp_io.h
/**
* @file rbamp_io.h
* @brief Raw I2C helpers for the rbAmp slave (STM32 HAL).
*/
#ifndef RBAMP_IO_H
#define RBAMP_IO_H
#include
#include
#include "main.h" /* CubeMX-generated, brings the HAL header */
#ifdef __cplusplus
extern "C" {
#endif
/* I2C transaction timeout in milliseconds (HAL_GetTick units). */
#define RBAMP_I2C_TIMEOUT_MS 50U
/**
* @brief Bind the helpers to a HAL I2C handle.
* @details Stores the pointer internally; call once at startup. The handle
* must have been initialised by HAL_I2C_Init() (typically by CubeMX).
*/
void RbAmpIO_Bind(I2C_HandleTypeDef *hi2c);
/**
* @brief Read one byte from a register of an rbAmp slave.
* @param addr 7-bit slave address (e.g. 0x50).
* @param reg Register address inside the slave.
* @param out Output byte.
* @return HAL_OK on success.
*/
HAL_StatusTypeDef RbAmpIO_ReadU8(uint8_t addr, uint8_t reg, uint8_t *out);
/**
* @brief Read a little-endian float32 from four consecutive registers.
* @details Reads four consecutive bytes. rbAmp supports READ auto-increment
* (a single burst-read is valid for atomicity). The per-byte form
* is shown for clarity. See chapter 11 for asymmetry rules.
*/
HAL_StatusTypeDef RbAmpIO_ReadFloatLE(uint8_t addr, uint8_t reg, float *out);
/**
* @brief Read a little-endian uint32 from four consecutive registers.
*/
HAL_StatusTypeDef RbAmpIO_ReadU32LE(uint8_t addr, uint8_t reg, uint32_t *out);
/**
* @brief Write a single byte to a register.
*/
HAL_StatusTypeDef RbAmpIO_WriteU8(uint8_t addr, uint8_t reg, uint8_t val);
/**
* @brief Broadcast CMD_LATCH_PERIOD to every rbAmp with GC reception
* enabled (FLEET_CONFIG.bit0 = 1; opt-in, default OFF).
* @details Canonical 5-byte general-call frame: A5 27 group tick_lo tick_hi.
* Slaves reject any first byte != 0xA5. See chapter 11 §6.3.2.
* @param tick16 Caller's 16-bit window counter (mirrored at GC_TICK 0x59).
* @param group GROUP_ID filter (0 = all-call).
* @return HAL_OK on ACK; HAL_ERROR on NACK — fall back to per-module snapshot.
*/
HAL_StatusTypeDef RbAmpIO_BroadcastLatch(uint16_t tick16, uint8_t group);
/**
* @brief Probe whether a slave responds at the given address (1-byte read).
* @return true if the slave acks, false otherwise.
*/
bool RbAmpIO_Probe(uint8_t addr);
/**
* @brief Block until DATA_VALID bit 0 of register 0xCE reads 1, or timeout.
* @return HAL_OK if ready in time, HAL_TIMEOUT otherwise.
*/
HAL_StatusTypeDef RbAmpIO_WaitReady(uint8_t addr, uint32_t timeout_ms);
/* ===== rbAmp register addresses (subset used in examples) ===== */
#define RB_REG_STATUS 0x00U
#define RB_REG_COMMAND 0x01U
#define RB_REG_VERSION 0x03U
#define RB_REG_AC_FREQ 0x20U
#define RB_REG_PERIOD_VALID 0x07U
#define RB_REG_U_RMS 0x86U
#define RB_REG_I0_RMS 0x8EU
#define RB_REG_I1_RMS 0x92U
#define RB_REG_I2_RMS 0x96U
#define RB_REG_P0_REAL 0xA6U
#define RB_REG_PF0 0xB2U
#define RB_REG_Q0 0xD0U
#define RB_REG_DATA_VALID 0xCEU
#define RB_REG_PERIOD_AVG_P0 0xDCU
#define RB_REG_PERIOD_AVG_P1 0xC2U
#define RB_REG_PERIOD_AVG_P2 0xC6U
#define RB_REG_PERIOD_MAX_P 0xE0U
#define RB_REG_PERIOD_LATCH_MS 0xECU
/* ===== Commands ===== */
#define RB_CMD_RESET 0x01U
#define RB_CMD_LATCH_PERIOD 0x27U
#ifdef __cplusplus
}
#endif
#endif /* RBAMP_IO_H */
rbamp_io.c
#include "rbamp_io.h"
#include
/* HAL I2C uses the 8-bit address format: left-shift the 7-bit address. */
#define ADDR8(addr7) ((uint16_t)((addr7) << 1))
static I2C_HandleTypeDef *s_hi2c = NULL;
void RbAmpIO_Bind(I2C_HandleTypeDef *hi2c) {
s_hi2c = hi2c;
}
HAL_StatusTypeDef RbAmpIO_ReadU8(uint8_t addr, uint8_t reg, uint8_t *out) {
return HAL_I2C_Mem_Read(s_hi2c, ADDR8(addr), reg,
I2C_MEMADD_SIZE_8BIT, out, 1,
RBAMP_I2C_TIMEOUT_MS);
}
HAL_StatusTypeDef RbAmpIO_ReadFloatLE(uint8_t addr, uint8_t reg, float *out) {
uint8_t buf[4];
for (int i = 0; i < 4; i++) {
HAL_StatusTypeDef st = HAL_I2C_Mem_Read(s_hi2c, ADDR8(addr), reg + i,
I2C_MEMADD_SIZE_8BIT,
&buf[i], 1,
RBAMP_I2C_TIMEOUT_MS);
if (st != HAL_OK) return st;
}
memcpy(out, buf, sizeof(float)); /* STM32 is little-endian — host order matches */
return HAL_OK;
}
HAL_StatusTypeDef RbAmpIO_ReadU32LE(uint8_t addr, uint8_t reg, uint32_t *out) {
uint8_t buf[4];
for (int i = 0; i < 4; i++) {
HAL_StatusTypeDef st = HAL_I2C_Mem_Read(s_hi2c, ADDR8(addr), reg + i,
I2C_MEMADD_SIZE_8BIT,
&buf[i], 1,
RBAMP_I2C_TIMEOUT_MS);
if (st != HAL_OK) return st;
}
*out = (uint32_t)buf[0] | (uint32_t)buf[1] << 8
| (uint32_t)buf[2] << 16 | (uint32_t)buf[3] << 24;
return HAL_OK;
}
HAL_StatusTypeDef RbAmpIO_WriteU8(uint8_t addr, uint8_t reg, uint8_t val) {
return HAL_I2C_Mem_Write(s_hi2c, ADDR8(addr), reg,
I2C_MEMADD_SIZE_8BIT, &val, 1,
RBAMP_I2C_TIMEOUT_MS);
}
HAL_StatusTypeDef RbAmpIO_BroadcastLatch(uint16_t tick16, uint8_t group) {
/* Canonical 5-byte general-call frame: A5 27 group tick_lo tick_hi.
* HAL_I2C_Master_Transmit accepts the 8-bit address; 0x00 << 1 = 0x00. */
uint8_t tx[5] = {
0xA5, /* frame magic */
RB_CMD_LATCH_PERIOD, /* opcode 0x27 */
group, /* group_id (0 = all-call) */
(uint8_t)(tick16 & 0xFF),
(uint8_t)((tick16 >> 8) & 0xFF),
};
return HAL_I2C_Master_Transmit(s_hi2c, ADDR8(0x00), tx, sizeof tx,
RBAMP_I2C_TIMEOUT_MS);
}
bool RbAmpIO_Probe(uint8_t addr) {
/* HAL_I2C_IsDeviceReady performs an address-only NACK probe. */
return HAL_I2C_IsDeviceReady(s_hi2c, ADDR8(addr), /*trials=*/2,
RBAMP_I2C_TIMEOUT_MS) == HAL_OK;
}
HAL_StatusTypeDef RbAmpIO_WaitReady(uint8_t addr, uint32_t timeout_ms) {
uint32_t deadline = HAL_GetTick() + timeout_ms;
while (HAL_GetTick() < deadline) {
uint8_t v = 0;
if (RbAmpIO_ReadU8(addr, RB_REG_DATA_VALID, &v) == HAL_OK && (v & 0x01U)) {
return HAL_OK;
}
HAL_Delay(50);
}
return HAL_TIMEOUT;
}
Redirección de printf
Todos los ejemplos llaman a printf() por UART. En su main.c añada el auxiliar canónico de redirección (funciona con newlib-nano):
extern UART_HandleTypeDef huart1;
/**
* @brief Standard newlib `_write` retarget — sends bytes to UART1.
* @details A bounded timeout (100 ms) prevents a stuck/unplugged UART from
* starving the IWDG (which `HAL_MAX_DELAY` would do). On timeout the
* chunk is dropped — preferable to a reset.
*/
int _write(int file, char *ptr, int len) {
if (HAL_UART_Transmit(&huart1, (uint8_t*)ptr, len, 100) != HAL_OK) {
return -1; /* drop chunk, do NOT block */
}
return len;
}
En proyectos de Cube IDE con semihosting desactivado y newlib-nano seleccionado, printf("%.1f", ...) requiere -u _printf_float en los flags del enlazador.
Ejemplo 1: lectura rápida (mínimo)
Objetivo: imprimir U, I, P, PF por UART una vez por segundo. Hardware: cualquier STM32 + un rbAmp UI1 + USB-UART para la consola del host.
En CubeMX:
- active
I2C1(Standard, 100 kHz) en PB6/PB7 - active
USART1(115200 8N1) en PA9/PA10 - resto por defecto
Código de usuario de main.c: los bloques /* USER CODE BEGIN 2 */ y /* USER CODE BEGIN WHILE */ que se muestran más abajo van dentro de la función main() generada por CubeMX, entre sus llamadas de inicialización y el bucle while(1). No los pegue a nivel de archivo: deben estar dentro de main().
Forma de referencia (el int main(void) { … } que lo rodea lo genera CubeMX y se muestra aquí solo como contexto):
/* USER CODE BEGIN Includes */
#include
#include "rbamp_io.h"
/* USER CODE END Includes */
extern I2C_HandleTypeDef hi2c1;
extern UART_HandleTypeDef huart1;
int _write(int file, char *ptr, int len) {
if (HAL_UART_Transmit(&huart1, (uint8_t*)ptr, len, 100) != HAL_OK) return -1;
return len;
}
#define RB_ADDR 0x50U
int main(void) /* generated by CubeMX */
{
HAL_Init(); /* generated by CubeMX */
SystemClock_Config(); /* generated by CubeMX */
MX_GPIO_Init(); /* generated */
MX_I2C1_Init(); /* generated */
MX_USART1_UART_Init(); /* generated */
/* USER CODE BEGIN 2 */
RbAmpIO_Bind(&hi2c1);
/* Wait until the first RT window has been computed. */
if (RbAmpIO_WaitReady(RB_ADDR, 2000) != HAL_OK) {
printf("ERROR: rbAmp not ready\r\n");
Error_Handler();
}
uint8_t ver = 0;
RbAmpIO_ReadU8(RB_ADDR, RB_REG_VERSION, &ver);
printf("rbAmp version: 0x%02X\r\n", ver);
/* USER CODE END 2 */
/* USER CODE BEGIN WHILE */
while (1) {
float u, i_, p, pf;
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_U_RMS, &u );
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_I0_RMS, &i_);
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_P0_REAL, &p );
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_PF0, &pf);
printf("U=%.1fV I=%.3fA P=%+.1fW PF=%+.3f\r\n", u, i_, p, pf);
HAL_Delay(1000);
/* USER CODE END WHILE */
}
}
Convención de este capítulo: los ejemplos 2–10 omiten el main(void) que los rodea y las llamadas de inicialización de CubeMX por brevedad, y muestran solo los bloques /* USER CODE BEGIN 2 */ / /* USER CODE BEGIN WHILE */. Todo fragmento que empiece por RbAmpIO_Bind(&hi2c1); es el contenido de main(), no código a nivel de archivo.
Salida esperada en la consola:
rbAmp version: 0x04
U=230.1V I=0.262A P=+60.2W PF=+0.998
U=229.9V I=0.262A P=+60.1W PF=+0.998
...
Ejemplo 2: medidor de energía de 60 segundos en OLED
Objetivo: contador de Wh actualizado una vez por minuto, mostrado en un SSD1306 de 128×64 que comparte el bus I²C del rbAmp. Hardware: STM32 + rbAmp + SSD1306 (0x3C) en el mismo bus. Contabilidad: unidireccional (nivel BASIC). Biblioteca: cualquier controlador SSD1306 para STM32-HAL (p. ej. afiskon/stm32-ssd1306).
#include
#include
#include "rbamp_io.h"
#include "ssd1306.h" /* your driver of choice */
#include "ssd1306_fonts.h"
extern I2C_HandleTypeDef hi2c1;
#define RB_ADDR 0x50U
/* USER CODE BEGIN 2 */
RbAmpIO_Bind(&hi2c1);
ssd1306_Init();
RbAmpIO_WaitReady(RB_ADDR, 2000);
/* Primer snapshot — discard the snapshot it produces. */
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
uint32_t t_prev_ms = HAL_GetTick();
double total_wh = 0.0;
/* USER CODE END 2 */
while (1) {
HAL_Delay(60UL * 1000UL);
/* 1) Final snapshot — closes the period [t_prev_ms .. now]. */
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
uint32_t t_now_ms = HAL_GetTick();
HAL_Delay(50); /* let firmware finalise snapshot */
/* 2) Check PERIOD_VALID. */
uint8_t valid = 0;
RbAmpIO_ReadU8(RB_ADDR, RB_REG_PERIOD_VALID, &valid);
if ((valid & 0x01U) == 0) {
printf("WARN: stale snapshot\r\n");
t_prev_ms = HAL_GetTick();
continue;
}
/* 3) Read time-averaged power, channel 0. */
float avg_p = 0.0f;
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_PERIOD_AVG_P0, &avg_p);
/* 4) Energy uses the MASTER clock. */
float dt_s = (float)(t_now_ms - t_prev_ms) / 1000.0f;
double e_wh = (double)avg_p * dt_s / 3600.0;
total_wh += e_wh;
t_prev_ms = t_now_ms;
/* 5) Render on OLED. */
char line[24];
ssd1306_Fill(Black);
snprintf(line, sizeof(line), "P: %6.1f W", avg_p);
ssd1306_SetCursor(0, 0); ssd1306_WriteString(line, Font_7x10, White);
snprintf(line, sizeof(line), "dt: %6.1f s", dt_s);
ssd1306_SetCursor(0, 16); ssd1306_WriteString(line, Font_7x10, White);
snprintf(line, sizeof(line), "%.2f Wh", total_wh);
ssd1306_SetCursor(0, 32); ssd1306_WriteString(line, Font_11x18, White);
ssd1306_UpdateScreen();
printf("avg_P=%.1f E_period=%.3f total=%.3f\r\n", avg_p, e_wh, total_wh);
}
El controlador SSD1306 y rbAmp comparten hi2c1: nunca reinicie el periférico, use el mismo manejador para ambos.
Ejemplo 3: monitor multimódulo
Objetivo: sondear tres módulos (alimentación principal, calentador de agua, AC) e imprimir el total. Hardware: STM32 + 3 × rbAmp UI1 en 0x50, 0x51 y 0x52.
#include
#include "rbamp_io.h"
extern I2C_HandleTypeDef hi2c1;
typedef struct {
uint8_t addr;
const char *label;
} module_t;
static const module_t modules[] = {
{ 0x50, "Mains " },
{ 0x51, "Boiler" },
{ 0x52, "AC " },
};
#define N_MODULES (sizeof(modules) / sizeof(modules[0]))
/* USER CODE BEGIN 2 */
RbAmpIO_Bind(&hi2c1);
/* Bus probe — halt if any module is missing. */
for (size_t i = 0; i < N_MODULES; i++) {
if (!RbAmpIO_Probe(modules[i].addr)) {
printf("ERROR: %s at 0x%02X not found\r\n",
modules[i].label, modules[i].addr);
Error_Handler();
}
}
printf("All modules OK\r\n");
/* USER CODE END 2 */
while (1) {
float total_p = 0.0f;
printf("---\r\n");
/* Round-robin read. */
for (size_t i = 0; i < N_MODULES; i++) {
float u = 0.0f, p = 0.0f;
RbAmpIO_ReadFloatLE(modules[i].addr, RB_REG_U_RMS, &u);
RbAmpIO_ReadFloatLE(modules[i].addr, RB_REG_P0_REAL, &p);
printf("[%s] U=%.1f P=%+.1f W\r\n", modules[i].label, u, p);
total_p += p;
}
printf("TOTAL: %.1f W\r\n", total_p);
HAL_Delay(2000);
}
HAL_I2C_IsDeviceReady() (dentro de RbAmpIO_Probe()) es el equivalente en STM32 del sondeo Wire.endTransmission() de Arduino.
Ejemplo 4: medidor de energía por aparato (UI3)
Objetivo: un módulo UI3 con tres pinzas de corriente CT en tres cargas distintas de la misma fase; contadores Wh independientes publicados por MQTT cada minuto. Hardware: STM32 + 1 × rbAmp UI3 + PHY Ethernet (o puente W5500 / ESP32-AT). Stubs de red: Net_Init() y Net_MqttPublish() (vea la introducción del capítulo).
#include
#include "rbamp_io.h"
extern I2C_HandleTypeDef hi2c1;
extern HAL_StatusTypeDef Net_Init(void);
extern HAL_StatusTypeDef Net_MqttPublish(const char *topic,
const uint8_t *payload, uint32_t len,
uint8_t qos, uint8_t retain);
#define RB_ADDR 0x50U
static const char *CH_NAMES[3] = { "main", "heatpump", "lights" };
/**
* @brief Publish one channel's data to MQTT.
*/
static void mqtt_publish_channel(const char *ch_name, float avg_p, double e_wh) {
char topic[64], payload[64];
int t = snprintf(topic, sizeof(topic), "rbamp/%s/state", ch_name);
int n = snprintf(payload, sizeof(payload),
"{\"power\":%.1f,\"energy\":%.4f}", avg_p, e_wh);
(void)t;
Net_MqttPublish(topic, (const uint8_t*)payload, (uint32_t)n, /*qos*/ 0, /*retain*/ 0);
}
/* USER CODE BEGIN 2 */
RbAmpIO_Bind(&hi2c1);
Net_Init();
RbAmpIO_WaitReady(RB_ADDR, 2000);
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD); /* primer */
uint32_t t_prev_ms = HAL_GetTick();
double total_wh[3] = { 0.0, 0.0, 0.0 };
/* USER CODE END 2 */
while (1) {
HAL_Delay(60UL * 1000UL);
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
uint32_t t_now_ms = HAL_GetTick();
HAL_Delay(50);
uint8_t valid = 0;
RbAmpIO_ReadU8(RB_ADDR, RB_REG_PERIOD_VALID, &valid);
if ((valid & 0x01U) == 0) {
t_prev_ms = HAL_GetTick();
continue;
}
/* PERIOD_AVG_P_W per channel: I0 at 0xDC, I1 at 0xC2, I2 at 0xC6. */
float avg_p[3];
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_PERIOD_AVG_P0, &avg_p[0]);
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_PERIOD_AVG_P1, &avg_p[1]);
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_PERIOD_AVG_P2, &avg_p[2]);
float dt_s = (float)(t_now_ms - t_prev_ms) / 1000.0f;
t_prev_ms = t_now_ms;
for (int ch = 0; ch < 3; ch++) {
double e = (double)avg_p[ch] * dt_s / 3600.0;
total_wh[ch] += e;
printf("[%s] avg_P=%+.1f W E_total=%.3f Wh\r\n",
CH_NAMES[ch], avg_p[ch], total_wh[ch]);
mqtt_publish_channel(CH_NAMES[ch], avg_p[ch], total_wh[ch]);
}
}
Ejemplo 5: bidireccional en el maestro con un módulo BASIC
Objetivo: implementar contabilidad bidireccional en el maestro mientras el módulo tiene firmware BASIC. El flanco de bajada de DRDY dispara una interrupción EXTI; la ISR activa un indicador y el bucle principal lee RT P_real y separa consumo y exportación. Hardware: STM32 + rbAmp UI1; DRDY conectado a PA0 (configurado como GPIO_EXTI0 de bajada, pull-up en CubeMX).
En CubeMX:
PA0→ modoGPIO_EXTI0, pull-up, disparoFalling edge- NVIC: habilite
EXTI line 0 interrupt
stm32xxxx_it.c: generado por CubeMX, solo el bloque de código de usuario:
extern volatile uint8_t g_data_ready; /* defined in main.c */
void EXTI0_IRQHandler(void) {
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0);
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
if (GPIO_Pin == GPIO_PIN_0) {
g_data_ready = 1; /* tiny ISR — set a flag and return */
}
}
Código de usuario en main.c:
#include
#include
#include "rbamp_io.h"
extern I2C_HandleTypeDef hi2c1;
volatile uint8_t g_data_ready = 0;
#define RB_ADDR 0x50U
/* USER CODE BEGIN 2 */
RbAmpIO_Bind(&hi2c1);
RbAmpIO_WaitReady(RB_ADDR, 2000);
double e_consumed_wh = 0.0;
double e_exported_wh = 0.0;
uint32_t t_last_sample_ms = HAL_GetTick();
uint32_t t_last_print_ms = t_last_sample_ms;
printf("Bidirectional accumulator started\r\n");
/* USER CODE END 2 */
while (1) {
if (!g_data_ready) {
continue; /* main loop also free to do other work */
}
__disable_irq();
g_data_ready = 0; /* clear flag atomically */
__enable_irq();
uint32_t t_now = HAL_GetTick();
/* Signed instantaneous P_real: + consume, − export. */
float p = 0.0f;
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_P0_REAL, &p);
float dt_s = (float)(t_now - t_last_sample_ms) / 1000.0f;
t_last_sample_ms = t_now;
if (p > 0.0f) {
e_consumed_wh += (double)p * dt_s / 3600.0;
} else {
e_exported_wh += (double)(-p) * dt_s / 3600.0;
}
/* Summary print every 5 s — not on every RT window. */
if (t_now - t_last_print_ms >= 5000) {
t_last_print_ms = t_now;
printf("P=%+8.1fW consumed=%.4f Wh exported=%.4f Wh net=%+.4f Wh\r\n",
p, e_consumed_wh, e_exported_wh,
e_consumed_wh - e_exported_wh);
}
}
Notes:
- La ISR de EXTI es mínima: solo asigna
g_data_ready. Todo el trabajo de I²C se ejecuta en el bucle principal. - El calificador
volatilees esencial: el compilador debe recargarg_data_readydesde la RAM en cada iteración del bucle. - Una ventana corta de
__disable_irq() / __enable_irq()alrededor del borrado evita una carrera con un disparo EXTI casi simultáneo.
Ejemplo 6: balance energético del hogar
Objetivo: panel de balance energético completo. Tres módulos:
- rbAmp n.º 1 en la alimentación principal (STD: bidireccional)
- rbAmp n.º 2 en la salida del inversor solar (BASIC válido)
- rbAmp n.º 3, UI3, en tres cargas grandes (calefacción, AC, VE)
El maestro usa RbAmpIO_BroadcastLatch() para instantáneas síncronas y publica un saldo retenido por MQTT cada minuto.
#include
#include
#include "rbamp_io.h"
extern I2C_HandleTypeDef hi2c1;
extern HAL_StatusTypeDef Net_Init(void);
extern HAL_StatusTypeDef Net_MqttPublish(const char *topic,
const uint8_t *payload, uint32_t len,
uint8_t qos, uint8_t retain);
#define ADDR_MAINS 0x50U /* bidirectional (STD) */
#define ADDR_SOLAR 0x51U /* generation only */
#define ADDR_LOADS 0x52U /* UI3 */
/* PERIOD_AVG_P_NEG address for the mains module — see the SKU datasheet
* of the STD product. Set to 0xFF for BASIC modules. */
#define REG_PERIOD_AVG_P_NEG_MAINS 0xFFU
typedef struct {
double mains_in_wh;
double mains_out_wh;
double solar_total_wh;
double loads_wh[3];
} totals_t;
/* USER CODE BEGIN 2 */
RbAmpIO_Bind(&hi2c1);
Net_Init();
RbAmpIO_WaitReady(ADDR_MAINS, 2000);
RbAmpIO_WaitReady(ADDR_SOLAR, 2000);
RbAmpIO_WaitReady(ADDR_LOADS, 2000);
static uint16_t gc_tick = 0;
if (RbAmpIO_BroadcastLatch(gc_tick++, 0) != HAL_OK) {
/* GC NACK — fall back to per-module sequential snapshot. */
RbAmpIO_WriteU8(ADDR_MAINS, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
RbAmpIO_WriteU8(ADDR_SOLAR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
RbAmpIO_WriteU8(ADDR_LOADS, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
}
uint32_t t_prev_ms = HAL_GetTick();
totals_t totals = {0};
printf("Home balance started\r\n");
/* USER CODE END 2 */
while (1) {
HAL_Delay(60UL * 1000UL);
/* Synchronous snapshot — all modules snapshot at the same instant. */
if (RbAmpIO_BroadcastLatch(gc_tick++, 0) != HAL_OK) {
/* GC NACK — fall back to per-module snapshot (skew ~1 ms/module). */
RbAmpIO_WriteU8(ADDR_MAINS, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
RbAmpIO_WriteU8(ADDR_SOLAR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
RbAmpIO_WriteU8(ADDR_LOADS, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
}
uint32_t t_now_ms = HAL_GetTick();
HAL_Delay(50);
float dt_s = (float)(t_now_ms - t_prev_ms) / 1000.0f;
t_prev_ms = t_now_ms;
/* ----- MAINS (bidirectional, STD) ----- */
uint8_t valid;
if (RbAmpIO_ReadU8(ADDR_MAINS, RB_REG_PERIOD_VALID, &valid) == HAL_OK
&& (valid & 0x01U)) {
float p_consume = 0.0f, p_export = 0.0f;
RbAmpIO_ReadFloatLE(ADDR_MAINS, RB_REG_PERIOD_AVG_P0, &p_consume);
if (REG_PERIOD_AVG_P_NEG_MAINS != 0xFFU) {
RbAmpIO_ReadFloatLE(ADDR_MAINS, REG_PERIOD_AVG_P_NEG_MAINS, &p_export);
}
totals.mains_in_wh += (double)p_consume * dt_s / 3600.0;
totals.mains_out_wh += (double)p_export * dt_s / 3600.0;
}
/* ----- SOLAR (generation only) ----- */
if (RbAmpIO_ReadU8(ADDR_SOLAR, RB_REG_PERIOD_VALID, &valid) == HAL_OK
&& (valid & 0x01U)) {
float p = 0.0f;
RbAmpIO_ReadFloatLE(ADDR_SOLAR, RB_REG_PERIOD_AVG_P0, &p);
totals.solar_total_wh += (double)p * dt_s / 3600.0;
}
/* ----- LOADS (UI3, three channels) ----- */
if (RbAmpIO_ReadU8(ADDR_LOADS, RB_REG_PERIOD_VALID, &valid) == HAL_OK
&& (valid & 0x01U)) {
float p[3] = {0};
RbAmpIO_ReadFloatLE(ADDR_LOADS, RB_REG_PERIOD_AVG_P0, &p[0]); /* I0 */
RbAmpIO_ReadFloatLE(ADDR_LOADS, RB_REG_PERIOD_AVG_P1, &p[1]); /* I1 */
RbAmpIO_ReadFloatLE(ADDR_LOADS, RB_REG_PERIOD_AVG_P2, &p[2]); /* I2 */
for (int i = 0; i < 3; i++) {
totals.loads_wh[i] += (double)p[i] * dt_s / 3600.0;
}
}
double total_consumed = totals.mains_in_wh + totals.solar_total_wh
- totals.mains_out_wh;
double solar_self_used = totals.solar_total_wh - totals.mains_out_wh;
if (solar_self_used < 0.0) solar_self_used = 0.0;
printf("MAINS in=%.2f out=%.2f\r\n", totals.mains_in_wh, totals.mains_out_wh);
printf("SOLAR gen=%.2f self-used=%.2f exported=%.2f\r\n",
totals.solar_total_wh, solar_self_used, totals.mains_out_wh);
printf("LOADS HP=%.2f AC=%.2f EV=%.2f\r\n",
totals.loads_wh[0], totals.loads_wh[1], totals.loads_wh[2]);
printf("TOTAL household consumed=%.2f Wh\r\n", total_consumed);
char payload[512];
int n = snprintf(payload, sizeof(payload),
"{\"mains_in\":%.3f,\"mains_out\":%.3f,\"solar\":%.3f,"
"\"self_used\":%.3f,\"total_consumed\":%.3f,"
"\"hp\":%.3f,\"ac\":%.3f,\"ev\":%.3f}",
totals.mains_in_wh, totals.mains_out_wh, totals.solar_total_wh,
solar_self_used, total_consumed,
totals.loads_wh[0], totals.loads_wh[1], totals.loads_wh[2]);
Net_MqttPublish("home/energy/balance", (const uint8_t*)payload,
(uint32_t)n, /*qos*/ 1, /*retain*/ 1);
}
Ejemplo 7: detección de eventos de corriente
Objetivo: en cada flanco de DRDY, comparar la P instantánea con una EMA y registrar las desviaciones significativas en una tarjeta SD mediante SDIO + FATFS. Hardware: STM32F4 / L4 / H7 + rbAmp + tarjeta SD en interfaz SDIO (CubeMX: habilite el middleware FATFS y SDIO).
Configuración en CubeMX:
SDIOmode = "SD 4 bits Wide bus" o "SD 1 bit"- Middleware
FATFSactivado, punto de montaje por defecto PA0=GPIO_EXTI0, bajada, pull-up (DRDY)
#include
#include
#include
#include "rbamp_io.h"
#include "fatfs.h"
extern I2C_HandleTypeDef hi2c1;
extern FATFS SDFatFS;
extern char SDPath[4];
extern volatile uint8_t g_data_ready; /* set by EXTI0 callback */
#define RB_ADDR 0x50U
#define EMA_ALPHA 0.05f
#define EVENT_THRESHOLD_W 200.0f
static FIL s_logfile;
static bool s_log_open = false; /* guard — f_write on closed FIL is UB */
/* USER CODE BEGIN 2 */
RbAmpIO_Bind(&hi2c1);
RbAmpIO_WaitReady(RB_ADDR, 2000);
/* Mount the SD card (CubeMX has already set up SDFatFS / SDPath).
* Both mount and open MUST succeed before we touch s_logfile in the loop. */
if (f_mount(&SDFatFS, SDPath, 1) == FR_OK) {
if (f_open(&s_logfile, "events.log",
FA_OPEN_APPEND | FA_WRITE) == FR_OK) {
s_log_open = true;
printf("SD mounted; logging to events.log\r\n");
} else {
printf("WARN: f_open(events.log) failed — file logging disabled\r\n");
}
} else {
printf("WARN: f_mount failed — file logging disabled\r\n");
}
/* Seed the EMA with current power so we do not log a spurious startup event. */
float p_ema = 0.0f;
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_P0_REAL, &p_ema);
printf("Event detector started\r\n");
/* USER CODE END 2 */
while (1) {
if (!g_data_ready) continue;
__disable_irq(); g_data_ready = 0; __enable_irq();
float p = 0.0f;
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_P0_REAL, &p);
float delta = p - p_ema;
p_ema = (1.0f - EMA_ALPHA) * p_ema + EMA_ALPHA * p;
if (fabsf(delta) > EVENT_THRESHOLD_W) {
const char *type = (delta > 0.0f) ? "TURN_ON" : "TURN_OFF";
char line[128];
int n = snprintf(line, sizeof(line),
"%lu %s delta=%+.1f W P=%.1f W EMA=%.1f W\r\n",
(unsigned long)HAL_GetTick(),
type, delta, p, p_ema);
printf("%s", line);
if (s_log_open) { /* never touch a closed FIL */
UINT bw;
f_write(&s_logfile, line, n, &bw);
f_sync(&s_logfile); /* flush to the card */
}
}
}
Ejemplo 8: publicador MQTT con descubrimiento automático de Home Assistant
Objetivo: integración de HA lista para usar. El STM32 publica las configuraciones de descubrimiento automático de HA (retenidas) y emite un estado JSON cada minuto. Hardware: STM32 con Ethernet (H7 / F7 / F4 + LAN8742) o cualquier STM32 con puente Ethernet.
#include
#include
#include "rbamp_io.h"
extern I2C_HandleTypeDef hi2c1;
extern HAL_StatusTypeDef Net_Init(void);
extern HAL_StatusTypeDef Net_MqttPublish(const char *topic,
const uint8_t *payload, uint32_t len,
uint8_t qos, uint8_t retain);
#define RB_ADDR 0x50U
#define DEVICE_ID "rbamp_main"
#define DEVICE_NAME "Mains rbAmp"
/**
* @brief Publish one HA discovery config (retained).
*/
static void publish_discovery_sensor(const char *key, const char *friendly,
const char *unit, const char *dev_class,
const char *state_class) {
char topic[128], payload[512];
snprintf(topic, sizeof(topic),
"homeassistant/sensor/%s/%s/config", DEVICE_ID, key);
int n = snprintf(payload, sizeof(payload),
"{"
"\"name\":\"%s %s\","
"\"unique_id\":\"%s_%s\","
"\"state_topic\":\"rbamp/%s/state\","
"\"value_template\":\"{{ value_json.%s }}\","
"\"state_class\":\"%s\","
"\"device\":{"
"\"identifiers\":[\"%s\"],"
"\"name\":\"%s\","
"\"manufacturer\":\"rbAmp\","
"\"model\":\"rbAmp UI*\""
"}",
DEVICE_NAME, friendly, DEVICE_ID, key,
DEVICE_ID, key, state_class,
DEVICE_ID, DEVICE_NAME);
if (unit) n += snprintf(payload + n, sizeof(payload) - n,
",\"unit_of_measurement\":\"%s\"", unit);
if (dev_class) n += snprintf(payload + n, sizeof(payload) - n,
",\"device_class\":\"%s\"", dev_class);
n += snprintf(payload + n, sizeof(payload) - n, "}");
Net_MqttPublish(topic, (const uint8_t*)payload, (uint32_t)n,
/*qos*/ 1, /*retain*/ 1);
}
/**
* @brief Publish the full set of HA discovery configs for one rbAmp.
*/
static void publish_discovery_all(void) {
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", NULL, "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");
}
/* USER CODE BEGIN 2 */
RbAmpIO_Bind(&hi2c1);
Net_Init();
publish_discovery_all();
RbAmpIO_WaitReady(RB_ADDR, 2000);
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD); /* primer */
uint32_t t_prev_ms = HAL_GetTick();
double total_wh = 0.0;
/* USER CODE END 2 */
while (1) {
HAL_Delay(60UL * 1000UL);
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
uint32_t t_now_ms = HAL_GetTick();
HAL_Delay(50);
uint8_t valid = 0;
RbAmpIO_ReadU8(RB_ADDR, RB_REG_PERIOD_VALID, &valid);
if ((valid & 0x01U) == 0) {
t_prev_ms = HAL_GetTick();
continue;
}
float avg_p = 0.0f;
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_PERIOD_AVG_P0, &avg_p);
float dt_s = (float)(t_now_ms - t_prev_ms) / 1000.0f;
total_wh += (double)avg_p * dt_s / 3600.0;
t_prev_ms = t_now_ms;
/* Live RT values for the state payload. */
float u = 0, i_ = 0, pf = 0, q = 0;
uint8_t freq = 0;
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_U_RMS, &u);
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_I0_RMS, &i_);
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_PF0, &pf);
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_Q0, &q);
RbAmpIO_ReadU8 (RB_ADDR, RB_REG_AC_FREQ, &freq);
char payload[384];
int n = snprintf(payload, sizeof(payload),
"{"
"\"voltage\":%.1f,"
"\"current\":%.3f,"
"\"power\":%.1f,"
"\"energy\":%.3f,"
"\"frequency\":%u,"
"\"power_factor\":%.3f,"
"\"apparent_power\":%.1f,"
"\"reactive_power\":%.1f"
"}",
u, i_, avg_p, total_wh,
(unsigned)freq, pf, u * i_, q);
char topic[64];
snprintf(topic, sizeof(topic), "rbamp/%s/state", DEVICE_ID);
Net_MqttPublish(topic, (const uint8_t*)payload, (uint32_t)n,
/*qos*/ 0, /*retain*/ 0);
printf("Published: %s\r\n", payload);
}
Ejemplo 9: registrador alimentado por batería con modo STANDBY
Objetivo: un registrador para exteriores o sin red eléctrica que despierta desde STANDBY cada 10 minutos mediante la alarma del RTC, toma una instantánea del periodo, la publica por MQTT y vuelve a STANDBY. El consumo lo domina el despertar poco frecuente: STANDBY está en el rango de unos pocos µA en la mayoría de familias STM32. Hardware: STM32L4 / L5 (mejor bajo consumo), o F4/F7 con funciones reducidas. rbAmp puede alimentarse mediante un interruptor high-side en un GPIO para que no consuma nada durante STANDBY. Persistencia: los registros de respaldo del RTC RTC->BKP0R..BKPxR (varían según la familia) sobreviven a STANDBY y a VBAT.
#include
#include
#include "rbamp_io.h"
/* CubeMX-generated: RTC + Wakeup timer + Backup registers in PWR */
extern I2C_HandleTypeDef hi2c1;
extern RTC_HandleTypeDef hrtc;
extern HAL_StatusTypeDef Net_Init(void);
extern HAL_StatusTypeDef Net_MqttPublish(const char *topic,
const uint8_t *payload, uint32_t len,
uint8_t qos, uint8_t retain);
#define RB_ADDR 0x50U
#define WAKE_SECONDS (10U * 60U) /* 10 minutes */
/* Backup-register layout (uint32 per slot). All survive STANDBY and VBAT.
* BKP0..1: total_wh (double, split into two uint32 halves)
* BKP2: wake_count
* BKP3: primer_done (0/1) + flags
* BKP4..5: t_prev_ms_ticks (uint64 split)
*/
#define BKP_TOTAL_WH_LO RTC_BKP_DR0
#define BKP_TOTAL_WH_HI RTC_BKP_DR1
#define BKP_WAKE_COUNT RTC_BKP_DR2
#define BKP_PRIMER RTC_BKP_DR3
#define BKP_T_PREV_LO RTC_BKP_DR4
#define BKP_T_PREV_HI RTC_BKP_DR5
static void bkp_load(double *total_wh, uint32_t *wakes,
uint8_t *primer, uint64_t *t_prev_ms) {
uint32_t lo = HAL_RTCEx_BKUPRead(&hrtc, BKP_TOTAL_WH_LO);
uint32_t hi = HAL_RTCEx_BKUPRead(&hrtc, BKP_TOTAL_WH_HI);
uint64_t bits = ((uint64_t)hi << 32) | lo;
memcpy(total_wh, &bits, sizeof(double));
*wakes = HAL_RTCEx_BKUPRead(&hrtc, BKP_WAKE_COUNT);
*primer = (uint8_t)HAL_RTCEx_BKUPRead(&hrtc, BKP_PRIMER);
uint32_t plo = HAL_RTCEx_BKUPRead(&hrtc, BKP_T_PREV_LO);
uint32_t phi = HAL_RTCEx_BKUPRead(&hrtc, BKP_T_PREV_HI);
*t_prev_ms = ((uint64_t)phi << 32) | plo;
}
static void bkp_save(double total_wh, uint32_t wakes,
uint8_t primer, uint64_t t_prev_ms) {
HAL_PWR_EnableBkUpAccess();
uint64_t bits;
memcpy(&bits, &total_wh, sizeof(double));
HAL_RTCEx_BKUPWrite(&hrtc, BKP_TOTAL_WH_LO, (uint32_t)(bits & 0xFFFFFFFFU));
HAL_RTCEx_BKUPWrite(&hrtc, BKP_TOTAL_WH_HI, (uint32_t)(bits >> 32));
HAL_RTCEx_BKUPWrite(&hrtc, BKP_WAKE_COUNT, wakes);
HAL_RTCEx_BKUPWrite(&hrtc, BKP_PRIMER, primer);
HAL_RTCEx_BKUPWrite(&hrtc, BKP_T_PREV_LO, (uint32_t)(t_prev_ms & 0xFFFFFFFFU));
HAL_RTCEx_BKUPWrite(&hrtc, BKP_T_PREV_HI, (uint32_t)(t_prev_ms >> 32));
}
/**
* @brief Arm the RTC wake-up timer and enter STANDBY.
* @details On the next wake (or RESET via NRST), execution restarts at the
* reset vector — exactly like a fresh boot.
*/
static void enter_standby(uint32_t seconds) {
HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, seconds,
RTC_WAKEUPCLOCK_CK_SPRE_16BITS);
HAL_PWR_EnterSTANDBYMode();
/* never returns */
}
/* USER CODE BEGIN 2 */
double total_wh;
uint32_t wake_count;
uint8_t primer_done;
uint64_t t_prev_unused; /* reserved BKP slot; see note below */
bkp_load(&total_wh, &wake_count, &primer_done, &t_prev_unused);
(void)t_prev_unused; /* HAL_GetTick() resets after STANDBY — */
/* the dt is approximated by WAKE_SECONDS */
/* instead. Slot kept for forward compat; */
/* upgrade to HAL_RTC_GetTime/Date if you */
/* need true wall-clock dt across sleeps. */
wake_count++;
RbAmpIO_Bind(&hi2c1);
if (RbAmpIO_WaitReady(RB_ADDR, 2000) != HAL_OK) {
bkp_save(total_wh, wake_count, primer_done, /*t_prev=*/0);
enter_standby(WAKE_SECONDS);
}
/* First wake-up after a cold boot: primer snapshot only. */
if (!primer_done) {
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
primer_done = 1;
bkp_save(total_wh, wake_count, primer_done, /*t_prev=*/0);
printf("Primer done — entering STANDBY\r\n");
enter_standby(WAKE_SECONDS);
}
/* Subsequent wake-ups: close the period and read its average power. */
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
HAL_Delay(50);
uint8_t valid = 0;
RbAmpIO_ReadU8(RB_ADDR, RB_REG_PERIOD_VALID, &valid);
if ((valid & 0x01U) == 0) {
bkp_save(total_wh, wake_count, primer_done, /*t_prev=*/0);
enter_standby(WAKE_SECONDS);
}
float avg_p = 0.0f;
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_PERIOD_AVG_P0, &avg_p);
/* dt approximation: STANDBY resets HAL_GetTick(), and the WAKE_SECONDS-driven
* RTC wake-timer is the wall-clock interval to single-digit-% accuracy with
* an LSE crystal. For tighter accounting, read HAL_RTC_GetTime/Date before
* STANDBY and compute dt against the stored epoch. */
float dt_s = (float)WAKE_SECONDS;
total_wh += (double)avg_p * dt_s / 3600.0;
/* Publish via Wi-Fi / Ethernet (graceful fallback). */
if (Net_Init() == HAL_OK) {
char payload[256];
int n = snprintf(payload, sizeof(payload),
"{\"wake\":%lu,\"dt_s\":%.1f,\"avg_p\":%.1f,\"energy_wh\":%.3f}",
(unsigned long)wake_count, dt_s, avg_p, total_wh);
Net_MqttPublish("rbamp/remote/state",
(const uint8_t*)payload, (uint32_t)n,
/*qos*/ 1, /*retain*/ 1);
printf("Published: %s\r\n", payload);
}
bkp_save(total_wh, wake_count, primer_done, /*t_prev=*/0);
enter_standby(WAKE_SECONDS);
/* USER CODE END 2 */
Notes:
- Los registros de respaldo (
BKP_DR*) sobreviven a STANDBY y a VBAT, pero no a una pérdida total de alimentación sin batería de respaldo VBAT. Para una persistencia absoluta, guarde periódicamente el total en la memoria flash interna. HAL_GetTick()se reinicia con cada STANDBY → use el calendario RTC (HAL_RTC_GetTime/Date) para un intervalo dt de hora de reloj absoluta si su aplicación lo necesita.- El RTC de CubeMX debe configurarse con LSE (cristal de 32.768 kHz) para una temporización fiable a largo plazo; la deriva del LSI puede llegar al 5–10 % según la temperatura.
- En STM32F1 / F4 el enum de la fuente de reloj de despertar puede diferir ligeramente; consulte la referencia HAL de la familia para los valores
RTC_WAKEUPCLOCK_*.
Ejemplo 10: tarifa por franjas horarias (TOU) con hora de pared SNTP
Objetivo: facturar la energía según un horario de tarifa por franjas horarias. El STM32 mantiene una hora de pared real mediante SNTP (LwIP lwip/apps/sntp.h), asigna cada periodo cerrado al tramo tarifario correspondiente, reinicia los totales diarios a medianoche y publica las cargas útiles con marcas de tiempo ISO. Hardware: STM32 con Ethernet (STM32H7 / F7 / F4 + LAN8742) o cualquier STM32 con puente Ethernet.
#include
#include
#include
#include "rbamp_io.h"
#include "lwip/apps/sntp.h"
extern I2C_HandleTypeDef hi2c1;
extern RTC_HandleTypeDef hrtc;
extern HAL_StatusTypeDef Net_Init(void);
extern HAL_StatusTypeDef Net_MqttPublish(const char *topic,
const uint8_t *payload, uint32_t len,
uint8_t qos, uint8_t retain);
#define RB_ADDR 0x50U
#define TZ_OFFSET_HOURS 2 /* CEST = UTC+2; recompute on roll-over for DST */
#define PEAK_START_HOUR 8
#define PEAK_END_HOUR 22
/* IMPORTANT: LwIP's SNTP populates the system clock via the SNTP_SET_SYSTEM_TIME
* macro that you MUST define in lwipopts.h. Without it, time(NULL) stays at 0
* forever and sntp_sync() will always time out. Minimal hook:
*
* #include
* #define SNTP_SET_SYSTEM_TIME(sec) \
* do { struct timeval tv = { (time_t)(sec), 0 }; \
* settimeofday(&tv, NULL); } while (0)
*
* Also requires _gettimeofday() / time() to be retargeted to the same source
* (newlib's default works once settimeofday is wired). */
typedef struct {
double peak_wh;
double off_peak_wh;
int day_of_year; /* tm_yday */
} day_totals_t;
typedef struct {
double peak_wh;
double off_peak_wh;
} lifetime_totals_t;
static day_totals_t s_today = { .day_of_year = -1 };
static lifetime_totals_t s_lifetime = { 0 };
/**
* @brief Start SNTP and wait until the system clock looks plausible (year > 2023).
*/
static HAL_StatusTypeDef sntp_sync(uint32_t timeout_ms) {
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, "pool.ntp.org");
sntp_setservername(1, "time.google.com");
sntp_init();
uint32_t deadline = HAL_GetTick() + timeout_ms;
while (HAL_GetTick() < deadline) {
time_t now = time(NULL);
struct tm lt;
gmtime_r(&now, <);
if (lt.tm_year + 1900 >= 2023) {
printf("SNTP sync: %04d-%02d-%02d %02d:%02d:%02d UTC\r\n",
lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday,
lt.tm_hour, lt.tm_min, lt.tm_sec);
return HAL_OK;
}
HAL_Delay(500);
}
return HAL_TIMEOUT;
}
static struct tm local_time(void) {
time_t now = time(NULL) + (TZ_OFFSET_HOURS * 3600);
struct tm lt;
gmtime_r(&now, <);
return lt;
}
static bool is_peak_hour(int hour) {
/* For schedules that cross midnight, swap to
* return (hour >= PEAK_START_HOUR) || (hour < PEAK_END_HOUR);
*/
return (hour >= PEAK_START_HOUR) && (hour < PEAK_END_HOUR);
}
static void iso_now(char *out, size_t out_len) {
struct tm lt = local_time();
const char sign = (TZ_OFFSET_HOURS >= 0) ? '+' : '-';
snprintf(out, out_len, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d00",
lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday,
lt.tm_hour, lt.tm_min, lt.tm_sec,
sign, (TZ_OFFSET_HOURS < 0) ? -TZ_OFFSET_HOURS : TZ_OFFSET_HOURS);
}
/**
* @brief Add one period's energy to the right tariff bucket and roll over at midnight.
*/
static void accumulate(double e_wh, const struct tm *tm_now) {
if (s_today.day_of_year != tm_now->tm_yday) {
if (s_today.day_of_year >= 0) {
char payload[192];
int n = snprintf(payload, sizeof(payload),
"{\"yday\":%d,\"peak_wh\":%.3f,\"off_peak_wh\":%.3f,"
"\"total_wh\":%.3f}",
s_today.day_of_year, s_today.peak_wh, s_today.off_peak_wh,
s_today.peak_wh + s_today.off_peak_wh);
Net_MqttPublish("rbamp/tou/day_close",
(const uint8_t*)payload, (uint32_t)n,
/*qos*/ 1, /*retain*/ 1);
printf("Day closed: %s\r\n", payload);
}
s_today.peak_wh = 0.0;
s_today.off_peak_wh = 0.0;
s_today.day_of_year = tm_now->tm_yday;
}
if (is_peak_hour(tm_now->tm_hour)) {
s_today.peak_wh += e_wh;
s_lifetime.peak_wh += e_wh;
} else {
s_today.off_peak_wh += e_wh;
s_lifetime.off_peak_wh += e_wh;
}
}
/* USER CODE BEGIN 2 */
RbAmpIO_Bind(&hi2c1);
Net_Init();
sntp_sync(15000);
RbAmpIO_WaitReady(RB_ADDR, 2000);
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD); /* primer */
uint32_t t_prev_ms = HAL_GetTick();
printf("TOU started: peak %02d:00..%02d:00 local\r\n",
PEAK_START_HOUR, PEAK_END_HOUR);
/* USER CODE END 2 */
while (1) {
HAL_Delay(60UL * 1000UL);
RbAmpIO_WriteU8(RB_ADDR, RB_REG_COMMAND, RB_CMD_LATCH_PERIOD);
uint32_t t_now_ms = HAL_GetTick();
HAL_Delay(50);
uint8_t valid = 0;
RbAmpIO_ReadU8(RB_ADDR, RB_REG_PERIOD_VALID, &valid);
if ((valid & 0x01U) == 0) {
t_prev_ms = HAL_GetTick();
continue;
}
float avg_p = 0.0f;
RbAmpIO_ReadFloatLE(RB_ADDR, RB_REG_PERIOD_AVG_P0, &avg_p);
float dt_s = (float)(t_now_ms - t_prev_ms) / 1000.0f;
double e_wh = (double)avg_p * dt_s / 3600.0;
t_prev_ms = t_now_ms;
/* Guard against fresh boot before SNTP succeeds. */
struct tm lt = local_time();
if (lt.tm_year + 1900 < 2023) {
printf("WARN: clock not yet synced, retrying SNTP\r\n");
sntp_sync(15000);
continue;
}
accumulate(e_wh, <);
bool peak = is_peak_hour(lt.tm_hour);
char iso[40];
iso_now(iso, sizeof(iso));
char payload[384];
int n = snprintf(payload, sizeof(payload),
"{"
"\"ts\":\"%s\","
"\"tariff\":\"%s\","
"\"avg_p\":%.1f,"
"\"period_wh\":%.4f,"
"\"today_peak_wh\":%.3f,"
"\"today_off_peak_wh\":%.3f,"
"\"life_peak_wh\":%.3f,"
"\"life_off_peak_wh\":%.3f"
"}",
iso, peak ? "peak" : "off_peak",
avg_p, e_wh,
s_today.peak_wh, s_today.off_peak_wh,
s_lifetime.peak_wh, s_lifetime.off_peak_wh);
Net_MqttPublish("rbamp/tou/state", (const uint8_t*)payload,
(uint32_t)n, /*qos*/ 0, /*retain*/ 0);
printf("%s\r\n", payload);
}
Notes:
- El cliente SNTP de LwIP rellena la fuente
time(NULL)de la biblioteca C a través de los hooksSYS_ARCH_RAND/sys_nowde LwIP; en los puertos STM32,gmtime_r()devuelve entonces valores razonables. - Para un manejo completo del horario de verano, guarde el desfase TZ en una pequeña tabla de búsqueda y recalcúlelo en el cambio de día, o pase la hora por
tzset()con una cadena TZ POSIX si su build de newlib lo admite (la mayoría lo hace). - Para la medición bidireccional de un STD, llame a
accumulate()dos veces: una para el lado de consumo y otra para el de exportación, y publique ambos cubos punta / valle.
Comparación de ejemplos
| # | Complejidad | Salida | MQTT | DRDY | Multimódulo | Bidireccional | Persistencia | Caso de uso |
|---|---|---|---|---|---|---|---|---|
| 1 | mínimo | printf por UART | — | — | — | — | — | prueba de humo |
| 2 | bajo | OLED | — | — | — | — | RAM | medidor en caja |
| 3 | bajo | printf por UART | — | — | sí (3) | — | — | monitorización doméstica |
| 4 | medio | — | sí | — | — | — | RAM | por electrodoméstico en HA |
| 5 | medio | printf por UART | — | sí | — | sí (maestro) | RAM | vivienda solar en nivel BASIC |
| 6 | alta | — | sí | — | sí (3) | sí | RAM | balance energético de toda la casa |
| 7 | medio | UART + SD (FATFS) | — | sí | — | — | Tarjeta SD | detección de eventos |
| 8 | medio | — | sí (+disco) | — | — | opcional | RAM + MQTT | Auto-descubrimiento de HA |
| 9 | medio | — | sí | — | — | — | Registros de respaldo RTC (BKP) | registrador exterior / autónomo |
| 10 | medio | printf por UART | sí | — | — | opcional | RAM + MQTT | TOU punta/fuera de punta con SNTP |
Buenas prácticas
- Compruebe siempre los códigos de retorno de la HAL. Las transacciones I²C pueden fallar de forma transitoria en buses largos; el código de producción debe reintentar en lugar de ignorar el error. Envuelva los reintentos alrededor de las llamadas
RbAmpIO_*si hace falta. - Mantenga las ISR pequeñas. Las callbacks de EXTI / SysTick / fin de DMA deben poner a 1 un
volatile uint8_ty regresar. Todo el trabajo de I²C y printf pertenece al bucle principal. - Un controlador I²C HAL por periférico. Tanto rbAmp como la OLED usan
hi2c1: nunca reinicie el periférico, use simplemente el manejador compartido. - Use
HAL_GetTick()para el reloj maestro. Precisión de milisegundos, monotónico, sobrevive a la mayoría de operaciones de la HAL. PERIOD_VALID(0x07) debe comprobarse tras cadaCMD_LATCH_PERIOD. Las instantáneas obsoletas aparecen si el maestro consulta más rápido de lo que integra el firmware.- Espere ≥ 50 ms tras una instantánea antes de leer
0xDC..0xEF: el firmware finaliza la instantánea dentro de su bucle principal. - Use
HAL_I2C_IsDeviceReady()para escaneos del bus: equivalente en STM32 del pingendTransmission()de Arduino. - Para aplicaciones con batería, entre en STOP o STANDBY entre muestras y arme el temporizador de despertar RTC. STANDBY reinicia la ejecución en el vector de reinicio: use registros de respaldo para el estado que deba sobrevivir.
- Guarde los totales de Wh en la memoria flash interna si necesita que sobrevivan a una pérdida total de alimentación (retirada de la batería sin VBAT). Los registros de respaldo RTC solo sobreviven si hay VBAT o VDD.
- Soporte de flotantes en
printfrequiere-u _printf_floaten los flags del enlazador de CubeIDE (compilación newlib-nano).
Lo siguiente
Tras repasar estos diez ejemplos:
- Para desarrollo ESP32 al estilo Arduino, véase arduino-examples.md (sin formato).
- Para MicroPython / CircuitPython, véase micropython-examples.md (sin formato).
- Para ESP-IDF nativo, consulte esp-idf-examples.md (sin procesar).
- Para el SDK C de Raspberry Pi Pico, véase pico-sdk-examples.md.
- Para la integración con ESPHome (YAML declarativo), consulte
tools/esphome-rbamp/docs/en/. - La especificación formal de registros I²C que se usa aquí está en api-reference.md.