I have a servo and on and off switch connected. digitRead(4) for some reason keeps outputting as HIGH even though the switch is set to OFF. So even when the switch is off, it still does actions inside the if statement. How do I fix this? Note that I have an Arduino Nano.
[pre]#include <Servo.h>
Servo servo; //initialize a servo object for the connected servo
int onoffswitch;
void setup() {
pinMode(4, INPUT);
servo.attach(9); // attach the signal pin of servo to pin9 of arduino
}
void loop() {
onoffswitch = digitalRead(4);
if (onoffswitch==1){
servo.write(60);
delay(1000);
servo.write(120);
delay(1000);
}
You need to use the pull-up or pull-down resistor for button to avoid the floating input use. The simplest way is use INPUT_PULLUP. See more detail in Arduino - Button tutorial