Ir al contenido

← Guía de hardware | Contenido | Siguiente: Estructura de la aplicación →

2. Requisitos de compilación

💡 ¿No quieres compilar? Los binarios de firmware precompilados están disponibles en la página de GitHub Releases . Simplemente descarga, extrae y flashea con los scripts incluidos — ¡no se requiere compilación!



2.1 Plataforma y herramientas


Plataforma principal

  • Versión de ESP-IDF: 5.5.1 (obligatoria)
  • Microcontrolador: ESP32 (clásico, no ESP32-S2/S3/C3)
  • Arquitectura: Xtensa dual-core LX6
  • Frecuencia de CPU: 240 MHz
  • Flash mínimo: 4 MB
  • RAM mínima: 520 KB (ESP32-WROOM-32 o ESP32-WROVER)


Frameworks y componentes

  • Arduino Core para ESP32: versión 3.x (vía ESP-IDF Component Manager)
  • CMake: versión mínima 3.16
  • Python: 3.8+ (para scripts idf.py)



2.2 Bibliotecas requeridas


Dependencias principales (vía IDF Component Manager)

Definidas en el archivo main/idf_component.yml:

yaml
dependencies:
  # Arduino Core 3.x for ESP32
  espressif/arduino-esp32:
    version: "^3.0.0"

  # ArduinoJson v7 - JSON serialization
  bblanchon/arduinojson:
    version: "^7.0.0"

  # IDF built-in components
  idf:
    version: ">=5.0.0"


Componentes ESP-IDF integrados (usados automáticamente)

  • nvs_flash – Almacenamiento no volátil para configuración
  • esp_wifi – Controlador y protocolos WiFi
  • esp_http_server – Servidor web asíncrono
  • esp_adc – Controlador ADC con soporte DMA
  • driver – Controladores GPIO, LEDC, Timer
  • freertos – Sistema operativo en tiempo real


Componentes personalizados (locales)

Ubicados en components/:

Componente Ruta Función
comm components/comm WiFi, WebServer, REST API, interfaz Material UI
hal components/hal Capa de abstracción de hardware (DimmerHAL, PowerMeterADC)
utils components/utils ConfigManager, HardwareConfigManager, SerialCommand
control components/control RouterController, algoritmos de control
rbdimmer components/rbdimmer Biblioteca RBDimmer (dimmer TRIAC)



2.3 Configuración del build (sdkconfig)


Parámetros principales

ini
# Microcontroller
CONFIG_IDF_TARGET="esp32"
CONFIG_SOC_CPU_CORES_NUM=2
CONFIG_ESP32_DEFAULT_CPU_FREQ_240=y

# Flash configuration
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESPTOOLPY_FLASHMODE_DIO=y
CONFIG_ESPTOOLPY_FLASHFREQ_40M=y

# FreeRTOS
CONFIG_FREERTOS_HZ=1000                    # 1ms tick
CONFIG_FREERTOS_UNICORE=n                  # Dual-core mode

# Serial Monitor
CONFIG_ESPTOOLPY_MONITOR_BAUD=115200


Configuraciones clave del proyecto

Configuración ADC

ini
CONFIG_SOC_ADC_SUPPORTED=y
CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y        # Digital controller
CONFIG_SOC_ADC_DMA_SUPPORTED=y             # DMA for continuous reading
CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12        # 12-bit resolution

Configuración WiFi

ini
CONFIG_SOC_WIFI_SUPPORTED=y
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y

Flash y particiones

ini
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"



2.4 Tabla de particiones

Archivo: partitions.csv

csv
# ESP32 Partition Table for AC Power Router Controller with OTA
# Flash Size: 4MB
#
# Name,     Type,    SubType,  Offset,   Size,     Flags
nvs,        data,    nvs,      0x9000,   0x6000,
otadata,    data,    ota,      0xf000,   0x2000,
app0,       app,     ota_0,    0x20000,  0x190000,
app1,       app,     ota_1,    0x1B0000, 0x190000,
spiffs,     data,    spiffs,   0x340000, 0xC0000,


Descripción de las particiones

Partición Tipo Tamaño Offset Función
nvs data (nvs) 24 KB (0x6000) 0x9000 Configuración del dispositivo (WiFi, RouterController, HardwareConfig)
otadata data (ota) 8 KB (0x2000) 0xf000 Metadatos OTA (qué app0/app1 está activo)
app0 app (ota_0) 1.6 MB (0x190000) 0x20000 Primer slot de firmware (OTA slot 0)
app1 app (ota_1) 1.6 MB (0x190000) 0x1B0000 Segundo slot de firmware (OTA slot 1)
spiffs data (spiffs) 768 KB (0xC0000) 0x340000 Sistema de archivos para la interfaz Web (HTML/CSS/JS)


