#define RELAY_PIN 2
// Define ultrasonic sensor pins
#define TRIGGER_PIN 3
#define ECHO_PIN 4
// Variables for ultrasonic sensor
long duration;
int distance;
void setup() {
// Initialize the relay pin as an output
pinMode(RELAY_PIN, OUTPUT);
// Initialize the ultrasonic sensor pins
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Start serial communication
Serial.begin(9600);
}
void loop() {
// Trigger ultrasonic sensor
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Measure the duration of the pulse
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if distance is greater than 5 cm
if (distance > 5) {
// Turn on the relay
digitalWrite(RELAY_PIN, HIGH);
Serial.println("Relay turned ON");
} else {
// Turn off the relay
digitalWrite(RELAY_PIN, LOW);
Serial.println("Relay turned OFF");
}
// Wait for a short delay before next measurement
delay(1000); // Adjust this delay as needed
}