Hey everyone,
I'm new to Arduino and hoping someone can help me out. I'm currently trying to program a servo that can move at three different speeds with three different buttons using an Arduino Uno R3 CH340. I've kind of gotten this to work with delay() to a point where it should suit my needs, ie the servo returns to its original position at different times/speeds, but I also want to add another button that will cancel the action of the previous button and return the servo to its original position. From what I understand from reading online so far, that's not possible with delay? Does anyone have any suggestions on what I could try instead?
Here's my code:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// constants won't change. They're used here to set pin numbers:
const int BUTTON_PIN1 = 2; // the number of the pushbutton pin
const int BUTTON_PIN2 = 3; // the number of the pushbutton pin
const int BUTTON_PIN3 = 4; // the number of the pushbutton pin
const int SERVO_PIN = 5; // the number of the pushbutton pin
const int CANCEL_PIN = 6;
int pos = 0; // variable to store the servo position
void setup() {
// initialize the pushbutton pin as an pull-up input
// the pull-up input pin will be HIGH when the switch is open and LOW when the switch is closed.
pinMode(BUTTON_PIN1, INPUT_PULLUP);
pinMode(BUTTON_PIN2, INPUT_PULLUP);
pinMode(BUTTON_PIN3, INPUT_PULLUP);
pinMode(CANCEL_PIN, INPUT_PULLUP);
myservo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object
}
void loop() {
int buttonState1 = digitalRead(BUTTON_PIN1); // read the state of the switch/button
int buttonState2 = digitalRead(BUTTON_PIN2); // read the state of the switch/button
int buttonState3 = digitalRead(BUTTON_PIN3); // read the state of the switch/button
int buttonState4 = digitalRead(CANCEL_PIN); // read the state of the switch/button
if (buttonState1 == LOW && pos <= 0) {
for (pos = 0; pos <= 135; pos += 1) {
myservo.write(pos);
delay(75);
}
}
if (buttonState1 == HIGH && pos >= 135) {
for (pos = 135; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(75);
}
}
if (buttonState2 == LOW && pos <= 0) {
for (pos = 0; pos <= 135; pos += 1) {
myservo.write(pos);
delay(140);
}
}
if (buttonState2 == HIGH && pos >= 135) {
for (pos = 135; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(140);
}
}
if (buttonState3 == LOW && pos <= 0) {
for (pos = 0; pos <= 135; pos += 1) {
myservo.write(pos);
delay(215);
}
}
if (buttonState3 == HIGH && pos >= 135) {
for (pos = 135; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(215);
}
}
}
Thanks for any tips in advance!