// Define the pin connected to the relay module
#define RELAY_PIN 2
// Define ultrasonic sensor pins
#define TRIGGER_PIN 3
#define ECHO_PIN 4
// Define servo motor pin
#define SERVO_PIN 5
// Variables for ultrasonic sensor
long duration;
int distance;
// Variables for servo motor control
int servoAngle = 0;
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;
// Print distance
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");
// Move the servo to 90 degrees
servoAngle = 90;
}
else
{
// Turn off the relay
digitalWrite(RELAY_PIN, LOW);
Serial.println("Relay turned OFF");
// Move the servo to 0 degrees
servoAngle = 0;
}
Serial.println("Servo degree");
Serial.println(servoAngle);
// Control the servo motor
analogWrite(SERVO_PIN, map(servoAngle, 0, 180, 0, 255));
// Wait for a short delay before next measurement
delay(1000); // Adjust this delay as needed
}