Light sensor servo motor

Hi Im doing a project called "light sensitive Curtain" but I only have 1 problem that is the the motor wont stop.Im using a LDR sensor and a MG995 servo motor .for example if the LDR value is above 200 then the motor would rotate for 3 sec,then it would rotate again continuously.so I would like to know how can I make so that the servo run only once then stanby for when the sensor value is changed below 60.

this is my code:

#include<Servo.h>

Servo servo;
const int sensorPin=0;

void setup() 
{
  servo.attach(5);
  Serial.begin(9600);
}

void loop() 
{
  int ldr = analogRead(sensorPin);
  Serial.println(ldr);
  
   if(ldr >= 200)
  {
    servo.attach(5);
    servo.write(100);
    delay(3000);
    servo.detach();
  }

  else if(ldr <=60)
  {
    servo.attach(5);
    servo.write(50);
    delay(3000);
    servo.detach();
  }

  else if(ldr >=61 & ldr <=199)
  {
    servo.attach(5);
    servo.write(92);
    delay(3000);
    servo.detach();
  }
}
#include<Servo.h>
Servo servo;
const byte sensorPin = A0;
const byte ServoPin = 5;
bool isActionMade = false;

void setup() {
  Serial.begin(9600);
  servo.attach(ServoPin);
}

void loop() {
  int ldr = analogRead(sensorPin);
  Serial.println(ldr);

  if (ldr >= 200 && !isActionMade)  {
    servo.write(100);
    Serial.println(F("ldr >= 200"));
    delay(3000);
    isActionMade = true;
  }
  else if (ldr >= 61 && ldr <= 199 && !isActionMade)  {
    servo.write(92);
    Serial.println(F("ldr >= 61 && ldr <= 199"));
    delay(3000);
    isActionMade = true;
  }
  else if (ldr <= 60)  {
    servo.write(50);
    Serial.println(F("ldr <= 60"));
    delay(3000);
    isActionMade = false;
  }
}
1 Like

You could use a variation of the state change detection method. Only actuate the servo if the ldr changes from more than 60 to less than 60. Do not actuate if ldr stays less than 60.

The analogRead function is smart enough to know that that is A0. One should use Ax notation when declaring for readability though.
const int sensorPin = A0;

Read the forum guidelines to see how to properly post code and some good information on making a good post.
Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

You can go back and fix your original post by highlighting the code and clicking the </> in the menu bar.
code tags new

1 Like

smarter as me :sweat_smile:

If you want to see how analogRead does that look into wiring_analog.c.

...or when using the analogue pins as digital pins.

1 Like

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