Mapa de memoria Flash (4 MB)

python
0x000000 ┌─────────────────────────┐
         │  Bootloader             │ (Automatic)
0x008000 ├─────────────────────────┤
         │  Partition Table        │ (Automatic)
0x009000 ├─────────────────────────┤
         │  NVS (24 KB)            │ ← Configuration
0x00F000 ├─────────────────────────┤
         │  OTA Data (8 KB)        │ ← OTA Metadata
0x020000 ├─────────────────────────┤
         │                         │
         │  APP 0 (1.6 MB)         │ ← Firmware slot 0
         │                         │
0x1B0000 ├─────────────────────────┤
         │                         │
         │  APP 1 (1.6 MB)         │ ← Firmware slot 1
         │                         │
0x340000 ├─────────────────────────┤
         │                         │
         │  SPIFFS (768 KB)        │ ← Web UI files
         │                         │
0x400000 └─────────────────────────┘ (4 MB)



2.5 Comandos de compilación y flasheo


Configuración del entorno (Windows)

powershell
# Install ESP-IDF 5.5.1
# Download from https://dl.espressif.com/dl/esp-idf/

# Activate environment
cd %USERPROFILE%\esp\esp-idf
.\export.ps1

# Navigate to project directory
cd C:\Users\\Documents\ESP-PROJECTS\ACRouter\ACRouter-project


Configuración del entorno (Linux/macOS)

bash
# Install ESP-IDF 5.5.1
mkdir -p ~/esp
cd ~/esp
git clone -b v5.5.1 --recursive https://github.com/espressif/esp-idf.git
cd esp-idf
./install.sh esp32

# Activate environment
. $HOME/esp/esp-idf/export.sh

# Navigate to project directory
cd ~/ACRouter-project


Comandos principales de compilación

1. Instalar dependencias (primera vez)

bash
idf.py set-target esp32
idf.py reconfigure

Esto instalará automáticamente:

  • Arduino Core 3.x (espressif/arduino-esp32)
  • ArduinoJson v7 (bblanchon/arduinojson)

2. Configuración del proyecto (opcional)

bash
idf.py menuconfig

Ajustes disponibles a través de menuconfig:

  • Serial flasher config → Tamaño del flash (4 MB)
  • Serial flasher config → Frecuencia del flash (40 MHz)
  • Partition Table → Tabla de particiones personalizada CSV
  • Component config → FreeRTOS → Frecuencia del tick (1000 Hz)

3. Compilar el proyecto

bash
# Full build
idf.py build

# Quick rebuild (only changed files)
idf.py app

# Clean and full rebuild
idf.py fullclean
idf.py build

4. Flashear y monitorizar

bash
# Flash + Serial monitor
idf.py flash monitor

# Flash only
idf.py flash

# Serial monitor only
idf.py monitor

# Flash via specific port (Windows)
idf.py -p COM3 flash monitor

# Flash via specific port (Linux)
idf.py -p /dev/ttyUSB0 flash monitor



2.6 Comando de flash y direcciones de memoria


Comando esptool.py (flasheo directo)

Si necesitas flashear manualmente con esptool.py (por ejemplo, desde otro ordenador):

bash
esptool.py --chip esp32 \
  --port COM3 \
  --baud 921600 \
  --before default_reset \
  --after hard_reset \
  write_flash -z \
  --flash_mode dio \
  --flash_freq 40m \
  --flash_size 4MB \
  0x1000 build/bootloader/bootloader.bin \
  0x8000 build/partition_table/partition-table.bin \
  0x20000 build/ACRouter-project.bin


Direcciones de archivos en el volcado de memoria

Archivo Dirección Tamaño Descripción
bootloader.bin 0x1000 ~28 KB Bootloader ESP32 (segunda etapa)
partition-table.bin 0x8000 ~3 KB Tabla de particiones
ACRouter-project.bin 0x20000 ~1.6 MB Firmware principal (app0)
ota_data_initial.bin 0xf000 8 KB Datos OTA iniciales (opcional)


Copia de seguridad del flash

bash
# Read entire Flash (4 MB)
esptool.py --chip esp32 --port COM3 \
  read_flash 0x0 0x400000 backup_flash_4MB.bin

# Read firmware only (app0)
esptool.py --chip esp32 --port COM3 \
  read_flash 0x20000 0x190000 backup_app0.bin

