0

I want my tower pro 9g servo to start from pos=0, wait there for 1 second, then reach pos=90 wait for 1 second, then reach pos=180 and wait for 1 second. Now it goes back to pos=0 and repeats this cycle. I have written the following code for this purpose:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(12);  // attaches the servo on pin 9 to the servo object
}

void loop() {


  for (pos = 0; pos <= 180; pos += 90) { // goes from 0 degrees to 180 degrees
    // in steps of 90 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }


  for (pos = 180; pos >= 0; pos -= 90) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }

}

But the behavior of the servo is not correct. It moves few degree from initial position and then comes back.

What is wrong with the logic in my code ?

  • remove the second for loop ... the first loop already does what you want – jsotola Jul 27 '18 at 15:37
0

I think that the servo is too slow. When you ask it to go 90 degrees it starts, than after one second (while it maybe reaches 5 degrees) you ask it to go to 180 degrees it is probably reaching 10 degrees. There it waits again one second.

Than you ask it to go back to 0 (which it does in the same 2 seconds as it moved from 0 to 10 degrees).

Try to adjust the delay times, or use a faster servo.

Also note that in your example (if you wish it would behave like coded), it will end 2 seconds at 0 and 180 degrees, and 1 second at 90 degrees).

Try:

void move_servo(int pos)
{
    myservo.write(pos);
    delay(30000);
}

void loop()
{
    move_servo(  0);
    move_servo( 90);
    move_servo(180);
    move_servo( 90);
}

It will wait 30 seconds between each step, make this less when possible. To make the servo wait not more than needed, check the old and new servo position and wait as needed, it's probably reasonably linear.

0

The logic looks OK to me. But be aware that these servos don't perform well at or close to their limits - mine tend to jitter there but there may be other issues as well. I have 10 of these hobby servos; each has a different jitter-band at the ends of its travel. You may have better success driving them to 10, 90, and 170 degrees.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.