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);
}
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.
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.
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.