# CNC Water Flow Controller

A fail-safe water flow monitoring module designed to protect CNC spindles and laser cutter tubes. It reads impulses from a ZJ-S401 water flow sensor, displays the real-time flow rate on an I2C OLED display, and triggers an active-low alarm to the CNC controller if the flow drops below a user-defined threshold.

![Flow Controller Schema](images/Flow_Controller.svg)

![Front](images/Flow_Controller_front.png)
![Back](images/Flow_Controller_back.png)

![ZJ-S401](images/Sensor_ZJ-S401.png)

Designed in **KiCad v9**.

## Features
* **Microcontroller:** WCH CH32V003J4M6 (RISC-V).
* **Display UI:** 8-pin connector for a custom OLED/Button panel (I2C SSD1315).
* **Adjustable Threshold:** 2-button interface (Up/Down) using an analog resistor ladder (ADC) to save MCU pins.
* **Fail-Safe Output:** N-channel MOSFET (2N7002) acting as an open-drain output. It actively pulls the CNC input to GND during normal operation. If power fails, wires break, or water stops, the connection opens and triggers the CNC alarm.
* **EMI Protection:** Hardware RC debouncing and noise filtering on the sensor input.
* **Direct 5V Operation:** Powered directly from the CNC controller's 5V rail.

## Hardware Design (KiCad)
* **Power:** 5V DC Input (via CNC connector J4).
* **Sensor Compatibility:** ZJ-S401 (or similar 5V Hall-effect flow sensors).
* **Output:** 3-pin CNC interface (+5V, GND, ALARM_CNC). Connects directly to standard CNC active-low sinking inputs.

### Microcontroller Pin Mapping (Per Schematic)
| Pin | Schematic Net | Function |
| :--- | :--- | :--- |
| 1 | `FLOW_PULSE_MCU` | Input: Pulse counter from Flow Sensor (via RC Filter) |
| 2 | `GND` | System Ground (VSS) |
| 3 | `ALARM_TRIGGER` | Output: Drives the Gate of the 2N7002 MOSFET |
| 4 | `+5V` | System Power (VDD) |
| 5 | `I2C_SDA` | I2C Data (OLED Display) |
| 6 | `I2C_SCL` | I2C Clock (OLED Display) |
| 7 | `BUTTON_ADC` | ADC Input: 2-Button Resistor Ladder |
| 8 | `SWIO` | WCH-LinkE Programming Interface |

## Firmware Logic (Overview)
1. **Interrupts:** Pin 1 counts falling edges from the flow sensor. Flow (L/min) is calculated every second.
2. **Failsafe:** If `Current_Flow >= Threshold`, Pin 3 is driven **HIGH** (MOSFET ON, CNC OK). If `Current_Flow < Threshold`, Pin 3 is driven **LOW** (MOSFET OFF, CNC Alarm).
3. **UI:** ADC reads Pin 7 to detect button presses for adjusting the threshold.
4. **Storage:** User-defined threshold is saved to MCU flash memory.

## Development & Programming
To flash the CH32V003, you will need a **WCH-LinkE** programmer connected to the 3-pin SWIO header `J1` (+5V, SWIO, GND).
