esphome-integrar-esp32-sensores-diy-home-assistant

ESPHome: How to Integrate an ESP32 with Home Assistant

  • 6 min

ESPHome is a system for generating microcontroller firmware from a YAML configuration and integrating them directly into Home Assistant.

The natural solution to this problem is to build our own hardware. At luisllamas.es we’ve been programming ESP8266 and ESP32 microcontrollers in C++ using the Arduino IDE for years.

However, writing C++ code from scratch to manage WiFi reconnection, keep a socket open, publish structured payloads, and manage availability (LWT) is a repetitive, tedious, and error-prone process. To avoid reinventing the wheel for every node, the Home Assistant ecosystem provides us with an extremely practical tool: ESPHome.

What is ESPHome?

ESPHome is a system that allows us to create custom firmware for microcontrollers (ESP8266, ESP32, RP2040, etc.) by writing only YAML configuration files, without touching a single line of C/C++ code.

The internal workings are very elegant:

  1. We define the hardware (pins, sensors, relays) in a YAML file.
  2. The ESPHome engine (written in Python) reads that YAML and dynamically generates the corresponding C++ source code.
  3. It downloads the necessary libraries from PlatformIO.
  4. It compiles the C++ code into a binary file (.bin).
  5. It flashes the binary onto our microcontroller.

The result is a robust IoT device, with automatic WiFi reconnection management, watchdog-controlled reboots, and support for over-the-air updates (OTA).

ESPHome does not eliminate the need to understand basic electronics. If we connect a sensor to the wrong pin, power a 3.3V module with 5V, or incorrectly mix grounds, the YAML won’t save us. The configuration simplifies the software, it doesn’t nullify physics.

Native API vs. MQTT

Traditionally, maker devices communicated with the server using the MQTT protocol. Although MQTT is excellent (and we’ll see it in the next article), ESPHome uses its own Native API by default.

The ESPHome native API uses a persistent TCP connection on port 6053, encoding data using Google’s Protocol Buffers.

This offers three very clear architectural advantages for our server:

  • Lower Overhead: Protocol Buffers is a binary serialization format, much lighter and faster to process than JSON text strings over MQTT.
  • Near-zero Latency: By keeping a TCP socket open directly with the Home Assistant Core, the latency between pressing a button on the ESP32 and Home Assistant registering it is only a couple of milliseconds.
  • Instant Auto-discovery: When you plug in an ESPHome node, Home Assistant detects it instantly. With a single click, all entities (sensors, switches, diagnostics) appear in the state machine.

Installation and First Flashing

To start using ESPHome in our HAOS-based architecture, we need to install the ESPHome Device Builder.

Go to the Home Assistant add-on store, search for “ESPHome Device Builder”, and install it. This launches a container with the compilation environment and a web interface for managing configurations.

First Installation and OTA Updates

For us to be able to update our board over WiFi (OTA), it first needs to have the ESPHome firmware installed with our network credentials.

For a new board, the first installation is usually done via USB from a computer. A browser compatible with WebSerial can install the firmware following the wizard; depending on the chip and USB adapter, installing its driver might still be necessary.

Once the first flashing is complete, you can disconnect the ESP32 from the computer. Subsequent compilations and updates can be installed over the air via OTA.

If an ESPHome node is going to stay fixed in an important location, it’s often worth reserving an IP for it on the router. Not because ESPHome always needs it, but because it makes debugging easier, allows you to access its logs, and locate it quickly when something goes wrong.

Anatomy of an ESPHome Node (YAML)

Let’s analyze the structured code of a real node. Suppose we want to build a high-precision temperature sensor for an aquarium using a Dallas DS18B20 waterproof probe, connected to GPIO4 of an ESP32.

The YAML configuration file is divided into logical blocks. This is the complete code to have the sensor reporting data to Home Assistant:

# 1. DEVICE METADATA
esphome:
  name: sensor-acuario
  friendly_name: "Aquarium Sensor"

# 2. CORE HARDWARE DEFINITION
esp32:
  board: esp32dev
  framework:
    type: arduino

# 3. COMMUNICATIONS AND BASE SERVICES
wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

# Enable the Native API for Home Assistant
api:
  encryption:
    key: !secret api_encryption_key

# Enable Over-the-Air updates
ota:
  - platform: esphome
    password: !secret ota_password

# 4. PHYSICAL COMPONENT DEFINITION
# The 1-Wire bus needed for the Dallas/DS18B20 sensor
one_wire:
  - platform: gpio
    pin: GPIO4

sensor:
  # Define the sensor platform
  - platform: dallas_temp
    address: 0x51011453ABF5AA28 # The unique internal sensor address
    name: "Aquarium Water Temperature"
    unit_of_measurement: "°C"
    accuracy_decimals: 2
    update_interval: 10s
    
  # Internal diagnostic sensors (optional but recommended)
  - platform: wifi_signal
    name: "Aquarium WiFi Signal"
    update_interval: 60s
Copied!

The Concept of Platforms

The real beauty of ESPHome lies in the sensor block (or switch, binary_sensor, display).

ESPHome has native support for hundreds of platforms. If tomorrow we decide to add an I2C OLED display to see the temperature physically on the aquarium, we don’t need to search for Adafruit libraries, initialize the I2C bus in the setup(), or manage buffer clearing in the loop().

We simply add the i2c: block defining the SDA and SCL pins, and a display: block with the ssd1306_i2c platform. ESPHome handles all the low-level code during compilation.

Edge Logic

ESPHome is not just a “dumb” bridge that sends data to the server. It is capable of running automations on the microcontroller itself.

If we implement a relay on the ESP32 to turn on the aquarium heater, we can program a safety rule directly in the ESPHome YAML: “If the temperature drops below 24°C, turn on the relay”.

# On-device automation fragment in ESPHome
sensor:
  - platform: dallas_temp
    # ...
    on_value_range:
      - below: 24.0
        then:
          - switch.turn_on: heater_relay
Copied!

This logic runs on the ESP32 itself. If Home Assistant or the network goes down, the microcontroller can continue to maintain the aquarium temperature autonomously.