#include <Servo.h>
Servo myServo; // Declare a servo object
int servoPin = 9; // Digital pin for servo
int lightPin = A4; // Analog pin for photoresistor
int angle; // Variable to store servo angle
int lightVal; // Variable to store photoresistor reading
void setup() {
myServo.attach(servoPin); // Attach the servo to the specified pin
pinMode(lightPin, INPUT); // Set the light pin as an input
Serial.begin(9600); // Initialize serial communication
}
void loop() {
lightVal = analogRead(lightPin); // Read the photoresistor value
angle = calculateAngle(lightVal); // Calculate the corresponding angle
myServo.write(angle); // Set the servo angle
Serial.println(angle); // Print angle for debugging
delay(250); // Delay for stability
}
int calculateAngle(int lightValue) {
// Mapping light values to servo angles using linear equation
return -16.0 / 63.0 * lightValue + 16.0 * 780.0 / 63.0;
}