const int trig = 33;
const int echo = 32;
const int relay = 4;
long duration;
int distance;
int threshold = 61;
int count = 0;
int wait = 0;
int tFlush = 0;
const int flowsensor = 16;
const int ledPin = 17;
volatile int flowDetected = 0;
unsigned long lastFlowTime = 0;
const unsigned long flowTimeout = 1000;
void flowChange() {
flowDetected = 1;
lastFlowTime = millis();
}
void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(relay, OUTPUT);
pinMode(flowsensor, INPUT);
digitalWrite(flowsensor, HIGH);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(flowsensor), flowChange, FALLING);
}
void loop() {
// Clears the trigPin
digitalWrite(trig, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echo, HIGH);
// Calculating the distance
distance = duration * 0.034/2;
if (distance <= threshold){
digitalWrite(relay, LOW);
}else {
digitalWrite(relay, HIGH);
}
unsigned long currentTime = millis();
if (digitalRead(relay) == HIGH){
if (flowDetected && (currentTime - lastFlowTime < flowTimeout)) {
Serial.println("Water flow detected!");
digitalWrite(ledPin, HIGH); // Turn on the LED
}
delay(1000); // Adjust delay as needed
}
if (digitalRead(relay) == LOW){
if (flowDetected && (currentTime - lastFlowTime < flowTimeout)) {
Serial.println("Water flow detected!");
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
Serial.println("No Water flow detected!");
digitalWrite(ledPin, LOW); // Turn off the LED
flowDetected = 0; // Reset flow detection when there is no flow
}
delay(1000); // Adjust delay as needed
}
}