Skip to content
Martin Mwiti
All documentation

Hydroponics Control System

Hardware and firmware architecture of an ESP32/Zephyr grow controller with per-vegetable growth profiles, closed-loop climate control, and a command/queue actuator model.

ESP32Zephyr RTOSCI2CPWMRS-485UARTView project

Overview

The hydroponics controller is a single ESP32 running Zephyr RTOS. It is responsible for the entire grow loop on-device: sample the environment, decide what the plant needs, and drive the actuators — without depending on a network connection to keep the plants alive.

Control is organized around two ideas:

  1. A profile per vegetable. A profile is a table of growth stages, and each stage carries the setpoints the plant needs at that point in its life. Selecting a profile hands the controller a schedule it can run unattended.
  2. Everything is a payload on a queue. Regulator and growth logic never touch hardware directly. They build a small ActuatorPayload_t and push it onto a Zephyr message queue; a single low-priority actuator thread owns the hardware and executes commands.

This decoupling is what makes it possible to add a sensor or replace an actuator without rewriting the control logic.

sensors_thread ──┐
                 ├──► sensorData (mutex) ──► temp_regulation_thread ──┐
AHT20 (I2C) ─────┘                              growth_control_thread ─┤
                                                                      ▼
                                                        actuators_msgq (k_msgq)
                                                                      │
                                                          actuators_thread
                                                                      │
        ┌─────────┬──────────┬──────────┬───────────┬─────────────┐
      Light     Heater    Humidifier  Inlet fan   Outlet fan    (future)

Hardware Design

The controller is an ESP32 DevKitC. The board overlay in the repo (boards/esp32_devkitc.overlay) maps each peripheral to a devicetree node, so the firmware addresses hardware by name rather than by hard-coded pin.

Sensors

PeripheralInterfaceAddress / PinsPurpose
AHT20/AHT10I²C00x38, SDA GPIO21, SCL GPIO22Ambient temperature and relative humidity
CS5490UART1TX GPIO19, RX GPIO18, 115200 baudAC voltage, current, power, and energy metering
RS-485 probesUART2TX GPIO17, RX GPIO16, 9600 baudWater-side sensor bus (pH, conductivity) for the nutrient loop

Actuators

PeripheralInterfacePinsNotes
Grow light4 × GPIOpower 14, on/off 27, brightness 12, color 13Controls an off-the-shelf LED fixture by emulating its button presses
HeaterGPIO relayGPIO5Switching relay for the heating element
HumidifierGPIOGPIO4Timed pulses for humidity control
Inlet fanPWM (LEDC ch0)GPIO1525 kHz PWM, 0–100 % duty
Outlet fanPWM (LEDC ch1)GPIO2325 kHz PWM, 0–100 % duty

Status and UI

PeripheralInterfacePins
Status LEDGPIOGPIO2
Display (planned)SPI3 ST7789VSCLK 26, MOSI 25, MISO 34, CS 33, DC 32, RESET 2

Fans use a 40 µs PWM period (25 kHz), which is inaudible and keeps the motors off the audible switching band. The grow light is not wired to the MCU directly — the controller drives the fixture's existing buttons with opto-isolated/level-shifted outputs, which avoids modifying the light's mains-side electronics.

Firmware Architecture

Threads

Zephyr preemptive threads with fixed priorities. Lower numbers are higher priority; the sensor and temperature threads can preempt the actuator thread at any time.

ThreadPriorityStackPeriodResponsibility
sensor_thread11024 B1 sRead the AHT20, filter, and publish sensor state
temp_regulation_thread21024 B1 sTemperature FSM + PID, drives heater and fans
growth_control_thread31024 B1 minRuns the vegetable profile and stage transitions
actuators_thread5512 Bevent-drivenOwns hardware, consumes the actuator queue

main() simply starts the threads and idles; it holds no control logic.

