So what im trying to do is get my servo to go from 0 to 90 when i press the button and stop. Then when i press it again it goes from 90 back to 0 then stop. basically every time i press the button it goes back and forth from 0 and 90.
Whats going on now is when i press the button it goes 0 to 90 but stays there and when i press the button again it jumps to 0 but then goes back to 90 again. Attached is the code im using and layout with a video.
Thank you for any help i can get with this.
#include <Servo.h>
// Set digital pin numbers:
const int servoPin = 8; // The number of the Servo pin
const int buttonPin = 9; // The number of the Pushbutton pin
int buttonState = 0; // Variable for reading the pushbutton status
int directionState = 0; // Variable for reading direction of the servo
Servo myservo; // Create servo object to control a servo
int pos = 0; // Variable to store the servo position
void setup() {
myservo.attach(8); // attaches the servo on pin 8 to the servo object
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
if (directionState == 0){
//The button is pushed
if (buttonState == HIGH) {
directionState = 1;// The direction for the servo is clockwise
// goes from 0 degrees to 90 degrees in steps of 1 degree
for(pos = 0; pos < 90; pos=pos+1)
{
myservo.write(pos); // tell servo to go to position in variable ‘pos’
delay(15); // waits 15ms for the servo to reach the position
}
}
} else if (directionState == 1) {
// The button is pushed
if (buttonState == HIGH) {
directionState = 0; // The direction for the servo is anti-clockwise
// goes from 90 degrees to 0 degrees in steps of 1 degree
// for (pos = 90; pos>=1; pos=pos–1)
{
myservo.write(pos); // tell servo to go to position in variable ‘pos’
delay(15); // waits 15ms for the servo to reach the position
}
}
}
}
Range_Finder.ino (1.59 KB)

