servo moving in 2 directions with buttons UPDATE: IM STUPID

here is my code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int buttonState = 0;
int buttonState2 = 0;
int pos = 0;    // variable to store the servo position
const int buttonPin = 3;
const int buttonPin2 = 5;
void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT);
  pinMode(buttonPin2, INPUT);

void loop() {
   buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH) {
   delay(15);                       // waits 15ms for the servo to reach the position
  else if(buttonState2 == HIGH){
   delay(15);                       // waits 15ms for the servo to reach the position

I have 2 buttons and a servo. The button on pin 3 will make the servo rotate correctly. However, I want the other button to make the servo rotate the other way, and it will not. I have tried plugging the other button into 3 and it works there. I think I must be dong something simple wrong.

 pinMode(buttonPin, INPUT);
  pinMode(buttonPin2, INPUT);

Have you got pulldown resistors holding the inputs LOW when the buttons are not pressed ? I suspect not

A suggestion:

Change the code to

  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);

to turn on the built in pullup resistors, wire the switches to take the inputs LOW when the switches are closed and test for LOW to detect button presses

thank you for your reply, it was actually much more simple, I had forgotten

buttonState2 = digitalRead(buttonPin2);

so it wasn't reading the second button's input

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