# Read NVS only (configuration)
esptool.py --chip esp32 --port COM3 \
  read_flash 0x9000 0x6000 backup_nvs.bin


Restauración desde copia de seguridad

bash
# Restore full Flash
esptool.py --chip esp32 --port COM3 --baud 921600 \
  write_flash 0x0 backup_flash_4MB.bin

# Restore NVS only (preserve configuration)
esptool.py --chip esp32 --port COM3 \
  write_flash 0x9000 backup_nvs.bin



2.7 Tamaño del firmware y uso de memoria


Tamaños típicos tras la compilación

python
Build Output:
=====================================
Bootloader:              28,512 bytes (0x6F80)
Partition Table:          3,072 bytes (0xC00)
ACRouter-project.bin:   ~1,200,000 bytes (~1.15 MB)
=====================================


Mapa de uso del flash (tras el flasheo)

python
Flash Usage (4 MB total):
├─ Bootloader + Partition     ~32 KB      (0.8%)
├─ NVS (configuration)         24 KB      (0.6%)
├─ OTA Data                     8 KB      (0.2%)
├─ APP 0 (firmware)          ~1.2 MB     (30%)
├─ APP 1 (OTA reserve)       ~1.2 MB     (30%)  ← Will be used during OTA update
├─ SPIFFS (Web UI)            768 KB     (19%)  ← Reserved for future
└─ Free                       ~748 KB    (18%)


Uso de RAM (en ejecución)

python
DRAM (Data RAM):
├─ Static .data + .bss       ~120 KB
├─ Heap (available)          ~180 KB
└─ FreeRTOS stacks           ~80 KB
=====================================
Total DRAM:                  ~380 KB / 520 KB

IRAM (Instruction RAM):
├─ Code (.text)              ~100 KB
├─ Cache                     ~32 KB
=====================================
Total IRAM:                  ~132 KB / 192 KB



2.8 Verificación de una compilación exitosa

Después de ejecutar idf.py build deberías ver:

python
Project build complete. To flash, run:
 idf.py flash
or
 idf.py -p (PORT) flash
or
 esptool.py --chip esp32 --port (PORT) --baud 921600 write_flash \
   --flash_mode dio --flash_size 4MB --flash_freq 40m \
   0x1000 build/bootloader/bootloader.bin \
   0x8000 build/partition_table/partition-table.bin \
   0x20000 build/ACRouter-project.bin


Archivos generados (build/)

Archivos principales en el directorio build/:

  • ACRouter-project.bin – firmware principal
  • ACRouter-project.elf – archivo ELF con símbolos (para depuración)
  • ACRouter-project.map – mapa de memoria (direcciones de funciones)
  • bootloader/bootloader.bin – bootloader
  • partition_table/partition-table.bin – tabla de particiones



2.9 Problemas comunes de compilación


Issue 1: Error "arduino-esp32 not found"

Solución:

bash
idf.py reconfigure
# Or manually:
cd managed_components
rm -rf espressif__arduino-esp32
idf.py reconfigure


Problema 2: Espacio de flash insuficiente

Síntoma:

python
Error: app partition is too small for binary

Solución: Verifica partitions.csv — app0/app1 debe ser >= 0x190000 (1,6 MB)


Problema 3: Conflicto de versión de ESP-IDF

Síntoma:

python
CMake Error: ESP-IDF version mismatch

Solución:

bash
# Check IDF version
idf.py --version

# Should be: ESP-IDF v5.5.1
# If different version - reinstall IDF 5.5.1


Issue 4: Error "NVS namespace too long"

Síntoma:

python
Error: NVS key exceeds 15 characters

Solución: Las claves NVS están limitadas a 15 caracteres. Usa abreviaturas (consulta HardwareConfigManager.h).


Issue 5: Don't Want to Deal with Build Issues?

Solución: ¡Usa los binarios de firmware precompilados!

If you're experiencing persistent build problems or simply want to get started quickly:

  1. Visita GitHub Releases
  2. Descarga la última versión del firmware
  3. Extrae el archivo que contiene:
  4. bootloader.bin
  5. partition-table.bin
  6. ACRouter-project.bin
  7. ota_data_initial.bin
  8. flash.bat / flash.sh (scripts de flasheo)
  9. FLASH_README.txt (instrucciones)
  10. Flashea con el script incluido:
  11. Windows: flash.bat COM5
  12. Linux/Mac: ./flash.sh /dev/ttyUSB0

¡No se requiere instalación de ESP-IDF ni compilación!


← Guía de hardware | Contenido | Siguiente: Estructura de la aplicación →