servo speed problem

hello,
I'm sure that my problem is really a beginner problem,...but I'm actually a beginner ;)..
so, I want to control a servo with a sharp IR, I want the servo to turn in a sense if I'm approaching the sensor, and in the other sense if I'm not approaching the sensor... I'm actually able to do it, but I can't control the speed with this code below , I think there is something to do with an increment operator, but I'm not able to do it
thank you

#include <Servo.h>
#define IR_pin 0
Servo myservo1;

int pos = 0;

int IR_val = 0;
void setup()
{
Serial.begin(9600);
myservo1.attach(2);

}

void loop()
{

IR_val = analogRead(IR_pin);
Serial.println( IR_val);

if (IR_val < 200)

{

myservo1.write(180);
delay(30);
}

if (IR_val > 200)
{

myservo1.write(0);

delay(30);
}
Serial.println( IR_val);

}

The simplest way is with a delay:

void loop() 
{ 
  IR_val = analogRead(IR_pin);
  Serial.println( IR_val); 
  
  if (IR_val < 200) {
     for (int pos = 0; pos < 180; ++pos) {
        myservo1.write(pos);
        delay(3);
     }
   }

so here, the traverse takes about 3* 180 milliseconds.

tanks you very much :slight_smile: it works!l

hi,
..so , it works well, but now, I'm wondering if I could have the servo to change its rotation sense immediately when I'm approaching the distance sensor, and not waiting it to reach the end of its movement
and also, Awol, you said

so here, the traverse takes about 3* 180 milliseconds.

I don't understand this calculation, I thought the 180 in the code was about degrees, not about time...?
thanx

180 one degree steps with a delay of 3 milliseconds between each step