I've been having trouble with a current project of mine where I need to make a servo rotate in a range of 60-120 degrees at a speed of 11 cycles per minute. I want one button that gets the servo rotating continuously and the other button to stop the rotation. With my current code it only swings for one cycle and the stop button won't interrupt it until the end. I tried to use a while loop to get the servo to continuously rotate but then the stop button won't work at all. Can someone help me?
Here's the code:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
const int start_button = 2; //start button
const int stop_button = 7; //stop button
int startbuttonState = 0;
int stopbuttonState = 0;
const int greenLED = 10;
const int redLED = 11;
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(start_button, INPUT);
pinMode(stop_button, INPUT);
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
}
void loop() {
startbuttonState = digitalRead(start_button);
stopbuttonState = digitalRead(stop_button);
if (startbuttonState == HIGH) {
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, LOW);
for (pos = 55; pos <= 115; pos += 1) { // goes from 55 degrees to 115 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(45); // waits 15ms for the servo to reach the position
}
for (pos = 115; pos >= 55; pos -= 1) { // goes from 115 degrees to 55 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(45); // waits 15ms for the servo to reach the position
}
}
else if (stopbuttonState == HIGH) {
digitalWrite(greenLED, LOW);
digitalWrite(redLED, HIGH);
myservo.write(90);
}
}