Smart home

Automatic irrigation ESP32 ESPHome

Water by soil moisture: ESP32-C6, probe, 12/24 V valve, ESPHome, fail-safe limits and Home Assistant. Parts list, GPIO wiring, ESPHome YAML and Home Assist

Updated · Emmanuel SAUVAGE

  • LevelAdvanced
  • Time3–5 h
  • Budgetabout £35–70 depending on the seller and valve

Rough estimate, check with your seller: prices vary by shop and period.

Project goal

You will open a solenoid valve, a valve that an electric current opens or closes, to water a flower bed or a vegetable garden, close it again automatically and decide when to water according to the time and the soil moisture. Home Assistant, the software that gathers your connected devices, gives the order to an ESP32, a small electronic board with Wi-Fi, which drives a relay, an electric switch. The whole circuit around the relay stays low voltage: the 230 V mains is used only inside a ready-made, certified adapter.

Why build it

A timed watering schedule wastes water when it has rained. With a soil moisture reading, Home Assistant opens the valve only when the soil is really dry, and the valve closes by itself after a maximum duration, even if the Wi-Fi goes down. You save water and avoid a watering that never stops.

Useful terms for this project: ESP32 (small Wi-Fi board) · ESPHome (prepares the board’s program) · GPIO (the board’s pins) · OTA (update without a USB cable)

Prerequisites

  • Home Assistant with ESPHome, and Wi-Fi covering where the valve sits (or an outdoor access point).
  • A normally closed 12 V DC or 24 V AC solenoid valve (matching your irrigation network), with its datasheet: voltage, current and minimum pressure.
  • A CE/UKCA-marked mains adapter with the same voltage as the valve and a current above the valve’s.
  • A waterproof enclosure (IP65 or better) for the electronics, and compliant plumbing (a check valve if the network connects to drinking water).

Diagrams

Wiring diagram : Automatic irrigation
Wiring diagram : Automatic irrigation5V → Relay module VCC; GND → Relay module GND; GPIO18 → Relay module IN; 3V3 → Soil moisture probe VCC; GND → Soil moisture probe GND; GPIO2 → Soil moisture probe AOUTESP32-C6 DevKitC-1Relay module5VVCCGNDGNDGPIO18INSoil moisture probe3V3VCCGNDGNDGPIO2AOUTPowerGround (GND)ControlData or signal
Principle diagram : Automatic irrigation
Principle diagram : Automatic irrigationHome Assistant → ESP32-C6 + ESPHome → Relay + solenoid valveHome AssistantSchedule, soil moisture, weatherOpens the valve then closes it2.4 GHz Wi-Fi + encrypted APIESP32-C6 + ESPHomeReads the moisture probe (GPIO2)Drives the relay (GPIO18), 20 min safety stopGPIO18 signal, 5 V relay coilRelay + solenoid valveThe relay only switches the valve’s low-voltage circuitCE-marked 12 V or 24 V adapter

Parts list

This ESP32 board is the base for every project in the series. ESPHome also works with other ESP32 boards: the board-choice guide helps you compare them. Which ESP32 board to choose?

ESP32-C6-DevKitC-1

Suggested board

ESP32-C6-DevKitC-1

check with the seller
  • Wi-Fi 6, Bluetooth 5, Zigbee and Thread (at hardware level)
  • Supported by ESPHome (ESP-IDF framework)
  • USB-C for flashing and power

Watch-outs

  • 2.4 GHz Wi-Fi only
  • Use a USB cable that carries data

Main components

ItemQuantityRole and precautions
ESP32-C6-DevKitC-11Control board (see the box above).
1-channel optocoupler relay module, 5 V coil1Pick a model whose IN input works with a 3.3 V signal and whose contacts handle the valve’s voltage and current.
Normally closed solenoid valve 12 V DC or 24 V AC1Match your installation’s voltage. Check minimum operating pressure and fitting size.
Low-voltage CE-marked mains adapter (12 V DC or 24 V AC)1Same voltage as the valve; current above the valve’s. Sealed block, never opened or modified.
Capacitive soil moisture probe (v1.2 type)1Analog output; lasts longer than a resistive probe. Keep the probe’s electronics out of the soil.
1N4007 diode (DC valve only)1Fitted in reverse across the valve to absorb voltage spikes when the relay opens.
In-line fuse holder and a fuse sized for the valve1Protects the valve wiring in case of a short circuit.

Small parts

