Built-in project · ESP32-C3-DevKitM-1

Plant sensor for Home Assistant on an ESP32-C3

A capacitive soil sensor mapped between two calibration readings, a light level, and a thirsty LED with two thresholds so it does not flicker, on an ESP32-C3. The whole build, an ESP32-C3 and 4 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.

Teaching? Assign it to your class in one click.

Beginner About 20 minutes to build and run. Runs in your browser. Free, and no account needed.

The parts retail for about $15.45. On Mokxi they're free.

The circuit runs here once the page has loaded.

What you'll learn

  • Calibrating a sensor with two measured readings
  • Mapping raw ADC values to a percent
  • Using two thresholds so an alarm does not flicker
  • Averaging several samples to reduce noise
  • Serving sensor data as JSON
  • Difficulty: Beginner
  • Time: About 20 minutes
  • Board: ESP32-C3-DevKitM-1
  • Parts: 6

How it works

A capacitive soil sensor on pin 3 and a light module on pin 4 are read every 5 seconds. The soil reading is mapped between two calibration numbers, DRY_RAW for dry air and WET_RAW for water, into 0 to 100 percent. The light reading is flipped so bigger means brighter.

When moisture falls below 30 percent the red LED on pin 19 lights. It stays on until moisture rises above 40 percent. The sketch prints what it would publish and serves the state as JSON at /state, since Mokxi has no MQTT broker.

Wiring table

Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.

Part and pinConnects to
Photoresistor sensor module pin GNDESP32-C3-DevKitM-1 pin GND
Soil moisture sensor, capacitive pin GNDESP32-C3-DevKitM-1 pin GND
Photoresistor sensor module pin VCCESP32-C3-DevKitM-1 pin 3V3
Soil moisture sensor, capacitive pin VCCESP32-C3-DevKitM-1 pin 3V3
Soil moisture sensor, capacitive pin AOUTESP32-C3-DevKitM-1 pin 3
Photoresistor sensor module pin AOESP32-C3-DevKitM-1 pin 4
LED, red pin CESP32-C3-DevKitM-1 pin GND
Resistor, 220 Ω pin 1ESP32-C3-DevKitM-1 pin 19
LED, red pin AResistor, 220 Ω pin 2

The code

The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.

sketch.ino · ESP32-C3-DevKitM-1
// Home Assistant plant sensor: soil moisture and light, calibrated, with a thirsty alarm.
//
//   capacitive soil sensor on GPIO 3   wetter soil reads LOWER, which surprises everyone once
//   light module on GPIO 4             the LDR board's analog output, brighter reads lower
//   red LED on GPIO 19                 lights while the plant needs water
//
// A plant sensor is mostly calibration. The raw number means nothing until you
// have measured two points with your own sensor: the stake in dry air and the
// stake in a glass of water. Put those two readings in DRY_RAW and WET_RAW and
// the sketch maps everything between them to 0 to 100 percent, the same job
// ESPHome's calibrate_linear filter does.
//
// The thirsty alarm uses two thresholds, not one, so a reading that hovers near
// the line does not switch it on and off every few seconds.
//
// A battery sensor would read once and deep sleep for many minutes. Here it reads
// every 5 seconds so you can watch it, and stays awake. Mokxi has no MQTT broker:
// the sketch prints what it would publish and serves JSON at /state.

#include <WebServer.h>
#include <WiFi.h>

const int SOIL_PIN = 3;
const int LIGHT_PIN = 4;
const int THIRSTY_LED_PIN = 19;

// Your sensor's two calibration readings (0 to 4095 on the ESP32-C3).
const int DRY_RAW = 3706;  // in air
const int WET_RAW = 1854;  // in water
const int THIRSTY_BELOW = 30;  // percent
const int HAPPY_ABOVE = 40;    // percent

const unsigned long READ_EVERY_MS = 5000;

WebServer server(80);
int moisture = 0;
int lightLevel = 0;
bool thirsty = false;
unsigned long lastRead = 0;

void publish(const char *topic, int value) {
  Serial.print("publish home/plant/");
  Serial.print(topic);
  Serial.print(' ');
  Serial.println(value);
}

// The average of a few readings: a single ADC sample is noisy on real hardware.
int readAverage(int pin) {
  long total = 0;
  for (int i = 0; i < 8; i++) total += analogRead(pin);
  return total / 8;
}

void readPlant() {
  int raw = readAverage(SOIL_PIN);
  moisture = constrain(map(raw, DRY_RAW, WET_RAW, 0, 100), 0, 100);
  // The light module reads lower in more light; flip it so bigger means brighter.
  lightLevel = map(readAverage(LIGHT_PIN), 4095, 0, 0, 100);

  Serial.print("soil raw ");
  Serial.print(raw);
  Serial.print(" -> ");
  Serial.print(moisture);
  Serial.println("%");
  publish("moisture", moisture);
  publish("light", lightLevel);

  if (!thirsty && moisture < THIRSTY_BELOW) {
    thirsty = true;
    Serial.println("publish home/plant/thirsty ON");
  } else if (thirsty && moisture > HAPPY_ABOVE) {
    thirsty = false;
    Serial.println("publish home/plant/thirsty OFF");
  }
  digitalWrite(THIRSTY_LED_PIN, thirsty ? HIGH : LOW);
}

