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 =;
while(currentAngle != desiredAngle) {
if (currentAngle < desiredAngle) {
currentAngle = currentAngle + 1;
} else {
currentAngle = currentAngle - 1;
unsigned long time = 0;
unsigned long debounce = 2000UL;
void setup() {
pinMode(2, INPUT);
pinMode(4, INPUT);
pinMode(9, OUTPUT);
sweepTo(servoPin9, 45);
int dt=1000;


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

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

Wire switches as S3 in the image.

Then look for a LOW.

The 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

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