Servo won't stop jittering around

Hi! So, I scavenged some code for servos so it could be controlled with a button

Here’s the code:

#include <Servo.h>

Servo myservo;

const int button = 8;
const int servo = 3;
const int pos1 = 100;
const int pos2 = 180;

void setup() {
  myservo.attach(servo);
  pinMode(button, INPUT);

}

void loop(){
  int buttonState = digitalRead(button);
  if(buttonState == LOW){
    myservo.write(pos1);
  }
  else{
    myservo.write(pos2);
  }
}

This code was working perfectly before, but now, whenever the button is in LOW state, the servo just jitters around (about -+10 degrees, it’s not a small jitter) and it won’t stop. I’d like to know if it’s some error in the code or a hardware error with the servo.

It’s an Sg90 servo and I’m using an Arduino Leonardo.

Thanks in advance!

EDIT: This isn’t the original code. The scavenged part of the code is only the setup.

How is the button wired ? Pull up or pull down added ? (Suggestion use INPUT_PULLUP)

ToxicCow22:
This code was working perfectly before… I’d like to know if it’s some error in the code or a hardware error with the servo.

The Rational Manager holds that something must have changed, if it was working but now it isn’t.

So what changed?

ToxicCow22:
It’s an Sg90 servo

Even those tiny ones can draw the best part of 750mA: how’s it powered?

It might be a good idea to debounce the button too. Or you're in danger of writing different values to the servo far too fast for it to ever get to where you are sending it.

Steve

slipstick:
It might be a good idea to debounce the button too. Or you're in danger of writing different values to the servo far too fast for it to ever get to where you are sending it.

Steve

That's a good point, but doesn't explain why it used to work....

wilfredmedlin:
That's a good point, but doesn't explain why it used to work....

That's true enough...but I've seen too many people saying "Nothing has changed" which later turns out to mean "except I took it all apart and put it together again wrong and then changed a few lines of code but they should do the same thing". I may be getting cynical in my old age.

But then those SG90s aren't the most reliable servos ever made so perhaps one useful thing to do would be to simply try it with a different servo. And if the setup is powered from a battery check its voltage because low voltage can cause servo hunting too.

Steve

slipstick:
And if the setup is powered from a battery check its voltage because low voltage can cause servo hunting too.

And battery voltage changes with use pretty much by definition of it being a battery.

The Rational Manager, at least the fault finding section, should be compulsory reading. I've used ot quite often as a slide or page or two in material I created over the years.

(But the tl/dr is that if it used to work, and doesn't now, something changed....)