Skip to content
Martin Mwiti
All documentation

CWX Valve Controller

Architecture of a programmable irrigation timer — a custom STM32F103 PCB that drives all five CWX valve types at a selectable voltage, with a battery-backed RTC, a graphic-LCD menu, and up to four daily schedules.

STM32F103C++PlatformIOKiCadView project

Overview

The CWX Valve Controller is a self-contained irrigation timer. It drives every valve in the CWX line (CR01–CR05), each of which is electrically different, through a generic valve/voltage abstraction, and runs up to four daily watering schedules on a battery-backed real-time clock. All configuration is persisted to EEPROM, so the device survives power cuts without losing its schedule or its state.

The project is one embedded system but two hardware generations:

  • v1 — an Arduino Micro wired prototype: relays, a rotary switch, an LM2596 supply, and an LCD. Documented as a wiring diagram and a flow chart.
  • v2 — a custom KiCad PCB around an STM32F103C8T6 with a graphics LCD (ST7920, 128×64), a DS3231 RTC, a programmatic voltage rail, and per-valve driver stages. This is what the firmware targets today.
                 ┌────────────────────────────── STM32F103C8T6 ─────────────────────────────┐
12-28 V DC       │  I2C        SPI (SW)   GPIO       ADC         TIM/EXTI                  │
   │             │   │            │        │          │                                    │
 LM2596-ADJ ─────┼─►│ DS3231 RTC  │ ST7920  │ relays   │ divider   │ L293D ×2 (CR01/CR05)  │
 (buck to Vdrive)│  │ (SDA/SCL)   │ GLCD    │ CR02/03/04          └─────────► valves      │
   │             │   │            │ + kbd   │                    TMUX1208 (voltage select)│
 Vin sense ◄─────┼───│─────────────┼─────────┴─────────────────────► LM2596 feedback        │
 Vdrive sense ◄──┼───│─────────────┴──► rotary encoder (CLK/DT/SW)                          │
                 └────────────────────────────────────────────────────────────────────────┘

Design Goals

  • One controller for the whole CWX valve family, instead of a different timer per valve
  • Valve operating voltage selectable on-device, from a single wide-range supply
  • Time accuracy through power loss (real-time clock with backup battery)
  • Configuration survives power loss (EEPROM)
  • No keypad — a rotating knob with a push button must be enough to configure everything
  • A schedule that spans midnight must work naturally

Hardware

MCU and peripherals

The brain is an STM32F103C8T6 (ARM Cortex-M3, 72 MHz, LQFP-48). The board builds the classic "Blue Pill" footprint but is laid out for this application, with the peripherals on fixed pins:

PeripheralPartInterface
Real-time clockDS3231MZ (integrated TCXO, SOIC)I2C + battery backup
Graphics LCDST7920 128×64 (GLCD)Software SPI via U8g2
User inputRotary encoder + push buttonExti on CLK / SW
Motor driversL293DD ×2 (H-bridge)GPIO control, enable
RelaysSongle SRD-05VDC Form C ×4GPIO control
Voltage selectTMUX1208 (8:1 analog mux)GPIO address bits

Power architecture

The board accepts 12–28 V DC. Three stages condition it:

  1. LM2596S-ADJ buck produces Vdrive, the valve operating rail. Its output is not fixed: an 8-channel TMUX1208 multiplexer switches between feedback-divider taps, letting firmware select 5 V, 6 V, 9 V, 12 V, or 24 V on the fly. Valve output is thus programmable per installation.
  2. L7805 regulates a 5 V rail for the relay coils and logic where needed.
  3. AMS1117-3.3 derives the 3.3 V MCU rail.

High-value bulk capacitors (470 µF/35 V, 220 µF/50 V) sit on the input and rail nodes, and SS36 Schottky diodes guard the supply path.

Valve interface

Each valve type has a matching electrical driver:

ValvesTopologyDrive pin(s)Notes
CR01H-bridge (motor)1A/2A + ENPolarity chosen by firmware; fixed gear-turn duration
CR02Relay (latching)PB8Relay holds the active state
CR03Relay (latching)PC13Relay holds the active state
CR04Relay (latching)PB9Relay holds the active state
CR05H-bridge + limit feedback3A/4A + EN, OPEN/CLOSED inputsEnd-of-travel switch confirms the move

The CR05 channels read back two limit-switch inputs (CR05_STATUS_OPEN, CR05_STATUS_CLOSED): the driver energizes the H-bridge and waits until the corresponding travel switch trips (or times out), so the controller knows the valve actually reached the commanded state.

Sensing

Two on-board divider taps let firmware measure the real world:

  • VIN_MEASURE_PIN — input supply voltage (12–28 V expected; the design assumes up to 36 V)
  • VALVE_V_MEASURE_PIN — the actual Vdrive rail reaching the valve

Both read through an 11:1 divider into the 3.3 V ADC, so 36 V maps near the top of range.

Board and connectors

