Problem getting SG90 to increment in single degrees 0-180

I have a MicroServer 9g SG90 attached to pin D3 of an UNO R4 Wifi. I am trying to step through each degree between 0 and 180 one by one with 1sec delay, but it fails to move on every increment, skipping roughly 9 out of every 10 degrees on average. Am I expecting too much from this component? My (debugging) sketch includes Servo library by Michael Margolis v1.2.1 :

#include <Servo.h>

int servoPin=3;
int servoAngle=0;
int delayTime=1000;
int baudRate=115200;
int x;
Servo myServo;

void setup() {

  Serial.begin(baudRate);
  
  myServo.attach(servoPin);

}

void loop(){
  
  for ( x=0; x<181; x++) {

    myServo.write(x);
    delay(delayTime);

    Serial.println(x);
  
  }

}

Sounds like you've run into this problem:

The latest release of the Servo library (1.2.2 as of this writing) apparently includes the fix by @KurtE to address this problem.

2 Likes

Thank you so much. It will sound silly but I was following along with this youtube tutorial which recommended using the same version of Servo.h as he was to avoid a potential clash:

My Bad!
Very much appreciated.

1 Like

That makes steps 0 to 180, inclusive, which yields 181 steps.

Try this for 180 steps, 0 .. 179

for (x =0: x < 180: x++) {
1 Like

In that video at 20:20, it has the same jerky 10° movements.

Here's some non-jerky movements on an Uno in Wokwi:

1 Like

Thanks xfpd. x represents a specific angle writen to the servo, and I wanted to start at 0° and end at 180° so I guess that is 181 steps as intended.
I initially coded:

for (x =0: x < 180: x++) {

but then noticed the serial monitor was only counting up to 179 before returning to 0:


So I went to 181 as a 'quick' fix :grin:

1 Like

Thanks DaveX. Yes... I hadn't noticed that. They're definitely not 1° increments are they. Now that my sketch is working the change in movement is quite slight and very smooth.
Thanks also for introducing me to Wokwi... will definitely be having a play with that!

1 Like

The problem may not lie in the microcontroller. The electronics within the servomotor may be designed with a certain dead band to prevent the motor from vibrating with a constant input.

1 Like

Thanks stitech. I wasn’t sure what to expect from such a cheap plastic-geared component so I was unsure if it was even capable of performing accurate 1 degree stepping. Turns out it is.

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