servo motor control problem

hello everyone,

I am working on the objective of using IR sensor to control the movement of a servo motor.
The motor responds to the value but not every time.

It moves on random signals but most of the time does not respond. It continuously produces knocking/clicking sounds without any movement of the gear.

The servo independently has been tested and works totally fine.

Any ideas why i am facing this problem ? I am also thinking of timing the signals for better monitoring . How can I do that?

Here are the components :

  1. IR sensor - Sharp IR sensor

  2. servo motor - tower pro 996R

here is the code :-

#include<Servo.h>

Servo servo1;

int analogPin = 3 ;

int dist = 0 ;
int i =0 ;


void setup() {
Serial.begin(9600);

servo1.attach(9);

// digitalWrite(A3, INPUT_PULLUP);
}

void loop() {
  dist = analogRead(analogPin);
  dist = map (dist,0,1023,0,20);
    
  Serial.println(dist);
  {
 
  for (i=0;i<20;i++)
  {
    if (dist==i)
      servo1.write(dist*10);
       
    }
      
  }
  delay(2000);
}

Do you get the expected values from your Serial.println()? Why is the for loop in there? Wouldn't you get the same result by just writing (dist * 10) directly?

But anyway, it's likely that the problem is power related. How are you powering things and particularly how is the servo connected. If it's connected to the Arduino's 5V pin then that's almost certainly at least part of the problem. Servos should always have a separate power supply. The MG996R is a biggish servo which will definitely take more current than an Arduino pin can safely deliver.

Steve