I use ldr to move my servo to 90 degrees when its reach my setpoint of darkness then after that i want it to go back to its initial position

#include <Servo.h>

Servo myservo;
int photocellPin = 0;
int photocellReading;

void setup()
{
Serial.begin(9600);
myservo.attach(3);
}
void loop()
{
Serial.print("Brightness = ");
Serial.println(photocellReading);
photocellReading = analogRead(photocellPin);
photocellReading = map(photocellReading, 0, 1023, 0, 179);
{
if
(photocellReading <= 89); //if the LDR is showing less than half light intensity
myservo.write(90);
delay(100);
}
}

Hello iyanitski and welcome to the worldbest Arduino Forum

something like this maybe?

(compiles, NOT tested!)

#include <Servo.h>

Servo myservo;
int photocellPin = 0;
int photocellReading;
bool servo_moved = false;

void setup()
{
  Serial.begin(9600);
  myservo.attach(3);
}
void loop()
{
  Serial.print("Brightness = ");
  Serial.println(photocellReading);
  photocellReading = analogRead(photocellPin);
  photocellReading = map(photocellReading, 0, 1023, 0, 179);

  if (servo_moved = false) {
    if (photocellReading <= 89) { //if the LDR is showing less than half light intensity
      myservo.write(90); //move to 90 deg position
      servo_moved = true;
    }
  }
  else {
    if (photocellReading > 89) { //if the LDR is showing more than half light intensity
      myservo.write(0); //move to 0deg position
      servo_moved = false;
    }
  }

  delay(100);
}

hope that helps....

1 Like

Please check the syntax of "if" statement. Your condition do nothing because the superficial ';' in the end of line.

@sherzaad
Please do not do for OP his homework :slight_smile:

thanks bro but what i mean is, the return to 0 is not dependent when the ldr showing more than half of light. what i want is when the ldr showing less than half of light the servo turns to 90 then automatically back to 0. in every reading that shows less than of light the servo turns to 90 then automatically back to 0. can you help me plsss

so if I understood you want the servo to move 0->90->0 when the target LDR level is detected.

if you are using a servo without feedback then probably the easiest way is to use a 'tuned' delay ie:

myservo.write(90); //move to 90 deg position
delay(x); //x milliseconds delay
myservo.write(0); //return to 0 deg position

if you are using a servo with feedback like this one then the other way of doing it is to keep reading the feedback (analogRead) within 'loop' and one it reach the 90deg position, run the "myservo.write(0); " to return the servo to zero position.

hope that helps....

how can i put that in a program?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.