ItemQuantityRole and precautions
USB-C data cable1For flashing and power. Charge-only cables do not carry data.
USB 5 V power supply (CE/UKCA-marked charger)1At least 1 A for the board alone; more if peripherals draw power from it.
Dupont jumper wires (male-female and female-female)1One mixed pack covers every prototype.
Low-voltage screw terminals or lever connectors1To connect sensor or dry-contact wires cleanly.
Heat-shrink tubing1Insulates solder joints and splices; avoid tape in a permanent build.
Vented plastic or 3D-printed enclosure1Protects the board; leave a cable gland and vents if the sensor measures air.

Amazon links are affiliate links: the site may earn a commission at no extra cost to you.

Step-by-step build

Step 1. Prepare ESPHome and create the device

  1. In Home Assistant, open the ESPHome Device Builder add-on (see the tutorial “Install ESPHome in Home Assistant (Device Builder)”). ESPHome is the software that turns a simple settings file into the program for your ESP32 board, without you having to write any code.
  2. Open “Secrets” (top right): this file keeps your passwords apart, so you can share your configurations without revealing them. Check that wifi_ssid (the name of your Wi-Fi network), wifi_password, api_encryption_key (the key that encrypts the link with Home Assistant), ota_password (for updates without a cable) and ap_password (for the board’s fallback Wi-Fi network) exist, and add any missing line. A valid API key is a long 32-byte string encoded in base64, which you can generate with “openssl rand -base64 32”.
  3. Click “New device”, name it “arrosage-auto”, pick ESP32-C6, skip the flash for now, then replace the file content with the YAML from this page (“Edit”). YAML is a configuration file written in plain text: it describes, line by line, what the board must do.

What you should see: The file opens in the editor with syntax highlighting and no red underline.

Check: The “Validate” action (⋮ menu) answers “Configuration is valid”.

Step 2. Wire the relay on the control side

  1. With the USB power unplugged, connect the three wires on the “control” side of the relay, the side the board drives: VCC (the module’s power) to the board’s 5V pin, GND (the ground) to a GND pin and IN (the order wire) to GPIO18, one of the metal pins lined up along the edge of the board, called GPIO.
  2. Leave the relay’s contact terminals free for now: nothing is connected to the valve yet.

What you should see: The board has only three wires to the relay; no adapter is plugged in.

Check: IN is on GPIO18 and VCC on 5V, not on 3V3.

Step 3. Flash the board and add it to Home Assistant

  1. Connect the board to your computer with the USB-C data cable: “flashing” means writing the program into the board’s memory, and this first write must be done over a cable. The board can already be wired or sitting on the breadboard, but any external peripheral with its own power supply must stay switched off.
  2. In ESPHome click “Install”, then “Plug into this computer” (Chrome or Edge over HTTPS) or “Manual download” and upload the file with ESPHome Web (web.esphome.io). If the port is missing, follow the flashing tutorial.
  3. After the reboot open Settings → Devices & services: the ESPHome device is discovered; click “Configure” and paste the API encryption key.

What you should see: The “Logs” show the Wi-Fi connection and then “Successfully connected to Home Assistant”.

Check: The device appears under Devices & services → ESPHome with its entities; later updates need no cable and go over Wi-Fi (this is OTA, “Over The Air”).

Step 4. Connect the valve to the low-voltage circuit

  1. Before connecting anything to the valve, check that the relay obeys. In Home Assistant, turn on the “Irrigation valve” switch: the relay must click, then release when turned off (if not, toggle “inverted” in the YAML file and reinstall).
  2. Unplug the mains adapter from the outlet.
  3. On one adapter wire, go through the relay: adapter (+ or one of the two output conductors) → COM terminal, NO terminal → one valve wire; the other valve wire goes straight back to the adapter.
  4. With DC, fit the 1N4007 in reverse (stripe toward +) across the valve; put the fuse on the supply wire.
  5. Insulate every connection with heat-shrink or a terminal block, then plug the adapter back in.

What you should see: The valve stays closed while the relay is at rest.

Check: Turn the switch on for 5 seconds: the valve opens with a small click, then closes when switched off.

Step 5. Install the probe and calibrate moisture

  1. Connect the soil moisture probe: VCC (its power) to 3V3, GND (the ground) to GND and AOUT (its analogue output, a voltage that varies with the moisture) to GPIO2.
  2. Read “Soil moisture” with the probe in air (dry value), then with the blade in a glass of water (wet value): note both voltages in the ESPHome log.
  3. Replace 2.60 and 1.20 in calibrate_linear with your measurements, then reinstall over OTA.

