-1

I'm fairly new to arduino, and on my own I'm trying to move a servo to the left and right using 2 buttons. I've got it working for the most part, however when I hold the button down nothing happens, and when I finally release the servo moves a certain amount based on how long I was holding the button down. I would like the servo to move when the button is being held down though. The servo also occasionally moves oddly and sporadically. I'm thinking its most likely a logic error in the code, but I can't figure it out. Could someone please tell me what they think I've done wrong? Thank you.

code:

#include <Servo.h>
Servo servo;

#define right 9
#define left 8

int angle = 90;
int angStep = 5;



void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(right, INPUT_PULLUP);
  pinMode(left, INPUT_PULLUP);
  servo.attach(2);
  servo.write(angle);
  Serial.print("Begin");
  Serial.print('\n');
  Serial.print(angle);
  Serial.print(angle);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(left) == HIGH && angle < 180){
    angle += angStep;
    Serial.print(angle);
    Serial.print('\n');
    servo.write(angle);
    delay(50);
  }

  if (digitalRead(right) == HIGH && angle > 0){
    angle -= angStep;
    Serial.print(angle);
    Serial.print('\n');
    servo.write(angle);
    delay(50);
  }
}
2
  • 3
    check for the opposite signal level at the button pin – jsotola Nov 18 '20 at 22:08
  • 1
    Connect the 'output' signals (that goes in the Arduino pin 8/9) instead to a resistor and a LED to see if it behaves like you expect. This rules out if there is a software or hardware problem. – Michel Keijzers Nov 18 '20 at 22:46
2

I think it's because you are using a pullup resistor, so it's constantly HIGH instead of constantly LOW. Try changing HIGH and LOW to the opposite.

1
  • I tried swapping the HIGH and LOW and nothing happened, so I just switched back to high and changed input_pullup to just input. Now the servo moves but just completely randomly and i don't know why it's so inconsistent. – john papp Nov 19 '20 at 16:27

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.