All writing

A battery powered soil moisture sensor with ESPHome

How I built a small sensor that lives in a flower pot, wakes up for under a second, reports soil moisture over WiFi and should run for more than a year on one 18650 cell.

I keep forgetting to water my dieffenbachia. Sometimes I water it twice in a week, then not for a month. So I built a small sensor that sits in the pot, measures how wet the soil is and sends the reading to my home server every few minutes. It runs on a single 18650 cell, spends almost all its time asleep and is awake for less than a second per reading.

This post covers all of it: the parts and why I picked them, a common flaw in cheap soil sensors and how I fixed mine with one wire, the wiring, the 3D printed case and how it goes together, and the software on the device and on the server.

The yellow 3D printed sensor case standing in the soil of a large plant pot
The finished sensor in my dieffenbachia's pot. Only the yellow case shows; the probe is in the soil underneath.

Why I built it

There are ready-made plant sensors, but I wanted something I fully control:

  • Runs on a battery for a long time. No cable to the pot.
  • Sends real numbers to my own network, not to a vendor's cloud. The data goes to an MQTT broker at home, and from there to a small plant dashboard and Home Assistant.
  • Can be set up without reflashing. WiFi, measuring interval and calibration should be changeable from a phone.
  • Looks tidy in a pot. A small round case, no loose boards.

How it works

The sensor follows the same short loop all day:

  1. Wake up from deep sleep, power the soil probe and check the battery.
  2. Connect to WiFi and the MQTT broker (about half a second).
  3. Measure soil moisture, battery and WiFi signal, publish them and wait for the broker to confirm delivery.
  4. Switch the probe off and go back to deep sleep until the next reading.
Diagram: the sensor sends readings over WiFi to an MQTT broker, which feeds a plant panel and Home Assistant
The sensor only talks to the MQTT broker. A small plant panel and Home Assistant read the measurements from there, so nothing leaves the home network.

Hardware

Only three parts do the real work: a board, a battery and the sensor itself.

LilyGO T-Energy S3 board, front with the ESP32-S3 module and back with the 18650 battery holder
LilyGO T-Energy S3. An ESP32-S3 board with an 18650 holder on the back, a charger, battery protection and a switch. It is the brain, the power supply and the charger in one piece.

I chose this board because the battery side is already solved properly. The charge chip (HX6610S) charges the cell over USB-C, a separate protection chip cuts the battery off before it is drained too far, and a buck regulator makes a clean 3.3 V. The battery voltage is wired to IO3 through a 100k/100k divider, so the firmware can read it without extra parts. There is an ON/OFF switch, BOOT and RST buttons, and the PCB antenna sits at the far end of the board, away from the battery.

The LilyGO T-Energy S3 on a desk, showing the ESP32-S3-WROOM-1 module and the two rows of header holes
My board. The ESP32-S3 module is on the left; the sensor wires go into the G, IO1 and IO2 holes in the top row, right next to it.
The T-Energy S3 held in a hand with a USB-C cable plugged in and a red LED lit
Plugged into USB-C for the first flash. The same port charges the battery later.
A blue Aspilsan INR18650 lithium-ion cell
Aspilsan INR18650 A28 (2800 mAh). The single cell that powers everything. It is an unprotected cell, which is fine here because the board has its own protection.
Capacitive Soil Moisture Sensor v2.0 with its three-wire cable
Capacitive Soil Moisture Sensor v2.0. It measures moisture through the PCB without exposed metal in the soil, so it does not corrode like the cheap two-prong resistive probes. Its output voltage drops as the soil gets wetter.

Parts list

PartQtyNoteWhere to buy
LilyGO T-Energy S3 (V1.0)1ESP32-S3, 16 MB flash, 18650 holderLILYGO store, docs on GitHub
18650 Li-ion cell1I used an Aspilsan INR18650 A28, 2800 mAh, flat topRobotistan
Capacitive Soil Moisture Sensor v2.01Check the timer chip before buying, see belowDirenc.net
M3×12 screws2Hold the sensor clamp in the caseAny hardware store
1.75 mm filament~2 cmCut into 4 pins for the clampLeftover from printing
PLA filament—For the case, cap and clamp—

What I tried before

This is not the first board I tried. Two others did not make it:

  • ESP32-C3 SuperMini: its ADC only reads up to about 2.5 V, and the sensor already gives 2.44–2.51 V in dry air. Dry soil would hit the ceiling. Its 5 V pin is also tied straight to USB, which is risky with a battery attached.
  • Seeed XIAO ESP32C6 with two 18650 cells and a separate protection board: I even designed a case for it. But the XIAO's charger does not protect the cell from deep discharge, so I would have needed extra parts. The T-Energy S3 has all of that on one board.

