Lara Grant

Press Button, Move Right, Press Again, Move Left

INPUT: 1 Momentary Button
OUTPUT: Two Servos – SG90 T Pro Micro Servos

DESCRIPTION: Press button once, both servos move right, push button again, both servos move left.

[code lang=”arduino” light=”true”] /*
* push button to rotate left
* push button to rotate right
*
* halloween workshop 2012
* source found: http://www.qrong.com/archives/46
* altered by lara grant
*/

#include <Servo.h>

// Set digital pin numbers:
const int servoPin = 7; // The number of the Servo1 pin
const int servoPin2 = 8; // The number of the Servo2 pin
const int buttonPin = 2; // The number of the Pushbutton pin

int buttonState = 0; // Variable for reading the pushbutton status
int directionState = 0; // Variable for reading direction of the servo

Servo myservo1; // Create servo object to control servo1
Servo myservo2; // Create servo object to control servo2

int pos = 0; // Variable to store the servo position

void setup() {
myservo1.attach(7); // attaches the servo on pin 7 to the servo object
myservo2.attach(8); // attaches the servo on pin 7 to the servo object
pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input

}

void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

if (directionState == 0){
//The button is pushed
if (buttonState == LOW) {
directionState = 1;// The direction for the servo is clockwise
for(pos = 0; pos < 180; pos=pos+1) // goes from 0 degrees to 180 degrees in steps of 1 degree
{
myservo1.write(pos); // tell servo to go to position in variable ‘pos’
myservo2.write(pos); // tell servo to go to position in variable ‘pos’
delay(15); // waits 15ms for the servo to reach the position
}
}

}
else if (directionState == 1) {
// The button is pushed
if (buttonState == LOW) {
directionState = 0; // The direction for the servo is anti-clockwise
for(pos = 180; pos>=1; pos=pos-1) // goes from 180 degrees to 0 degrees in steps of 1 degree
{
myservo1.write(pos); // tell servo to go to position in variable ‘pos’
myservo2.write(pos); // tell servo to go to position in variable ‘pos’
delay(15); // waits 15ms for the servo to reach the position
}
}
}

}

[/code]

Have your say