Toggle switch servo control

I am attempting to control a servo with a toggle switch. When the switch is in one position, the servo should move to 30 degrees. When the switch is flipped, it should move to 150 degrees. The idea here is to engage or disengage a brake on a small wind turbine (senior design project).

The sketch I have does move the servo to the correct positions, but without flipping the switch, the switch state alternates every 6-7 seconds causing the servo to move back and forth.

The serial monitor supports this. I get 6-7 0s and then 6-7 1s.

Thanks!

#include <Servo.h>
const int killswitch = 3;
const int brakeservosignal = 2;
static int state;


Servo brakeservo;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(killswitch,INPUT);
brakeservo.attach(brakeservosignal);
brakeservo.write(90);
}
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(digitalRead(killswitch));
  delay(1000);
  brakeservo.write((digitalRead(killswitch)) ? 30 : 150);
}

How your switch wired?

1 Like

hi @acswave ,

Welcome to the forum..

If it's an Uno flip the servo and buttons pins..
servo needs pwm, button not so much..

Uno Servo Button

good luck.. ~q

No change in performance.

One leg to digital 3, one leg to ground. It does not matter if the switch functions as normally open or closed, so a pull up resistor shouldn't be needed if my understanding is correct.

Try this:

Change the pinMode line to pinMode(killswitch,INPUT_PULLUP);

That will ensure that the input pin is in a known (HIGH) state when the switch is open. Otherwise the pin is floating and could return HIGH or LOW at random.

2 Likes

It seems that your understanding is not good... Try to switch on an internal pullup as mentioned in the previous post

If the only connections to your switch are pin 3 and gnd, then you will need a pull up resistor.
The switch connects pin 3 to gnd for a LOW.
Pin 3 needs to go up to 5V for a HIGH.
Just leaving pin 3 open does not mean it is low or high.

Tom... :grinning: :+1: :coffee: :australia:

That seems to have done the trick. Thank you!

1 Like

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