#include <Arduino.h>
// Pin definitions
#define TRIG_PIN 5
#define ECHO_PIN 18
#define LED1_PIN 2
#define LED2_PIN 4
// Function to get distance from the HC-SR04 sensor
long getDistance() {
// Clear the trigPin by setting it LOW
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the trigPin HIGH for 10 microseconds
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the echoPin, and return the sound wave travel time in microseconds
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance (in cm) based on the speed of sound (340 m/s)
long distance = duration * 0.034 / 2;
return distance;
}
void setup() {
// Initialize serial communication at 115200 bits per second
Serial.begin(115200);
// Configure pin modes
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED1_PIN, OUTPUT);
pinMode(LED2_PIN, OUTPUT);
}
void loop() {
// Get the distance from the HC-SR04 sensor
long distance = getDistance();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Define distance thresholds for flood warning
const long SAFE_DISTANCE = 100; // Safe distance in cm
const long WARNING_DISTANCE = 50; // Warning distance in cm
// Control LEDs based on distance
if (distance > SAFE_DISTANCE) {
// Safe distance
digitalWrite(LED1_PIN, LOW); // Green LED off
digitalWrite(LED2_PIN, LOW); // Red LED off
} else if (distance > WARNING_DISTANCE && distance <= SAFE_DISTANCE) {
// Warning distance
digitalWrite(LED1_PIN, HIGH); // Green LED on
digitalWrite(LED2_PIN, LOW); // Red LED off
} else {
// Flood distance
digitalWrite(LED1_PIN, LOW); // Green LED off
digitalWrite(LED2_PIN, HIGH); // Red LED on
}
// Wait for 500 milliseconds before the next loop
delay(500);
}