#include <Servo.h> // Include the Servo library
Servo myservo; // Creat servo object
#define LDRSensor A0 // The LDR sensor is attached to analog pin A0.
int previous = 0; // set the previous intensity value initially to 0.
void Rotate(int); // Declaring functions, Rotate and SeekLight.
void SeekLight(int, int);
void setup() {
myservo.attach(9); // Attach the servo to pin 9, which has PWM.
Serial.begin(9600); // Begin the serial comm.
}
void loop() {
int current = analogRead(LDRSensor); // Read the current light intensity and print it.
Serial.println(current);
/*
- Check if the value changed from the previous.
- If the value changed:
1- Set previous to the new value.
2- rotate the servo clockwise once.
3- Then read the intensity at that position.
*/
if (abs((current - previous)) >= 20){
previous = current;
Rotate(5);
current = analogRead(LDRSensor);
/*
- Check if the value got better.
- If it did, call the SeekLight function which rotates the servo
as long as the value keeps getting better.
*/
if (current < previous){
SeekLight(current, 5);
Rotate(-5); // return the servo to the last position which is maximum intensity.
}
/*
- If the intensity isn't getting better, rotate in the other direction
(counter-clockwise), read the intensity and do the process described
above for the counter-clockwise direction.
*/
else {
Rotate(-10);
current = analogRead(LDRSensor);
if(current < previous){
SeekLight(current, -5);
Rotate(5);
}
}
}
delay(250);
}
void Rotate(int deg) {
int ang = myservo.read();
myservo.write(ang + deg);
delay(250);
}
void SeekLight(int Sensordata, int deg) {
while(Sensordata < previous){
previous = Sensordata;
Rotate(deg);
Sensordata = analogRead(LDRSensor);
}
}