0
#include <Servo.h>
const int buttonPin = 3;
int buttonState = 0;

Servo myservo;   
void setup() {
    myservo.attach(2);    
    pinMode(buttonPin, INPUT);
}

void loop() {
    buttonState = digitalRead(buttonPin);   
    if (buttonState == HIGH){ myservo.write(90); }   
    else { myservo.write(155); }   
    delay(1000); 
}
4
  • 1
    And what exactly does not work? What do you see happending or not happending? What have you expected?
    – chrisl
    Oct 27, 2019 at 21:54
  • So it is supposed to move a servo when I push a button but the Servo just moves back and forth randomly.
    – Jonah W
    Oct 27, 2019 at 21:58
  • 2
    Floating input. Show your wiring.
    – Majenko
    Oct 27, 2019 at 22:09
  • You may also print buttonState and check it's value in the serial monitor.
    – Paul
    Oct 27, 2019 at 23:15

2 Answers 2

1

Just put your button between pin3 and GND, and use the internal pullup resistor like this:

#include <Servo.h>
const int buttonPin = 3;
int buttonState = 0;

Servo myservo;   
void setup()
{
    myservo.attach(2);    
    pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
    buttonState = digitalRead(buttonPin);
    if(buttonState == LOW)
    {
      myservo.write(90);
    }
    else
    {
      myservo.write(155);
    }   
    delay(1000); 
}
0

There are two problems you should pay attention to when using the button:

1
  • Since the servo pulse frequency is about 50 Hz it has a clock period of about 20 ms. This is more than enough to debounce buttons, so there is no need for it. Oct 28, 2019 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.