Choosing a soil sensor that actually works

The capacitive sensors all look the same, but many of them are built wrong. This video by Flaura explains it well: after ordering from 38 sellers, most of the sensors had at least one of three design faults.

  1. No voltage regulator. Some boards leave out the small 3.3 V regulator, and the output then moves with the supply voltage.
  2. The wrong timer chip. The sensor is built around a 555 timer. The classic NE555 needs about 4.5 V or more, so on 3.3 V it is unreliable. You want the CMOS version, marked TLC555 or TL555C.
  3. A resistor that is not connected. The 1 MΩ resistor next to the chip (R4, marked 105) should go to ground, but on many boards the trace is missing. The sensor then reacts slowly and "sticks" after it has been wet.

When buying, zoom into the product photos and read the chip marking. Mine has a TL555C and the regulator is fitted, so it works fine on 3.3 V. It did have the third problem.

Close-up of the timer chip on the sensor, marked TL555C
The chip on my sensor: TL555C, the CMOS version that works on 3.3 V. This marking is what to look for in the product photos.
An unmodified Capacitive Soil Moisture Sensor v2.0 board, model HW-390, near its connector
An unmodified sensor of the same model (HW-390). R4, marked 105, sits next to the connector, with nothing extra on it.

The fix: one small wire

The fix from the video is simple: solder a thin wire from the free end of R4 to ground, so the resistor is connected the way the design intended. I soldered a short piece of thin wire for it. It runs from R4 around the top edge of the board to the back, which is why the case leaves a little room behind the sensor.

Close-up of the sensor with a purple wire soldered to resistor R4
The fix on my sensor: the purple wire is soldered to R4 (105) and connects it to ground.

It is easy to test: put the sensor in a glass of water up to the white line, pull it out and watch the reading. With the fix, mine returns to the dry value in one or two seconds.

The sensor standing in a glass of water, wired to the board
The water test. The sensor goes into the glass only up to the white line; the electronics above it must stay dry.

These are the values my sensor gives through the ESP32-S3's ADC:

ConditionSensor voltage
In dry air2.51 V
In water, up to the white line1.14 V

The firmware maps this range to 0–100 %. In real soil the numbers sit somewhere in between, which is why the device has a calibration wizard (more on that below).

Wiring

The sensor has three wires and they go to three header holes on the board. The cable's plug stays on the sensor side; the other end is soldered straight into the holes, so nothing can shake loose in the pot.

SensorT-Energy S3What it does
GND (black)GGround
AOUT (yellow)IO1Analog moisture reading (ADC1)
VCC (red)IO2Power for the sensor
Wiring diagram: sensor GND to G, AOUT to IO1, VCC to IO2 on the T-Energy S3
Three wires. The sensor's power comes from a GPIO pin instead of the 3.3 V rail, so the firmware can switch it off completely while the board sleeps.

Powering the sensor from IO2 is the important trick. The sensor only draws a few milliamps, which a GPIO pin can supply, and it means the sensor uses nothing at all during the 99.9 % of the time the board is asleep. The firmware turns it on first thing after waking, so it has warmed up by the time WiFi is connected.

Always switch the board OFF and unplug USB before you solder or change wires.

Tools and supplies

  • Soldering iron with a fine tip, thin solder and flux
  • A short piece of thin insulated wire (for the R4 fix) and a bit of heat shrink or tape
  • Flush cutters and a wire stripper
  • A multimeter, to check the battery voltage and the sensor output
  • A 3D printer (I use a Bambu Lab A1 mini) and PLA
  • A screwdriver for the two M3 screws
  • A USB-C data cable for the first flash (a charge-only cable will not show up on the computer)

The enclosure

I designed the case in OpenSCAD, so every size is a parameter and a change is just a re-render. It is a round capsule, 53.4 mm wide and about 110 mm tall, with a screw cap.

Measuring the board with the battery fitted using a digital caliper
Measuring the board with the battery fitted. Every number like this went straight into a parameter of the model.
The board held up in front of the case model in the slicer to compare sizes
Holding the board up to the model in the slicer before printing, a quick check that it really fits inside.
Render of the closed cylindrical enclosure with grip ridges around the cap
Closed, it is just a smooth cylinder. The ridges around the cap make it easy to grip when unscrewing.
Render of the enclosure with its screw cap lifted off and the sensor probe sticking out of the bottom
The design with the cap off: the board and battery go inside, only the probe goes into the soil.

