Hey guys, I'm new at this so I apologize if it's been asked before. I know this is a noob question but I'm following a simple tutorial I found for a two button servo setup where one button makes the servo rotate clockwise and the other makes it rotate counter-clockwise. However right now, the servo only moves when the button is being pressed. How can I redo this code so that the servo will perform the rotation after merely a click of the button and not having to hold it down for the duration of the spin? I hope this explanation makes sense. The code is below.
#include <Servo.h>
const int buttonPin = 2;
const int buttonPin2 = 4;
int buttonState = 0;
int buttonState2 = 0;
Servo servoA;
int position = 0;
void setup()
{
servoA.attach(9);
pinMode(buttonPin, INPUT);
pinMode(buttonPin2,INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
buttonState2 = digitalRead(buttonPin2);
if(buttonState ==HIGH && position < 180){
servoA.write(position++);
delay(5);
}
if(buttonState2 == HIGH && position > 3){
servoA.write(position--);
delay(5);
}
}
I found for a two button servo setup where one button makes the servo rotate clockwise and the other makes it rotate counter-clockwise. However right now, the servo only moves when the button is being pressed. How can I redo this code so that the servo will perform the rotation after merely a click of the button and not having to hold it down for the duration of the spin?
May be too simple for what you want.
//zoomkat servo button test 12-29-2011
// Powering a servo from the arduino usually *DOES NOT WORK*.
#include <Servo.h>
int button1 = 4; //button pin, connect to ground to move servo
int press1 = 0;
int button2 = 5; //button pin, connect to ground to move servo
int press2 = 0;
Servo servo1;
void setup()
{
pinMode(button1, INPUT);
pinMode(button2, INPUT);
servo1.attach(7);
digitalWrite(4, HIGH); //enable pullups to make pin high
digitalWrite(5, HIGH); //enable pullups to make pin high
}
void loop()
{
press1 = digitalRead(button1);
if (press1 == LOW)
{
servo1.write(170);
}
press2 = digitalRead(button2);
if (press2 == LOW)
{
servo1.write(10);
}
}
enum servoState {STOP, SEEK1, SEEK2};
servoState state = STOP;
void loop()
{
// handle button 1
if (digitalRead(buttonPin1) == HIGH and buttonState1 == LOW)
{
state = SEEK1;
buttonState1 = HIGH;
delay(10);
}
else if (digitalRead(buttonPin1) == LOW and buttonState1 == HIGH)
{
buttonState1 = LOW;
}
// handle button 2
if (digitalRead(buttonPin2) == HIGH and buttonState2 == LOW)
{
state = SEEK2;
buttonState2 = HIGH;
delay(10);
}
else if (digitalRead(buttonPin2) == LOW and buttonState2 == HIGH)
{
buttonState2 = LOW;
}
// handle servos
if (state == SEEK1 and position < 180)
{
servoA.write(position++);
delay(5);
}
else if (state == SEEK2 and position > 3)
{
servoA.write(position--);
delay(5);
}
else if (position <= 3 or position >= 180)
{
state = STOP;
}
}