#include <ESP32Servo.h>
const int servoPin = 18; // Servo signal pin
const int buttonPin = 4; // Push button pin
const int photoresistorPin = 34; // Photoresistor pin
Servo myServo;
int buttonState = 0;
int lastButtonState = 0;
int photoValue = 0;
int photoThreshold = 500; // Adjust this value based on your photoresistor behavior
void setup() {
myServo.attach(servoPin);
pinMode(buttonPin, INPUT);
Serial.begin(115200);
}
void loop() {
// Read button state
buttonState = digitalRead(buttonPin);
// Read photoresistor value
photoValue = analogRead(photoresistorPin);
// Map the photoresistor value to servo position
int servoPosition = map(photoValue, 0, 1023, 0, 180);
servoPosition = constrain(servoPosition, 0, 180); // Ensure servo position is within valid range
// If the button is pressed or photoresistor value exceeds the threshold, move the servo
if ((buttonState == HIGH || photoValue > photoThreshold) && lastButtonState == LOW) {
myServo.write(servoPosition);
Serial.print("Button or Photoresistor triggered. Servo position: ");
Serial.println(servoPosition);
} else {
// If the button is not pressed and photoresistor value is below the threshold, stop the servo
myServo.write(90); // Move to the middle position
Serial.println("Button not pressed. Servo stopped.");
}
// Store the current button state for comparison in the next iteration
lastButtonState = buttonState;
// Add a delay to avoid rapid changes
delay(50);
}