void sendState() {
  String json = "{\"moisture\":";
  json += String(moisture);
  json += ",\"light\":";
  json += String(lightLevel);
  json += ",\"thirsty\":";
  json += thirsty ? "true" : "false";
  json += "}";
  server.send(200, "application/json", json);
}

void setup() {
  Serial.begin(115200);
  pinMode(THIRSTY_LED_PIN, OUTPUT);

  Serial.println("Plant sensor: simulated WiFi, no MQTT broker in Mokxi.");
  WiFi.begin("Mokxi-Lab", "breadboard");
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
  }
  Serial.print("online at http://");
  Serial.print(WiFi.localIP());
  Serial.println("/state");
  server.on("/", sendState);
  server.on("/state", sendState);
  server.begin();
  readPlant();
  lastRead = millis();
}

void loop() {
  server.handleClient();
  if (millis() - lastRead >= READ_EVERY_MS) {
    lastRead = millis();
    readPlant();
  }
  delay(10);
}

Code walkthrough

The key functions of the sketch, and what each one does.

readAverage sketch.ino

Reads a pin 8 times and returns the average. One ADC sample is noisy on real hardware, so averaging gives a steadier number.

// The average of a few readings: a single ADC sample is noisy on real hardware.
int readAverage(int pin) {
  long total = 0;
  for (int i = 0; i < 8; i++) total += analogRead(pin);
  return total / 8;
}

readPlant sketch.ino

Averages the soil pin, maps it from DRY_RAW..WET_RAW to 0 to 100 and clamps it. It reads the light the same way, prints and publishes both, then updates the thirsty flag: on below THIRSTY_BELOW, off above HAPPY_ABOVE. The LED follows the flag.

void readPlant() {
  int raw = readAverage(SOIL_PIN);
  moisture = constrain(map(raw, DRY_RAW, WET_RAW, 0, 100), 0, 100);
  // The light module reads lower in more light; flip it so bigger means brighter.
  lightLevel = map(readAverage(LIGHT_PIN), 4095, 0, 0, 100);

  Serial.print("soil raw ");
  Serial.print(raw);
  Serial.print(" -> ");
  Serial.print(moisture);
  Serial.println("%");
  publish("moisture", moisture);
  publish("light", lightLevel);

  if (!thirsty && moisture < THIRSTY_BELOW) {
    thirsty = true;
    Serial.println("publish home/plant/thirsty ON");
  } else if (thirsty && moisture > HAPPY_ABOVE) {
    thirsty = false;
    Serial.println("publish home/plant/thirsty OFF");
  }
  digitalWrite(THIRSTY_LED_PIN, thirsty ? HIGH : LOW);
}

sendState sketch.ino

Builds a small JSON text with moisture, light and thirsty, and sends it as the web answer for / and /state.

void sendState() {
  String json = "{\"moisture\":";
  json += String(moisture);
  json += ",\"light\":";
  json += String(lightLevel);
  json += ",\"thirsty\":";
  json += thirsty ? "true" : "false";
  json += "}";
  server.send(200, "application/json", json);
}

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • The moisture percent looks wrong This project
    Measure your own sensor in dry air and in a glass of water, and put those readings in DRY_RAW and WET_RAW.
  • Wetter soil makes the raw number go down This project
    That is normal for a capacitive sensor. The calibration handles it, which is why DRY_RAW is the larger number.
  • The digital output never changes, or is always on, no matter the light. Photoresistor sensor module
    Turn the trimmer on the module until DO flips at the light level you want. The digital output is set by that threshold, and which direction means bright depends on the board.
  • Analog readings go down when it gets brighter, and the code expects the opposite. Photoresistor sensor module
    The LDR sits in a divider, so the direction depends on how the module is built. Print the raw value in the light and dark, then flip it in code with 1023 minus the reading if needed.
  • The reading seems backward: wet soil gives a lower number. Soil moisture sensor
    A capacitive sensor reads lower when wetter. Measure it in dry air and in a glass of water, then map those two values to 0 and 100 percent.
  • The reading is unstable or the sensor corrodes. Soil moisture sensor
    Keep the electronics above the soil line and do not submerge past the marked line. Power it from 3.3 V or 5 V as the board allows, and average several readings.
  • The LED is dim, burns out, or the pin reads wrong because the resistor value is off. Resistor
    Read the color bands again. A 220 ohm to 330 ohm resistor suits a typical LED on 5 V. 10k is a common pull-up or pull-down value. Check with a multimeter if unsure.
  • A pull-up or pull-down resistor is missing, so the input floats and reads random values. Resistor
    Tie the input to 5 V or ground through about 10k. Or use INPUT_PULLUP and wire the switch to ground.

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.