#include <ESP32Servo.h>
// Pin definitions
const int potPin = 0; // Potentiometer
const int relayPin = 12; // Relay 1
const int relay2Pin = 14; // Relay 2
const int servoPin = 33; // Servo
const int trigPin = 26; // Ultrasonic Sensor Trig
const int echoPin = 25; // Ultrasonic Sensor Echo
// Variables
Servo myServo;
long duration;
int distance;
int potValue;
void setup() {
// Initialize pins
pinMode(relayPin, OUTPUT);
pinMode(relay2Pin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myServo.attach(servoPin);
// Initialize Serial Monitor
Serial.begin(115200);
}
void loop() {
// Read potentiometer value
potValue = analogRead(potPin);
Serial.print("Potentiometer Value: ");
Serial.println(potValue);
// Control Relay 2 based on potentiometer value
if (potValue < 500) {
digitalWrite(relay2Pin, LOW); // Turn off Relay 2
} else {
digitalWrite(relay2Pin, HIGH); // Turn on Relay 2
}
// Measure distance using ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // Calculate distance in cm
Serial.print("Distance: ");
Serial.println(distance);
// Control Relay 1 based on distance
if (distance < 100) {
digitalWrite(relayPin, HIGH); // Turn on Relay 1
} else {
digitalWrite(relayPin, LOW); // Turn off Relay 1
}
// Control Servo based on distance (optional)
if (distance < 100) {
myServo.write(90); // Move servo to 90 degrees
} else {
myServo.write(0); // Move servo to 0 degrees
}
delay(100); // Small delay for stability
}