Coding a Servo with a Photoresistor

Hi Everyone,

I have this code (below) that reads a photoresistor and then move the servo small amounts depending on the light reading. My code seems to be correct, but the servo keeps glitching - it moves to 90 degrees at the beginning of the program and then sits at around 10 degrees for the remainder of the time, no matter what I make the light reading.

CODE:

#include <Servo.h>

int sensorValue = 0;

Servo servo_3;

void setup()
{
pinMode(A0, INPUT);
Serial.begin(9600);

pinMode(9, OUTPUT);
servo_3.attach(3);

}

void loop()
{
// read the value from the sensor
sensorValue = analogRead(A0);
// print the sensor reading so you know its range
Serial.println(sensorValue);
// map the sensor reading to a range for the LED
analogWrite(9, map(sensorValue, 0, 1023, 0, 255));
delay(2000); // Wait for 1000 millisecond(s)

if (sensorValue < 100) {
servo_3.write(0);
}
else if (100 < sensorValue < 200) {
servo_3.write(9);
}
else if (200 < sensorValue < 300) {
servo_3.write(18);
}
else if (300 < sensorValue < 400) {
servo_3.write(27);
}
else if (400 < sensorValue < 500) {
servo_3.write(36);
}
else if (500 < sensorValue < 600) {
servo_3.write(45);
}
else if (600 < sensorValue < 700) {
servo_3.write(54);
}
else if (700 < sensorValue < 800) {
servo_3.write(63);
}
else if (800 < sensorValue < 900) {
servo_3.write(72);
}
else if (900 < sensorValue < 1000) {
servo_3.write(81);
}
else if (1000 < sensorValue < 1100) {
servo_3.write(90);
}
}

If you can find any issues and tell me how to fix them, I would greatly appreciate it!!

Thanks,
Augreim Soperlls

The problem is with if (100 < sensorValue < 200). The Arduino compiler does not treat this as you intend. Try :-
if ((sensorValue > 100) && (sensorValue < 200))

Other compilers may understand what is intended but not the Arduino compilier.

Regards
Jim

1 Like

The first part of the test is redundant. You don’t get to that point unless you have already failed the previous if test.

It also WRONG. You do nothing if the sensor value is an exact multiple of 100.

Hi Augreim,

James is right about the error in the code.

Have you monitored output of that LDR with the serial monitor? I think that you will find some of those light levels unreachable.