The v2 board is captured in KiCad (schematic, layout, and Gerber set documented) and built around through-hole XH-A connectors for the valve and supply tails, a 14-pin header for the display, an SWD header for programming, and a BOOT header for recovery. Placement was constrained by the enclosure: the display header, gland aperture, and screw positions line up with the mechanical layout documented in the user manual.

Pin Map

From src/pinout.h:

FunctionPin
I2C SDA / SCL (RTC)PB7 / PB6
GLCD SCK / MOSI / CS / RSTPA5 / PA7 / PA4 / PB11
GLCD backlightPA6
Relay CR02 / CR03 / CR04PB8 / PC13 / PB9
Rotary CLK / DT / SWPB10 / PA0 / PB1
TMUX enable / A0 / A1 / A2PB13 / PB12 / PB15 / PB14
CR01 enable / 1A / 2APA11 / PA8 / PA14
CR05 enable / 3A / 4APA13 / PA15 / PA12
CR05 status CLOSED / OPENPB4 / PB5
Valve V sense / input V sensePA2 / PA3

Firmware

Build

PlatformIO, ststm32 platform, genericSTM32F103C8 board, Arduino framework, UART at 115200 baud on PA10/PA9. Two libraries: adafruit/RTClib for the DS3231 and olikraus/U8g2 for the ST7920 GLCD (software SPI).

Structure

The code is split into focused modules:

ModuleResponsibility
main.cppLoop orchestration: time ticks, schedule engine, input dispatch, screen refresh
states.h/.cppThe state machine, menu as a linked list, configuration substates
glcd.h/.cppAll GLCD rendering: menu, screens, prompts, blinking fields, glyphs
rtc.h/.cppDS3231 access, schedule-time math (within-window, before-event, midnight wrap)
eeprom_utils.h/.cppBounded EEPROM read/write and the settings layout
cr0x_valves.h/.cppPer-valve drive routines (relay, H-bridge, travel-feedback)
voltage_ctrl.h/.cppVoltage rail select, supply check, rail read-back
rotary_enc.h/.cppEncoder and button ISRs with debouncing and long-press detection

State machine

The system moves between five states:

INIT ──► SHOWING_DETAILS ←─► MENU_NAVIGATION ←─► CONFIGURING
              │                    ▲  └──────────► IDLE (timeout)
              └────────────────────┘
  • INIT — on boot: read selected valve/voltage and schedules, build the menu, restore the saved valve state (turning the valve off or confirming it on), then move on.
  • SHOWING_DETAILS — live summary: current time, valve, voltage, valve state, and the active schedule window. Knob scrolls schedules; a push opens the menu; idles after 90 s.
  • MENU_NAVIGATION — a dynamic menu; a short press enters a config substate.
  • CONFIGURING — valve type, voltage, schedules, or system time, each a small guided wizard.
  • IDLE — screen off; wakes on push or 10 s before a valve event.

The threading model is light: a 1 s RTC tick drives screen updates and the auto-timeout counters, a 5 s cadence re-evaluates schedules, and two ISRs feed encoder/button events that the main loop consumes with flags — no RTOS needed.

The menu is built at runtime as a doubly-linked list (states.h → menuItem_t, malloced in states.cpp). populateMenu() composes the item set from current progress: valve-type and voltage items disappear once configured, "More"/"Less" reveal the hidden ones, and a "Clear error" item appears only if a valve-drive error is pending. This keeps the menu minimal on a 128×64 screen (~4 visible items on some GLCDs), with scroll position tracking in drawMenu().

menuItem_t *createMenuItem(const char *item);   // node = { data, prev, next }
menuItem_t *insertAtEnd(menuItem_t **head, const char *data);
menuItem_t *deleteMenuItem(menuItem_t **head, const char *item);

Persistence

Settings live in the first 32 bytes of EEPROM (eeprom_utils.h), laid out as:

AddressSetting
0–19Schedules 1–4: start hour/min, stop hour/min, status byte (5 bytes each)
20Valve state (on/off)
21–23Idle/config timeout and force-stop (utility bytes, see note)
24–25Selected valve type (24), selected voltage (25)
26–27"valve selected" and "voltage selected" flags
28–31Schedule enable flags (mirror of the per-schedule status bytes)

Selected valve type and voltage are stored at 24–25 with strict enum re-validation on read.

Every write is bounded-address checked. On boot the firmware does not trust stale state: it re-validates enum values (readSelectedValve()/readSelectedVoltage() reject out-of-range bytes) and recomputes the config. The RTC is battery-backed, so time itself is not persisted to EEPROM — the DS3231 keeps counting through power loss.

Valve control

states.h drives outputs through a function pointer selected at config time:

VsetRes_t (*setValve)(bool new_state);

A VsetRes_t result propagates success, timeout, error, or low-supply back into the UI (VSET_SUCCESS, VSET_TIMEOUT, VSET_ERROR, VSET_SUPPLY_VOLTAGE_TOO_LOW).

Motorized valves pulse the bridge for a fixed gear-travel time then release it:

