Commit | Line | Data |
---|---|---|
49f3a36d JM |
1 | /* Flow sensor |
2 | * activates the relay when the rate of flow exceeds | |
3 | * the selected value | |
4 | */ | |
5 | ||
6 | /* pin definitions */ | |
7 | #define LED_RED 1 | |
8 | #define LED_GREEN 0 | |
9 | #define RELAY 4 | |
10 | #define TRIM_ADC 2 /* ADC2 */ | |
11 | #define TRIM_PIN 4 /* ADC2 is on PC4 */ | |
12 | #define FLOW_INT 0 | |
13 | #define FLOW_PIN 2 | |
14 | ||
15 | /* our frequency counter */ | |
16 | volatile int pulsecount = 0; | |
17 | ||
18 | /* increase the counter on interrupt */ | |
19 | void counterISR() | |
20 | { | |
21 | pulsecount++; | |
22 | } | |
23 | ||
24 | unsigned long last_time = 0; | |
25 | int threshold = 0; | |
26 | ||
27 | /* read the trim pot, | |
28 | * div 3 to give a 1 - 342 range | |
29 | */ | |
30 | void update_threshold(void) | |
31 | { | |
32 | threshold = analogRead(TRIM_ADC); | |
33 | threshold /= 3; | |
34 | threshold += 1; | |
35 | } | |
36 | ||
37 | ||
38 | void setup() { | |
39 | // pin 2 is the pulse from the flow sensor | |
40 | pinMode(FLOW_PIN, INPUT); | |
41 | ||
42 | // pin 4 (ADC2) is an analog input | |
43 | pinMode(TRIM_PIN, INPUT); | |
44 | ||
45 | // pin 0 & 1 are the LEDs | |
46 | pinMode(LED_RED, OUTPUT); | |
47 | pinMode(LED_GREEN, OUTPUT); | |
48 | pinMode(RELAY, OUTPUT); | |
49 | ||
50 | // starting state: RED, relay open | |
51 | digitalWrite(LED_RED, HIGH); | |
52 | digitalWrite(LED_GREEN, LOW); | |
53 | digitalWrite(RELAY, LOW); | |
54 | ||
55 | update_threshold(); | |
56 | last_time = millis(); | |
57 | ||
58 | // now start the interupt routine | |
59 | attachInterrupt(FLOW_INT, counterISR, FALLING); | |
60 | } | |
61 | ||
62 | void loop() { | |
63 | unsigned long now = millis(); | |
64 | ||
65 | // clock has looped, restart | |
66 | if (now < last_time) { | |
67 | last_time = now; | |
68 | pulsecount = 0; | |
69 | return; | |
70 | } | |
71 | ||
72 | // it has been a second | |
73 | if (now >= (last_time + 1000)) { | |
74 | int count = pulsecount; | |
75 | ||
76 | if (count == 0) { | |
77 | // no movement: red | |
78 | digitalWrite(LED_RED, HIGH); | |
79 | digitalWrite(LED_GREEN, LOW); | |
80 | digitalWrite(RELAY, LOW); | |
81 | }else | |
82 | if (count > threshold) { | |
83 | // good flow: green, close relay | |
84 | digitalWrite(LED_RED, LOW); | |
85 | digitalWrite(LED_GREEN, HIGH); | |
86 | digitalWrite(RELAY, HIGH); | |
87 | } else { | |
88 | // bad flow: yellow | |
89 | digitalWrite(LED_RED, HIGH); | |
90 | digitalWrite(LED_GREEN, HIGH); | |
91 | digitalWrite(RELAY, LOW); | |
92 | } | |
93 | ||
94 | // check if the threshold moved | |
95 | update_threshold(); | |
96 | ||
97 | // restart the clock | |
98 | last_time = now; | |
99 | pulsecount = 0; | |
100 | } | |
101 | ||
102 | // otherwise do nothing, just wait | |
103 | } |