Hi guys,
I'm quite new to programming and currently i'm trying to control a servo motor with a push button.
Means whenever i press it once, it will complete a cycle (turn 180 clockwise and back).
But currently i must hold it to make it turn or it'll just stop.
This is my code
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 3; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int pos = 0; // variable to store the servo position
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
myservo.attach(2); // attaches the servo on pin 9 to the servo object
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == LOW) {
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(10); // waits 15ms for the servo to reach the position
digitalWrite(3, HIGH);
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(10); // waits 15ms for the servo to reach the position
}
}
else {
digitalWrite(3, LOW);
// turn LED off:
for(pos = 0; pos < 0; pos += 1) // goes from 0 degrees to 0 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
}
}
}