I am making a project which requires a servo to turn 90 degrees by pushing a button, and then return to its original position after pushing the button again. I am unsure of how to get it to stay at one position between button presses. Any help would be greatly appreciated!
#include <Servo.h>
const int button1Pin = 4;
Servo servo1;
void setup()
{
pinMode(button1Pin, INPUT);
servo1.attach(9);
}
void loop()
{
int button1State;
int position;
button1State = digitalRead(button1Pin);
if (button1State == LOW){
{
servo1.write(45);
}}
else {
servo1.write(135);
}
}
Search in the forum search box in the upper right f this page for "servo toggle" and you might find similar previous discussions. Below is some toggle test code, but can't remember how well it worked.
//zoomkat servo button toggle test 4-28-2012
#include <Servo.h>
int button = 5; //button pin, connect to ground to move servo
int press = 0;
Servo servo;
boolean toggle = true;
void setup()
{
pinMode(button, INPUT); //arduino monitor pin state
servo.attach(7); //pin for servo control signal
digitalWrite(5, HIGH); //enable pullups to make pin high
}
void loop()
{
press = digitalRead(button);
if (press == LOW)
{
if(toggle)
{
servo.write(160);
toggle = !toggle;
}
else
{
servo.write(20);
toggle = !toggle;
}
}
delay(500); //delay for debounce
}
obsean:
How can I get this script to switch from one servo position to another and then return to the original spot?
Simple button servo test code. Not sure just what you want.
//zoomkat servo button test 7-30-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;
Servo servo1;
void setup()
{
pinMode(button1, INPUT);
servo1.attach(7);
digitalWrite(4, HIGH); //enable pullups to make pin high
}
void loop()
{
press1 = digitalRead(button1);
if (press1 == LOW)
{
servo1.write(160);
}
else {
servo1.write(20);
}
}