// Define pins for HC-SR04 sensor
const int trigPin = 9;
const int echoPin = 10;
// Define pin for relay controlling the solenoid valve
const int relayPin = 8;
// Variables to store distance measurements
long duration;
int distance;
// Define water level thresholds in centimeters
int lowLevelThreshold = 15; // Below this distance, the water level is low (solenoid opens)
int highLevelThreshold = 5; // Above this distance, the water level is high (solenoid closes)
void setup() {
// Set the trigger and echo pins as output and input
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set the relay pin as output
pinMode(relayPin, OUTPUT);
// Initially, close the solenoid valve (turn relay off)
digitalWrite(relayPin, LOW);
// Begin serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10us pulse to trigger the sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, and calculate the duration
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters (speed of sound = 0.034 cm/us)
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check the water level and operate the solenoid valve accordingly
// If the distance is greater than the low level threshold, open the valve (water level low)
if (distance > lowLevelThreshold) {
digitalWrite(relayPin, HIGH); // Turn on the relay to open the solenoid valve
Serial.println("Water level low. Opening valve...");
}
// If the distance is below the high level threshold, close the valve (water level high)
else if (distance < highLevelThreshold) {
digitalWrite(relayPin, LOW); // Turn off the relay to close the solenoid valve
Serial.println("Water level high. Closing valve...");
}
// Delay for 1 second before the next reading
delay(1000);
}