What you should see: Moisture goes from about 0 % in air to about 100 % in water.

Check: Push the probe into watered then dry soil: the value changes consistently.

Step 6. Create the watering automation

  1. An automation is an “if… then…” rule that Home Assistant applies by itself. Open Settings → Automations & scenes → Create automation.
  2. Trigger: a morning or evening time. Condition: soil moisture below your threshold (for example 35 %). Action: turn on “Irrigation valve”, wait the chosen duration, then turn it off.
  3. Run it by hand and measure how long a proper watering takes.

What you should see: The valve opens at the planned time only if the soil is dry.

Check: Simulate a failure: cut Wi-Fi during watering; the valve must close by itself after 20 minutes.

ESPHome code (YAML)

YAML is a configuration file written in plain text: it tells ESPHome what the board must do. Paste this one into ESPHome after creating the device. It targets an ESP32-C6 board; values to personalise are marked with “CHANGE” comments.

esphome:
  name: arrosage-auto
  friendly_name: Automatic irrigation

esp32:
  board: esp32-c6-devkitc-1   # XIAO ESP32C6: use board: seeed_xiao_esp32c6
  framework:
    type: esp-idf             # required for ESP32-C6

logger:                       # serial logs, also visible over Wi-Fi

api:
  encryption:
    key: !secret api_encryption_key

ota:
  - platform: esphome
    password: !secret ota_password

wifi:
  ssid: !secret wifi_ssid       # 2.4 GHz network only
  password: !secret wifi_password
  ap:                           # fallback hotspot if the Wi-Fi is unreachable
    ssid: "arrosage-auto fallback"
    password: !secret ap_password

captive_portal:

switch:
  - platform: gpio
    id: valve_relay
    name: "Irrigation valve"
    icon: mdi:sprinkler
    pin:
      number: GPIO18
      inverted: false            # many relay boards are active-LOW: set true if the logic is reversed
    restore_mode: ALWAYS_OFF     # the valve stays closed after a reboot or power cut
    on_turn_on:
      - delay: 20min             # hard stop, even if Wi-Fi or Home Assistant is down
      - switch.turn_off: valve_relay

sensor:
  - platform: adc
    id: soil_moisture
    name: "Soil moisture"
    pin: GPIO2
    attenuation: 12db
    update_interval: 60s
    unit_of_measurement: "%"
    accuracy_decimals: 0
    filters:
      - median:
          window_size: 5
          send_every: 1
      - calibrate_linear:
          - 2.60 -> 0.0          # CHANGE: voltage with the probe dry (in air)
          - 1.20 -> 100.0        # CHANGE: voltage with the probe in water
      - clamp:
          min_value: 0
          max_value: 100

  - platform: wifi_signal
    name: "WiFi signal"
    update_interval: 120s
    entity_category: diagnostic

YAML comments are in English, as in the ESPHome documentation. This code has not been run on your hardware: use “Validate” before flashing and adjust pins and names.

Home Assistant integration

  • The “Irrigation valve” switch and the “Soil moisture” reading become standard entities: add them to a dashboard, calendar or automation.
  • Combine the moisture condition with a rain forecast (weather integration) to avoid watering before a storm.
  • Set an alert if the valve stays open longer than planned: a notification on the entity in the “on” state for more than 25 minutes.

Common problems and troubleshooting

SymptomFix
The relay clicks but the valve does not openCheck the adapter’s voltage and current, the valve’s minimum water pressure, and that the wires go through COM and NO.
The valve stays openThe relay is stuck or the logic is inverted. Unplug the adapter and close the water supply, then check “inverted” and the relay.
Moisture value keeps jumpingThe probe is badly powered or the ground floats. Check the common GND, keep wires short and keep the median filter on.
The valve opens briefly at bootSome relay modules energise for a moment while the board starts. Fit a manual safety valve on the water inlet.

FAQ

Can I drive a 230 V valve?

Not in this project: 230 V must not be wired DIY. Choose a low-voltage valve, or have an electrician do the connection.

Relay or smart plug?

A smart plug controlled by Home Assistant is simpler for a low-voltage adapter, but the ESPHome relay adds the local safety timeout if Wi-Fi drops.

What about winter?

Drain the pipes and the valve before frost, otherwise the water can crack them.

Related tutorials

These step-by-step guides explain the gestures common to every project in the series.

Other ESP32 projects

Sources and documentation

Cette page vous a-t-elle été utile ?

Have a question about this guide or need advice? Ask us here

Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.