/ #home assistant #esp32 

Control and Automate Air Purifier with ESP32 and Home Assistant Air Quality Index

I’ve always been a bit obsessive about air quality. Living in a city, you notice the difference a good air purifier makes, but I got tired of manually turning it on every time the pollution levels spiked. It felt, well, decidedly un-smart. So I set out to fix that by creating a system where my air purifier automatically kicks in when the Home Assistant Air Quality Index (AQI) reaches a certain threshold.

The result? A perfectly automated, healthier living space that requires zero intervention. In this step-by-step guide, I’ll show you how to control and automate an air purifier with ESP32 and Home Assistant Air Quality Index monitoring. We’ll use a simple relay to safely interface with the purifier and ESPhome to make the ESP32 a seamless part of our smart home.

What You’ll Need

Before we dive in, let’s gather our tools. Here’s the shopping list for this project:

  • ESP32 Development Board: The brains of the operation. I used a generic ESP32 DevKit, which is cheap and powerful.
  • 5V Relay Module: This is the switch that will safely control your air purifier. A 1-channel relay like this one is perfect.
  • Jumper Wires (Male-to-Female): For making connections without a breadboard.
  • Micro-USB Cable: To power the ESP32.
  • AC Power Cord & Socket (Optional but Recommended): For a safe and permanent installation. You can get an outlet box kit to house the relay cleanly.
  • A Smart Air Quality Sensor: I’m assuming you already have an AQI sensor in Home Assistant. This could be a PurpleAir, a DIY sensor with an SDS011, or even a weather service providing local AQI data.
  • Home Assistant Instance: Obviously, you’ll need Home Assistant set up and running.
  • ESPhome Add-on: Installed in your Home Assistant instance.

Step 1: The Hardware Hookup (It’s Easier Than You Think)

Don’t let the wires intimidate you; this is a simple circuit. We’re connecting the relay to the ESP32 so that Home Assistant can tell the ESP32 to flip the switch.

Here’s the wiring diagram in text form:

  1. Relay VCC → ESP32 5V pin
  2. Relay GND → ESP32 GND pin
  3. Relay IN (or SIG) → ESP32 GPIO 23 (You can use almost any GPIO pin, I just like 23)
⚠️ Safety First! If you're planning to control a high-voltage device like a plug-in air purifier, please, please be careful. Use a pre-made outlet box or ensure all high-voltage connections are properly insulated and enclosed. We're only dealing with low-voltage (5V) on the ESP32 side.

The relay acts as a switch for the air purifier’s power. The ESP32 sends a 3.3V signal to the relay’s input pin, which activates an electromagnet inside, physically flipping the switch on the high-voltage side. It’s a simple, isolated, and safe way to control AC devices.

Step 2: Flashing the ESP32 with ESPhome

ESPhome is the magic glue that makes DIY ESP devices feel native in Home Assistant. We’ll create a configuration file to define our relay switch.

  1. In your Home Assistant sidebar, go to Settings -> Add-ons.
  2. If you haven’t already, install the ESPhome add-on.
  3. Open the ESPhome dashboard and click + NEW DEVICE. Follow the prompts to set up a new device, giving it a name like air-purifier-controller. When asked for a platform, select ESP32.

Now, let’s craft the configuration. Replace the default YAML code with the following:

# air-purifier-controller.yaml
esphome:
  name: air-purifier-controller
  friendly_name: Air Purifier Controller

esp32:
  board: esp32dev
  framework:
    type: arduino

# Enable logging and a simple API for Home Assistant communication
logger:
api:
ota:
  password: "your_secure_ota_password"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Optional: Add a fallback hotspot in case WiFi fails
  ap:
    ssid: "Air-Purifier-Controller Fallback"
    password: "another_secure_password"

captive_portal:

# Our main component - the relay switch
switch:
  - platform: gpio
    name: "Air Purifier Relay"
    pin: GPIO23
    id: relay_purifier
    icon: "mdi:air-purifier"
    # Assuming your relay is 'active low'. If it behaves backwards, set this to 'true'.
    inverted: false

A few things to note here:

  • Secrets: I’m using !secret for my WiFi credentials. You should too! Create a secrets.yaml file in your ESPhome folder and define wifi_ssid and wifi_password there.
  • OTA: The ota section allows you to push future updates to the ESP32 over-the-air, which is incredibly convenient.
  • inverted: false: Some relay modules are “active low,” meaning they turn on when the signal is LOW. If your relay clicks “on” when you flash the firmware but is “off” in Home Assistant, change this to inverted: true.

Save the configuration and click INSTALL. Choose the Plug into this computer method and follow the on-screen instructions to flash your ESP32. Once it’s done, the device should connect to your WiFi and appear in your Home Assistant dashboard.

Step 3: Integrating the AQI Sensor in Home Assistant

For the automation to work, Home Assistant needs a reliable air quality sensor. I use a PurpleAir sensor integration, but the process is similar for any sensor.

Your sensor entity will likely have an attribute for the AQI. You can find this by going to Settings -> Devices & Services -> Entities and searching for your sensor. Look for an attribute like aqi or air_quality_index.

To make this easier to use in an automation, let’s create a template sensor that exposes the AQI as its own state.

Add this to your configuration.yaml file:

# In configuration.yaml
template:
  - sensor:
      - name: "Living Room AQI"
        unit_of_measurement: "AQI"
        # Replace 'sensor.purpleair_sensor' with your actual sensor entity_id
        state: "{{ state_attr('sensor.purpleair_sensor', 'aqi') | int }}"
        # If your sensor provides PM2.5, you can calculate AQI directly.
        # Uncomment and use the lines below instead, replacing with your PM2.5 entity.
        # state: >
        #   {% set pm25 = states('sensor.living_room_pm25') | float %}
        #   {{ ((pm25 / 12.0) * 100) | round(0) }}

