Toggle Switch for a Servo

I am trying to use a push button or even 2, to get my servo to move to either one position or another.

The problem I am having is that the servo is acting on its own, going back and forth from 45 to 135 and pausing, at random times even when no buttons are connected.

Here is the code I am using:

#include <Servo.h>

Servo servoPin9;
void sweepTo(Servo servo, int desiredAngle) {
int currentAngle = servo.read();
while(currentAngle != desiredAngle) {
if (currentAngle < desiredAngle) {
currentAngle = currentAngle + 1;
} else {
currentAngle = currentAngle - 1;
}
servo.write(currentAngle);
delay(10);
}
}
unsigned long time = 0;
unsigned long debounce = 2000UL;
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(4, INPUT);
pinMode(9, OUTPUT);
servoPin9.attach(9);
sweepTo(servoPin9, 45);
int dt=1000;

}

void loop() {
if (digitalRead(2) == HIGH && servoPin9.read() < 46 && millis() - time > debounce) {
delay(100); /* 100 milliseconds /
sweepTo(servoPin9, 135);
delay(1000); /
1000 milliseconds /
}
if (digitalRead(4) == HIGH && servoPin9.read() > 134 && millis() - time > debounce) {
delay(100); /
100 milliseconds /
sweepTo(servoPin9, 45);
delay(1000); /
1000 milliseconds */
}
}

Use:
pinMode(2, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);

Wire switches as S3 in the image.

Then look for a LOW.

The servo.read() function does not return the current position of the servo, read() returns the last commanded position (that was sent to the servo via the write() function). With the typical hobby servo, you can never know the real position of the servo. There is no way to read the feedback pot. Adafruit sells servos with the feedback broken out.

You can use the JC button library for toggle switches. It’s a lot more simple. The code will be shortened. JC Button