Inside, everything is stacked from front to back: the board stands upright with the antenna at the top under the plastic cap (best for the WiFi signal), the battery sits right behind it on the board, and the sensor stands behind the battery and leaves through a slot in the floor.

Cross-section render of the enclosure showing the board rail, the battery and the sensor slot in the floor
A cut through the case. The board slides down a rail on the left, the large block is the battery, and the sensor (right) goes through the floor slot. The bottom of the case sits exactly at the sensor's white line, the deepest it should go into soil.

A few details that took some iterations:

  • Screw cap. A right-hand thread with a 2.5 mm pitch, about two turns. Its flanks are at 45°, so both parts print without supports. A ring under the cap presses the board down onto its seat when you close it, so nothing rattles.
  • Board rails. The USB-C port and the switch stick out past the edge of the board, so a simple slot would catch them. The rails hold the board from the back and the sides, and a small pad at the top rests against the ESP32 module from the front.
  • The floor slot is 23.0 × 1.8 mm: just 0.2 mm larger than the sensor, so it neither squeezes nor wobbles.
  • No USB hole. An earlier version had a USB-C tunnel in the side wall, but it made the case weaker and harder to print. To charge, I unscrew the cap and lift the board out; the sensor cable is long enough for that.
A yellow test print of the bottom of the case with the board and battery standing in it
Before printing the whole case I printed only its bottom 26 mm to check how the board sits in the rails. This was an earlier version, still with the USB-C opening in the side wall.

The sensor clamp

The sensor needs to be held firmly, otherwise it moves every time I touch the pot. The sensor PCB has two notches on its edges, so I made a two-piece clamp with teeth that fit into those notches.

The first version had V-shaped teeth and the sensor still wobbled: the notches are actually trapezoids. Instead of guessing, I printed a small test comb with four teeth of different widths (4.7, 5.0, 5.3 and 5.6 mm). The 5.3 mm one fit perfectly, and that value went back into the model.

A white printed tooth sitting in the notch on the edge of the sensor board
A printed tooth sitting in the sensor's notch while testing the fit.
Assembly steps for the two-piece sensor clamp, from the printed halves to the screws in the case
How the clamp goes together: the two printed halves (1a, 1b), four short filament pins and the sensor in between (2), pressed together so the teeth sit in the notches (3), lowered into the case (4) and screwed down from above with two M3×12 screws (5).

Printing

All parts print in PLA without supports. I used 50 % infill; mine is printed in yellow.

PartOrientation
BodyUpright, floor on the bed
CapUpside down, flat top on the bed
Clamp, back halfSplit face on the bed
Clamp, front halfSplit face on the bed
Notch test comb (optional)Flat

The edges that touch the bed start with a 45° chamfer before they round off, which avoids overhangs on the first layers. The STL files and the OpenSCAD source are available for download.

Assembly

  1. Fix the sensor first (the R4 wire, if your board needs it) and solder the three wires to G, IO1 and IO2.
  2. Put the sensor in the clamp. Push four 4.5 mm pieces of 1.75 mm filament into the holes of one half, lay the sensor in, and press the other half on. The teeth must sit in the notches.
  3. Lower the clamped sensor into the case. The probe goes through the floor slot and the clamp rests on two posts in the floor.
  4. Screw the clamp down with two M3×12 screws. They are reachable with a straight screwdriver through the opening at the top.
  5. Insert the battery into the holder on the back of the board, watching the polarity.
  6. Slide the board down the rails, antenna end up, and set the switch to ON. With the switch off, the board will never wake up on battery.
  7. Screw on the cap. It pushes the board onto its seat.
  8. Push the probe into the soil up to the bottom of the case, not deeper than the white line.
Looking down into the open yellow case at the board, the battery holder and the coiled sensor cable
Looking into the open case: the board stands in its rails with the battery behind it, and the sensor cable is coiled in the space above.
The open yellow case standing in the soil with its cap lying next to it
The case open in the pot. To charge the battery, I lift the board out from here.
The closed yellow case held above the pot, with the sensor probe sticking out of the bottom
Closed and ready. Only the probe comes out of the bottom, up to the white line.

Software

The firmware is written with ESPHome on the ESP-IDF framework. The full source is on GitHub. Most of it is a YAML file, with a few C++ helper files for the parts ESPHome does not do on its own: the settings page, saved settings and the diagnostic counters.