Restart Home Assistant. You should now have a new sensor called sensor.living_room_aqi that gives a clean numeric AQI value.

Step 4: Creating the Magic - The Home Assistant Automation

This is where it all comes together. We’ll create an automation that watches the AQI sensor and toggles our ESP32 relay.

Go to Settings -> Automations & Scenes -> Create Automation.

Choose “Create new automation” and switch to the YAML tab. Paste the following configuration:

alias: "Auto-Control Air Purifier based on AQI"
description: "Turn on the air purifier when AQI is poor, turn it off when it's good again."
trigger:
  - platform: numeric_state
    entity_id: sensor.living_room_aqi
    above: 50
    for:
      minutes: 5
  - platform: numeric_state
    entity_id: sensor.living_room_aqi
    below: 35
    for:
      minutes: 10
condition: []
action:
  - choose:
      - conditions:
          - condition: template
            value_template: "{{ trigger.to_state.state | int > 50 }}"
        sequence:
          - service: switch.turn_on
            target:
              entity_id: switch.air_purifier_relay
            data: {}
          - service: notify.mobile_app_your_phone
            data:
              message: "Air quality is poor (AQI {{ trigger.to_state.state }}). Air purifier turned on."
      - conditions:
          - condition: template
            value_template: "{{ trigger.to_state.state | int < 35 }}"
        sequence:
          - service: switch.turn_off
            target:
              entity_id: switch.air_purifier_relay
            data: {}
          - service: notify.mobile_app_your_phone
            data:
              message: "Air quality is back to good (AQI {{ trigger.to_state.state }}). Air purifier turned off."
    default: []
mode: single

Let’s break down this automation:

  • Triggers: We have two.
    1. Trigger when AQI goes above 50 for 5 minutes. (This turns the purifier ON).
    2. Trigger when AQI goes below 35 for 10 minutes. (This turns the purifier OFF). I use a longer delay here to prevent short-cycling the purifier.
  • Actions: The choose block decides what to do based on which trigger fired.
    • If the AQI is high, it turns on the relay and sends a notification.
    • If the AQI is low, it turns off the relay and sends another notification.
💡 Pro Tip: Hysteresis is Your Friend
Notice I use two different thresholds (50 to turn on, 35 to turn off). This is called hysteresis. It prevents the automation from rapidly turning the purifier on and off if the AQI is hovering right around a single value. Tweak these numbers based on your comfort level and your purifier's effectiveness.

Save the automation, and you’re in business!

Troubleshooting and Common Pitfalls

No project is complete without a few hiccups. Here are some I ran into:

  • The relay clicks but the purifier doesn’t turn on. Double-check your high-voltage wiring if you’re using a custom cord. If you’re plugging the purifier into the relay module, ensure the module is rated for the purifier’s current (amps).
  • The ESP32 won’t connect to WiFi. Check your secrets.yaml file. The ESPhome logs (click “LOGS” on the device in the dashboard) are your best friend here.
  • The automation doesn’t trigger. Go to Developer Tools -> States and check if your sensor.living_room_aqi has a valid numeric state. Also, check the “Traces” for the automation in Settings -> Automations to see a step-by-step log of what happened.
  • The state is ‘unknown’. Your template sensor might be trying to read an attribute that doesn’t exist. Double-check the entity ID and attribute name in your configuration.yaml.

Where to Go From Here

Congratulations! You now have an automated air purifier that responds to the Home Assistant Air Quality Index. This project opens the door to so much more.

  • Add a Physical Button: Use another GPIO pin on the ESP32 to add a physical button that overrides the automation, letting you manually turn the purifier on or off.
  • Create an Energy-Saving Mode: Modify the automation to only run during certain hours of the day.
  • Build a Dashboard: Create a Lovelace dashboard card that shows the current AQI, the purifier’s status, and a history graph. It’s incredibly satisfying to watch it work.
  • Control Multiple Purifiers: Use the same principle to control purifiers in different rooms based on individual room sensors.

This project perfectly illustrates the power of Home Assistant: tying together commercial sensors, DIY hardware, and complex logic to create a truly smart home that works for you.


Frequently Asked Questions (FAQ)

Q: Can I use an ESP8266 (like a Wemos D1 Mini) instead of an ESP32? A: Absolutely! The process is identical. Just change the esp32: section in the ESPhome YAML to esp8266: and select an appropriate board like d1_mini.

Q: My air purifier has a smart plug. Can I use that instead of a relay? A: Yes, and it’s often easier! If you have a Tuya, Kasa, or other smart plug that’s already integrated into Home Assistant, you can skip the ESP32/relay hardware entirely. Just replace the switch.air_purifier_relay entity in the automation with your smart plug’s entity.

Q: What’s a good AQI threshold to use? A: This is personal, but a common guideline is: Good (0-50), Moderate (51-100), Unhealthy for Sensitive Groups (101-150). I find starting with an “ON” threshold of 50 and an “OFF” threshold of 35 provides a good balance of clean air and device longevity.

Q: Is it safe to run an air purifier automatically for long periods? A: Most modern air purifiers are designed for long runtimes. However, always consult your device’s manual. The hysteresis in our automation helps prevent the excessive wear and tear that can come from frequent on/off cycling.

Looking for more DIY smart home projects? Check out my guide on monitoring home temperature with ESP32 and Xiaomi sensors or my deep dive into setting up Zigbee2MQTT with Aqara sensors.