0

I want a standard servo to rotate 180 degrees when button 1 is pressed and released. But I want the servo to rotate back to the initial position only when button 2 is being held down (& to stop rotating once button 2 is released). The arduino code I have now correctly allows the servo to make a full rotation 180 degrees with a press and release of button 1, but the servo also incorrectly rotates back to the initial position with a press and release of button 2 instead of stopping once released. Any help with the following code would be much appreciated:

#include <Servo.h>
Servo myservo;

int pos;

const int buttonPin = 2;
const int buttonPin2 = 3;
int buttonState = 0;
int buttonState2 = 0;

void setup()
{
  myservo.attach(9);

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

}
void loop()

{

  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2); 

  if (buttonState == HIGH) {  
    pos=180;
    myservo.write(180);    

  }

  if (buttonState2 == HIGH) {  
    pos-=1;
    myservo.write(pos); 

  } 
} 
  • Can you tell me what you get on a single press and release on button2.Dont press it for long just a sudden press and release.check it and update me – Mathews Sunny May 18 '17 at 17:05

1 Answers1

0

You don't have any delay in your loop. Your pos-=1; line will be executed with high frequency, and the servo is not able to follow that.

A simple solution would be to introduce a short delay (e.g. delay(20);) after your myservo.write(pos); so the servo has some time to actually reach the new position.

Laurenz
  • 1,810
  • 12
  • 25