Measuring and sleeping

The sensor reading is an ADC value that a filter turns into a percentage using the calibrated dry and wet voltages:

output:
  - platform: gpio
    pin: GPIO2          # sensor power, switched off during sleep
    id: sensor_power

sensor:
  - platform: adc
    pin: GPIO1
    id: soil_raw
    name: "Soil Raw Voltage"
    attenuation: 12db
    samples: 16
    update_interval: never   # only measured when the loop asks for it

  - platform: copy
    source_id: soil_raw
    id: soil_moisture
    name: "Soil Moisture"
    unit_of_measurement: "%"
    device_class: moisture
    filters:
      - lambda: 'return moisture_percent(x);'   # dry voltage = 0 %, wet voltage = 100 %
// Dry and wet voltages come from the calibration saved on the device
inline float moisture_percent(float v) {
  float p = (settings.dry_v - v) / (settings.dry_v - settings.wet_v) * 100.0f;
  return p < 0 ? 0 : (p > 100 ? 100 : p);
}

Before WiFi even starts, the board checks the battery. If the cell is getting low, it does not risk draining it further and sleeps for a whole day:

esphome:
  on_boot:
    - priority: 590            # before WiFi
      then:
        - output.turn_on: sensor_power
        - component.update: battery_voltage
        - if:
            condition:
              lambda: 'return battery_voltage->state < 3.40;'
            then:
              - output.turn_off: sensor_power
              - deep_sleep.enter:
                  id: sleep_ctl
                  sleep_duration: 24h

Getting from 5.5 seconds to 0.8

The first version was awake for about 5.5 seconds per reading. Every second awake costs battery, so I went through the wake-up step by step. The final version is awake for about 0.8 seconds, and most of the gain came from four things:

  • MQTT waited five seconds for nothing. ESPHome's MQTT client only makes its first connection attempt five seconds after boot. Starting it disabled and enabling it the moment WiFi connects removed almost all of that.
  • The first WiFi attempt always failed. On every boot the ESP32's first connection attempt got "Authentication Failed" and the second one worked in about 70 ms. The default reaction to a failed attempt is a full scan of all channels (about 2.6 s). Listing the same network twice, with its access point address and channel fixed, makes ESPHome try the second entry right away instead of scanning.
  • A static IP, so there is no DHCP round trip. It has to be outside the router's DHCP range; my first choice was inside it, another device got the same address, and readings went missing for a day until I found it.
  • No serial log and no mDNS in the final build. Logging to USB slowed the boot when no computer was attached.
wifi:
  networks:
    # The same network twice: if the first attempt fails, the second entry
    # is tried immediately instead of scanning all channels.
    - ssid: !secret wifi_ssid
      password: !secret wifi_password
      bssid: "AA:BB:CC:DD:EE:01"
      channel: 2
    - ssid: !secret wifi_ssid
      password: !secret wifi_password
      bssid: "AA:BB:CC:DD:EE:01"
      channel: 2
  fast_connect: true
  manual_ip:
    static_ip: 192.168.1.50   # outside the router's DHCP range
    gateway: 192.168.1.1
    subnet: 255.255.255.0
  on_connect:
    - mqtt.enable              # connect to MQTT right away, not after 5 s

mqtt:
  broker: !secret mqtt_broker
  enable_on_boot: false
  log_topic: null

logger:
  baud_rate: 0                 # no USB logging in normal use

Making sure the data arrived

For a while the logs looked fine but some readings never arrived. The board published its values, waited a fixed 300 ms and went to sleep. With a weak signal, a lost packet needs to be sent again, and the board was already asleep by then.

Now the board publishes one extra message to its own topic with QoS 1 and waits until the broker sends it back. Because everything goes over the same connection, once that message comes back, all earlier ones have arrived too. If it does not come back within three seconds, the board reconnects and sends everything again. If that also fails, it tries again after five minutes instead of waiting for the next full interval.

script:
  - id: wait_for_delivery
    then:
      - lambda: 'id(delivered) = false;'
      - mqtt.publish:
          topic: soil-sensor/delivered
          payload: !lambda 'return to_string(rtc_diag.wakeups);'
          qos: 1
      - wait_until:
          condition:
            lambda: 'return id(delivered);'   # set when the message comes back
          timeout: 3s

The board also keeps a few counters in RTC memory, which survives deep sleep: wake-ups, missed readings, total errors and the reason for the last failure (WiFi, MQTT, dropped connection or no delivery). When something goes wrong, these show whether it was the WiFi, the broker or the signal.

