button state changes. jitter. help please.

Hi all, so I want to use an input (flip switch) to turn a servo. Code is below. Problem being I am getting quite a bit of jitter on the line, Like I flip from on to off and the numbers go from 1 to 0 then a 1 and a 1 then all 0's. How can I stop that jitter. My wiring is as follows.

Servo --> gnd to arduino gnd, 5v to arduino 5v, signal to arduino pin 8
Switch --> lead 1 to arduino 5v, lead 2 to arduino pin 9 (when switch turned off, pin reads no voltage AKA LOW)

#include <Servo.h>

int myservoPin = 8;
int switchPin = 9;
int switchpinState;
Servo myservo;

void setup() {
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(myservoPin, OUTPUT);
  myservo.attach(myservoPin);
} 

void loop() {
  switchpinState = digitalRead(switchPin);
  
  
  if (switchpinState == HIGH) {
    myservo.write(70); 
  }
  else {
    myservo.write(-70);
  }  
  
  Serial.println(switchpinState);  

}

ilovearduinosomuch:
Servo --> gnd to arduino gnd, 5v to arduino 5v, signal to arduino pin 8

This is the usual problem. As the servo draws current it causes the voltage on the arduino 5v supply to drop. This then leads to unpredictable behaviour. Sometimes resetting it, sometimes causing it to crash, sometimes just causing I/O errors.

You should really use an independent power source for your servo, (but connecting the Ground of this to the Arduino GND)

The servo is an inductive load and you have no protection diode for the turn-off surge.

It's a very lightweight servo?
It should be on a motor circuit anyway.

Also what Ken noted, +1.

And you may be getting switch bounce in there too.

If you temporarily add a short delay() - say delay(100) - as the last thing in loop() it will stop switch bounce if that is the problem. A better system is illustrated in several things at a time.

If that does not stop the problem you will know it is not swtich bounce.

...R

If you replace the servo with an LED and it still happens then it is contact bounce.
If it stops then you have a power supply problem.

Your flip switch has "break-before-make" contacts. During the small "break" interval the input is floating and giving erratic results. Using INPUT_PULLUP will prevent this floating condition (but will not prevent bounce).

dlloyd:
Your flip switch has "break-before-make" contacts. During the small "break" interval the input is floating and giving erratic results. Using INPUT_PULLUP will prevent this floating condition (but will not prevent bounce).

A small capacitor across the switch will kill the bounce, as Nick Gammon shows with a 1 uF cap in his blog page touring switches.

Or wire you switch up correctly.
http://www.thebox.myzen.co.uk/Tutorial/Inputs.html