Inter-thread communication

  • actuators_msgq — k_msgq of ActuatorPayload_t, depth 5. The single command channel into the actuator thread.
  • sensor_data_msgq — k_msgq of SensorData_t, depth 10. Available for telemetry consumers.
  • g_sensor_state_mutex — guards the shared sensor snapshot and setpoints.
  • actuators_context_mutex — guards the shared actuator context (current light, fan, heater, and humidifier state).
  • g_sensor_state_sem — signalled whenever sensor data or setpoints change, for event-driven regulators.

Actuator command model

All commands share one tagged union, so any producer can enqueue any action without knowing how it is implemented:

typedef struct {
    ActuatorType_t actuator;   /* LIGHT, HUMIDIFIER, HEATER, FAN */
    ActuatorData_t data;       /* union of command payloads */
} ActuatorPayload_t;
 
typedef union {
    LightControls_t   lightControls;   /* power, on/off, brightness, color */
    FanControls_t     fanControls;     /* inlet/outlet + speed % */
    bool              heaterState;
    HumidifierTimeMs_t humidifiertimeMs;
} ActuatorData_t;

Small builder functions (buildLightBrightnessPayload, buildInletFanSpeedPayload, buildHeaterStatePayload, …) construct payloads so control code stays declarative. The actuator thread switches on payload.actuator and dispatches to the driver, de-duplicating against the current context so redundant commands are ignored.

Sensor Pipeline

The AHT20 driver (sensors/aht10.c) talks I²C directly: it triggers a measurement, waits for conversion, reads 6 bytes, and decodes the 20-bit humidity and temperature words. aht10_read() is called once per second from the sensor thread.

sensor_services.c cleans up the raw stream before it reaches the regulator:

  • Moving average over a 10-sample window (TEMP_AVG_WINDOW).
  • Outlier rejection — a sample more than 2.0 °C from the running average is discarded (TEMP_OUTLIER_THRESHOLD).
  • Rate of change — the change in average temperature per second, used by the regulator to tell a real trend from noise.

Filtered values are written to a single mutex-protected SensorData_t:

typedef struct {
    float temp_instant;       /* °C */
    float temperature_avg;    /* °C */
    float change_rate;        /* °C per second */
    float humidity;           /* % RH */
    float ac_voltage;         /* V   */
    float ac_current;         /* A   */
    float instant_power;      /* W   */
    float energy_consumed;    /* kWh */
    float water_pH;           /* pH  */
    float water_conductivity; /* µS/cm */
    int64_t timestamp_ms;
} SensorData_t;

The matching SensorSetpoints_t stores the active targets (temperature, humidity, water pH, and water conductivity), with defaults of 25 °C, 60 % RH, pH 6.5, and 800 µS/cm.

Growth Profiles

A vegetable profile is a C table of stages. Each stage defines the environment for that phase and how long it lasts:

typedef struct {
    Color_t led_color;
    uint8_t brightness;          /* 1–7 */
    uint8_t photoperiod_hours;
    float air_temp_set;
    float rh_set;
    uint32_t duration_days;
} LettuceStateConfig_t;
 
typedef enum {
    STATE_GERMINATION = 0,
    STATE_SEEDLING,
    STATE_VEGETATIVE,
    STATE_FINISHING
} LettuceStateId_t;

The current lettuce profile:

StageLight colorBrightnessPhotoperiodAir tempRHDuration
GerminationBlue224 h21.0 °C75 %1 day
SeedlingRed + blue422 h25.0 °C65 %10 days
VegetativeRed + blue620 h24.0 °C60 %10 days
FinishingRed + blue518 h22.5 °C55 %14 days

Once per minute the growth thread reads the current actuator state and the profile's target for the active stage. Where they differ, it emits the corresponding light, humidifier, or temperature-setpoint command onto the queue. When the stage's elapsed time exceeds duration_days, it advances to the next stage and restarts the timer. It also performs soft safety checks, recommending more airflow or cooling when temperature or humidity run above tolerance.

Adding a vegetable means adding a state enum and a config table — the control thread's logic is generic over the stage array.

Temperature Regulation