VsetRes_t setCR01(bool new_state){
    digitalWrite(CR01_1A_CTRL, new_state);
    digitalWrite(CR01_2A_CTRL, !new_state);
    delay(100);                      // stabilization
    digitalWrite(CR01_EN, HIGH);     // drive the gear motor
    delay(VALVE_GEAR_TURN_DELAY_MS); // 7 s
    digitalWrite(CR01_EN, LOW);
    digitalWrite(CR01_1A_CTRL, LOW);
    digitalWrite(CR01_2A_CTRL, LOW);
    return VSET_SUCCESS;
}

CR05 adds verification: while the bridge is enabled it spins until the matching limit switch asserts, with an 8 s timeout that surfaces as VSET_TIMEOUT on the display.

Voltage selection

setVoltage() performs a select → measure → verify sequence instead of trusting the rail blindly:

  1. Check the input supply has ≥ 3 V headroom above the target (MIN_VALVE_VOLTAGE_VS_POWER_SUPPLY_DIFFERENCE) — otherwise VSET_SUPPLY_VOLTAGE_TOO_LOW.
  2. Assert the mux address for the target voltage and enable the mux.
  3. Read Vdrive back through the divider and accept it only within ±1 V of the target; anything else returns VSET_ERROR and drops the rail.
void setVoltage(ValveVoltage v, VsetRes_t *status){
  if ((input - target) < 3) { *status = VSET_SUPPLY_VOLTAGE_TOO_LOW; ... }
  select_mux_output_for(v);
  enable_mux();
  float measured = readValveVoltage();
  *status = fabs(measured - target) <= VOLTAGE_ERROR ? VSET_SUCCESS : VSET_ERROR;
}

One caveat the firmware itself documents: the mux only shunts the feedback network — turnOffValveVoltage() drops the rail to the buck's safe minimum, and a true power-cut enable line is marked as a next-hardware-revision item.

Schedule engine

Schedules are stored as start/stop ScheduleTime_t in rtc.h. Three rules define them:

  • A stop time must be ≥ 5 minutes after start, including a window that crosses midnight (isTimeDifferenceMoreThan5Minutes() folds midnight).
  • An enabled schedule whose window contains the current time is "time to irrigate".
  • Only one schedule may be active at once; enabling a window that overlaps an existing one is refused at edit time (isConflictingTimeSchedules()).

Every 5 s the loop runs setActiveIrrigationSchedule(). On a start boundary it calls setValve(true); on stop, setValve(false). Crucial detail: if the user disables a schedule while it is running, the loop immediately turns the valve off, and it will not turn back on while disabled. The released candidate is tracked so a later schedule still fires cleanly.

if (is_time_to_irrigate) {
  if (!valve_on) {
    res = setValve(true);
    if (res == VSET_SUCCESS) valve_on = true, writeValveState(true);
  }
} else if (valve_on) {
  res = setValve(false);       // also fires when a schedule is disabled
  if (res == VSET_SUCCESS) valve_on = false, writeValveState(false);
}

The schedule engine double-checks against the RTC rather than millis(), so it stays correct through deep sleep or power restarts.

UI behaviour

Everything ships through the knob/button idioms described in the user manual: rotate to move, push to select, long-press to jump to a save screen. Configuration wizards sequence fields (year→month→…→seconds, or start-hour→start-minute→stop-hour→stop-minute) with the active field blinking on the ST7920. The summary screen highlights the running schedule's window, and the display sleeps after 90 s of no interaction — auto-waking 10 seconds before the next valve event so the user sees the change happen.

Error Handling

Drive errors are surfaced rather than silently swallowed. A failed valve move records error_setting_valve, injects a top-level "Clear error" menu item, and shows a timeout/error banner; the schedule engine refuses to run (!error_setting_valve) while an error is pending. Voltage errors similarly reject a bad selection at save time, showing "Supply voltage too low" or "Error setting voltage" and keeping the previous configuration.

Design Notes

  • Why a function pointer for valves. Five valve models, five electromechanical personalities — isolating them behind setValve() left the schedule engine and the menu completely valve-agnostic.
  • Feedback over timers. CR05's limit switches turned "we think it turned" into "we know it turned", which is worth the two extra wires on that model.
  • Persist state, not just config. Writing the valve state (writeValveState) means a bonus interruption in the middle of a watering window resumes correctly on restore, because the relay/H-bridge goes back to the commanded state at boot.
  • Feed-back validated rail. Selecting an output voltage by setting pins is only half the job; measuring Vdrive and rejecting out-of-tolerance or under-supplied selections caught real bench surprises (dynamo and buck startup) during development.
  • One knob is enough — but the UI rules (blink, long-press to save, auto-wake before events) carry the burden, which is exactly the design trade made deliberately.

Future Improvements

  • True power-cut relay (EN) for the LM2596 so "valve off" means no rail at all
  • Configurable month/day-of-week rules per schedule (currently schedules are daily)
  • On-device event log of valve opens/closes for diagnostics
  • Web dashboard integration (via the Dopesilicon platform) for remote monitoring of the valve state and supply health

The machine-readable wiring diagram, the state-machine flow chart, and the KiCad sources live in the project repository alongside the firmware.