Arduino reading button as high

Hi. What I am trying to do is move a servo arm back and forth while the button is pushed down. And when it is not pushed down, I want nothing to happen. What is happening is that no matter what, my arduino is reading the button as HIGH right away when it is uploaded to the board when I am pressing it down. Do I have to add some sort of ‘else’ statement as if it were an ‘if’ statement. Or is there a better way of doing this. My servo is attached to digital pin 2 and my button to digital pin 3. Thank you!

#include <Servo.h>
Servo myservo;

void setup() {
  myservo.attach(2);
  pinMode(3, INPUT_PULLUP);
}
void startServo(int duration) {
  myservo.write(0);
  delay(duration);
  myservo.write(180);
  delay(duration);
}
void loop() {
  while (digitalRead(3) == HIGH) {
    startServo(1500);
  }
}
/code]
Ethan :)
pinMode(3, INPUT_PULLUP);

You're using the internal pullups. The button should be between the pin and ground. So your button will read HIGH when it is NOT pressed. When it is pressed it will read LOW.

Thank you so much! I will change it to just an INPUT.

Ethan :slight_smile: :slight_smile: :slight_smile:

That might be a mistake. How do you have the switch wired up? Your best bet would be to leave the pinMode as INPUT_PULLUP, wire the button between the pin and ground and change HIGH to LOW in this line.

while (digitalRead(3) == HIGH) {

http://www.gammon.com.au/switches

Thank you. I got it to work. After looking at the diagram I realized my resistor was on the wrong side. I didn't think it mattered that much but now I understand it a little more.

Ethan :) :) :)