Using 2 LDR's to Control direction of a Continuous Rotation Servo

Im building a small robot which moves in two directions depending on the direction of the light falling. Ive used 2 LDR's and one Continuous Rotation Servo(which is separately powered from a 9v battery) to move the robot.

#include <Servo.h>
Servo S;
int val;
int val2;

void setup()
{
S.attach(12);
Serial.begin(9600);
}

void loop()

{
val = analogRead(0);
//Serial.println(val);
val2 = analogRead(1);
//Serial.println(val2);

if (val > val2)
{
val = map(val, 0, 1023, 90, 180);
S.write(val);
}

if (val2 > val)
{
val2 = map(val2, 0, 1023, 90, 0);
S.write(val2);
}

else
S.write(90);
delay(100);
}

The problem I'm facing is that the servo turns in only one direction when I hold a light on one LDR. When I shine a light on the other it doesn't turn. Was hoping someone could help me out.

  1. After each map function put in a Serial.print to see what is actually being sent to the servo.
  2. Read the "how to use the forum" stickies.
  3. Post code in code tags.
  4. The 9V battery is not the best power supply for a servo.

edit: try 10K resistors in place of the 1K resistors.

 if (val > val2)
{
val = map(val, 0, 1023, 90, 180);
S.write(val);
}

if (val2 > val)
{
val2 = map(val2, 0, 1023, 90, 0);
S.write(val2);
}


else
S.write(90);

You have two if statements and one else statement. You need an if statement, an else if statement, and an else statement.

if(val1 > val2) // I expect you to number ALL related variables
{
}
else if(val1 < val2)
{
}
else // they are equal
{
}

Thanks for the help guys. The small tweak in the coding made it work. Ill make sure to keep those points in mind :slight_smile: