0

I'm trying to get my servo motor to sweep from 0 to 180 degrees then back to 0 degrees for infinite amount of times. I using the following code but my motor keeps resetting when it get backs to 0 degrees (meaning it goes 0-->180-->0 then completes a 360 and starts over). Also the 0-180 degree sweep appears to be more of a 0-270 degree sweep. Anyone running into these problems?

int angle = 0;

void setup() {
  myservo.attach(9);
  myservo.write(angle);
}

void loop()
{
  for (angle = 0; angle < 180; angle += 1)
  {
    myservo.write(angle);
    delay (50);
  }

  for (angle = 180; angle > 0; angle -= 1)
  {
    myservo.write(angle);    
    delay(50);
  }   
}

3 Answers 3

1

Are you trying to have the servo sweep at a particular speed? Why not just use:

void loop()
{
  angle=180;
  myservo.write(angle);

  delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.

  angle=0;
  myservo.write(angle);

  delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.
}
4
  • Thanks. I tried this and it worked for 0.5 second delay but when I increased the time the servo makes a 360 again. it goes 180 degrees-->360 turn-->0 degree--> 180 then pauses-->360 degree turn and repeats.
    – CJ.
    Aug 31, 2017 at 15:23
  • Can you post a link to the exact servo unit you are using? Aug 31, 2017 at 15:28
  • I purchased the Elegoo Uno Project Super Starter Kit (elegoo.com/product/elegoo-uno-project-super-starter-kit)
    – CJ.
    Aug 31, 2017 at 15:41
  • 1
    If that servo goes over 180 travel, something is wrong with it. Aug 31, 2017 at 15:44
2

Is your servo the modified 360 degree type with no position feedback (meaning the internal feedback potentiometer has been disabled)?

2
  • Not that I am aware of. I made no modifications to it.
    – CJ.
    Aug 31, 2017 at 15:16
  • Is it a continuous rotation servo ? Can you give the brand and type and a link to where you bought it ?
    – Jot
    Aug 31, 2017 at 16:32
1

I had a bunch of SG90 mini servos so I tried your code. My servos turn 0 -> 180 -> 0 -> 180 -> 0 -> 180, over and over. No 360 spins at all.

  • Maybe your servo is defect? (can you check with another servo?)
  • Maybe it is not getting enough power? (how are you powering it?) It needs at least 4.8V and at least 220mA
  • Maybe it doesn't get a strong clean PWM signal? (You'll probably need an oscilloscope to check this)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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