The temperature loop is a finite state machine wrapped around a PID controller, and runs at 1 Hz. A deadband of 0.5 °C prevents the heater and fans from fighting each other around the setpoint.

IDLE ──below setpoint−deadband──► HEATING ──reaches band──► HOLDING
  │                                   ▲                        │
  └──above setpoint+deadband──► COOLING ◄──────────────────────┘
  • IDLE / HOLDING — no heating or cooling; outputs off.
  • HEATING — PID output drives the heater. Heater contacts are always bounded between 500 ms and 10 s of on-time (HEATER_MIN_ON_MS / HEATER_MAX_ON_MS) so the element is never switched continuously.
  • COOLING — PID output sets the inlet and outlet fan duty proportionally.

The PID runs with Kp = 1.2, Ki = 0.5, Kd = 0.01, a 1 s interval, integral anti-windup, and derivative-on-measurement (which avoids derivative kick on setpoint changes). Output is clamped to −1.0…1.0, then split into a heating duty (positive) or cooling duty (negative).

Fan speeds map to named modes rather than raw values:

ModeInletOutlet
Off0 %0 %
Light circulation—50 %
Active heating70 %—
Active cooling100 %100 %

Lighting and Humidification

The grow fixture is controlled by simulating button presses. lights.c holds each of the fixture's four inputs (power, on/off, brightness, color) as a GPIO and pulses it for 500 ms, exactly as a human pressing the button would. The context tracks the resulting logical state:

  • Brightness — 0–7, stepped by pulse count.
  • Color — RED_BLUE, BLUE, or RED; color changes are computed as the shortest forward step from the current color.
  • Power and on/off — separate toggles, reflecting the fixture's own controls.

stepsToDesiredBrightness() and stepsToDesiredColor() translate a target into the number of button pulses needed, accounting for whether the fixture is currently in a monochrome or red/blue mode.

The humidifier is driven with a timed pulse (500 ms to 5 s, a fixed enum of durations) and each actuation increments a counter, giving a simple measure of humidity activity over time.

Water and Nutrient Delivery (in progress)

The water side is scaffolded but not yet closed-loop. SensorData_t already carries water_pH and water_conductivity, and SensorSetpoints_t has per-profile pH and conductivity targets, so the growth profile can already express what each vegetable needs.

The RS-485 bus (UART2 at 9600 baud) is initialized and ready for water probes, and the CS5490 energy meter (UART1 at 115200) is integrated for power monitoring. The remaining work is probe integration, peristaltic pump and water-pump drivers, and a dosing regulator that mirrors the temperature loop: measure pH/EC, compare to the profile, and dose under firmware limits.

Connectivity, Dashboard, and Camera (planned)

The ESP32 provides Wi-Fi for cloud connectivity. The intended data path is to publish the SensorData_t snapshot and active setpoints over MQTT to a cloud dashboard for live and historical analysis, with a camera node feeding a remote visual stream so growers can check plant health without being on site.

Keeping this layer outside the control loop is deliberate — soft real-time control stays on-device, and the cloud is for observation, logging, and recipe management rather than plant-critical decisions.

Safety and Resilience

  • Local control. The full loop runs on the ESP32, so the grow space keeps operating on its last-known setpoints if the cloud or network is unavailable.
  • Bounded actuation. Heater on-time is rate-limited in firmware, and the light and humidifier use timed pulses rather than indefinite outputs.
  • Noise rejection. Outlier temperature samples are dropped before they reach the regulator, so a bad reading cannot trigger a heat/cool swing.
  • State protection. Sensor state and actuator context are mutex-protected, and all cross-thread commands flow through queues.
  • Explicit setpoints. Every actuator decision derives from the active profile rather than a hard-coded constant, which keeps "what the plant needs" in one auditable place.

Roadmap

  • Water probes (pH/EC) and peristaltic dosing on the RS-485 bus
  • MQTT telemetry and a cloud dashboard for live and historical data
  • Remote camera feed
  • Local status display on the ST7789V panel
  • Additional vegetable profiles beyond the lettuce reference
  • Closed-loop humidity and CO₂ control