--- /dev/null
+/* Flow sensor
+ * activates the relay when the rate of flow exceeds
+ * the selected value
+ */
+
+/* pin definitions */
+#define LED_RED 1
+#define LED_GREEN 0
+#define RELAY 4
+#define TRIM_ADC 2 /* ADC2 */
+#define TRIM_PIN 4 /* ADC2 is on PC4 */
+#define FLOW_INT 0
+#define FLOW_PIN 2
+
+/* our frequency counter */
+volatile int pulsecount = 0;
+
+/* increase the counter on interrupt */
+void counterISR()
+{
+ pulsecount++;
+}
+
+unsigned long last_time = 0;
+int threshold = 0;
+
+/* read the trim pot,
+ * div 3 to give a 1 - 342 range
+ */
+void update_threshold(void)
+{
+ threshold = analogRead(TRIM_ADC);
+ threshold /= 3;
+ threshold += 1;
+}
+
+
+void setup() {
+ // pin 2 is the pulse from the flow sensor
+ pinMode(FLOW_PIN, INPUT);
+
+ // pin 4 (ADC2) is an analog input
+ pinMode(TRIM_PIN, INPUT);
+
+ // pin 0 & 1 are the LEDs
+ pinMode(LED_RED, OUTPUT);
+ pinMode(LED_GREEN, OUTPUT);
+ pinMode(RELAY, OUTPUT);
+
+ // starting state: RED, relay open
+ digitalWrite(LED_RED, HIGH);
+ digitalWrite(LED_GREEN, LOW);
+ digitalWrite(RELAY, LOW);
+
+ update_threshold();
+ last_time = millis();
+
+ // now start the interupt routine
+ attachInterrupt(FLOW_INT, counterISR, FALLING);
+}
+
+void loop() {
+ unsigned long now = millis();
+
+ // clock has looped, restart
+ if (now < last_time) {
+ last_time = now;
+ pulsecount = 0;
+ return;
+ }
+
+ // it has been a second
+ if (now >= (last_time + 1000)) {
+ int count = pulsecount;
+
+ if (count == 0) {
+ // no movement: red
+ digitalWrite(LED_RED, HIGH);
+ digitalWrite(LED_GREEN, LOW);
+ digitalWrite(RELAY, LOW);
+ }else
+ if (count > threshold) {
+ // good flow: green, close relay
+ digitalWrite(LED_RED, LOW);
+ digitalWrite(LED_GREEN, HIGH);
+ digitalWrite(RELAY, HIGH);
+ } else {
+ // bad flow: yellow
+ digitalWrite(LED_RED, HIGH);
+ digitalWrite(LED_GREEN, HIGH);
+ digitalWrite(RELAY, LOW);
+ }
+
+ // check if the threshold moved
+ update_threshold();
+
+ // restart the clock
+ last_time = now;
+ pulsecount = 0;
+ }
+
+ // otherwise do nothing, just wait
+}