Two traps with updates over WiFi

  • New firmware was rolled back silently. ESPHome marks a new firmware as good after 60 seconds, but this board is asleep long before that. The bootloader then assumed the update had failed and went back to the old version. Setting safe_mode: boot_is_good_after: 10s and marking every successful cycle as good fixed it.
  • The board is asleep almost all the time, so it is not there to receive an update. That is what the settings mode is for.

The settings page on the device

Changing WiFi or the measuring interval should not need a laptop and a USB cable. So the sensor has a settings mode with its own small web page. It can be started in three ways:

  • press the BOOT button: it wakes the board straight into settings mode
  • send a one-time ON message to its MQTT settings topic: the board picks it up on its next wake-up and clears it, so it only happens once
  • if it fails to reach WiFi three times in a row, it opens its own setup network for a phone to connect to

In settings mode the board stays awake for ten minutes (extended by every request) and serves the page.

The device settings page showing soil moisture, battery voltage, WiFi signal and a live chart
The top of the settings page: soil moisture, battery and WiFi signal, refreshed every few seconds, with a live chart. Useful when pushing the sensor into the pot or trying a different spot for a better signal.

I did not use ESPHome's built-in web server and entities for this on purpose. Every entity would also be published to MQTT on every wake-up, including the WiFi password field. Instead, the page is a single HTML file (about 6 KB gzipped) compiled into the firmware, with a small JSON API next to it. The settings are saved on the device and the web server only runs in settings mode.

From the page I can change the WiFi network (with a scan of nearby networks), the MQTT server, the measuring interval (5 minutes to 4 hours), the low-battery limit and the plant's name, see the diagnostic counters, upload new firmware with a progress bar, and restart or reset the device.

A new WiFi setting is tried before it is kept: if the sensor cannot reach the MQTT broker within 45 seconds, it goes back to the old setting and shows a warning on the page. That saved me once already, when one access point in the house turned out not to pass traffic to the rest of the network.

The calibration step of the settings page with the current dry and wet voltages and two calibration methods
The calibration wizard. The recommended method uses the pot itself: "dry" is soil that needs watering, "wet" is 10–15 minutes after watering. Then 0 % means "water now" and 100 % means "just watered", which is more useful than air and water.

The wizard takes several readings for each point, rejects them if the value is still moving or the sensor seems unplugged, and only saves at the end. If I stop halfway, the old values stay.

The plant panel

On the server side, a small Docker service listens to the MQTT topics, stores every reading in SQLite and shows them on a web page. It is a FastAPI app with no external dependencies in the browser, so it also works without internet.

A card on the plant panel showing the plant photo, its moisture percentage and a small trend line
Each sensor gets a card with the plant's photo, the latest moisture value, a small 24-hour trend, battery and signal. A new sensor shows up by itself as soon as it sends its first reading.
The detail page of a plant with its photo, description, moisture value, battery, WiFi signal and a switch for settings mode
The detail page has charts for 24 hours, 7 days and 30 days, a description of the plant and a switch that sends the sensor into settings mode on its next wake-up, so I don't have to press the BOOT button inside the case.

The same readings also reach Home Assistant through MQTT discovery. To keep the wake-ups short, the discovery messages are only sent after a power-up and then about twice a day, not on every reading.

Results

A tall dieffenbachia in a dark green pot with the yellow sensor in the soil
The plant that started all this, with its new sensor.
  • Awake time: about 0.8 seconds per reading, of which about 0.5 seconds is connecting to MQTT.
  • Battery: in the first days the voltage barely moved. My rough estimate at a 30-minute interval is around 3.5 mAh per day including the cell's own self-discharge, which would be about a year and a half on a 2800 mAh cell. I have not measured the sleep current yet, so this is an estimate; the battery chart over the next weeks will tell.
  • Reliability: after fixing the IP conflict and adding the delivery check, the misses I still see have a clear cause in the counters, like the broker's computer being asleep.

What's next

  • Waterproof the sensor's electronics. The part above the white line and the PCB edges should get a coat of nail polish or epoxy before the sensor spends months in damp soil.
  • Calibrate in real soil over a few watering cycles, instead of the air and water values it uses now.
  • Move to Home Assistant's MQTT broker, which is always on, and link the plant to OpenPlantbook for its ideal moisture range. The goal is a "days until watering" estimate based on how fast the soil dries out.
  • Test the setup network path with a phone; it is in the firmware but I have not needed it yet.

Source and files