You are on page 1of 1

servo + 2 pushbuttons

#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
const int buttonPin = 2; //sets pin 2 as button
const int buttonPin2 = 3; //sets pin 3 as button
const int ledPin = 13; // sets pin 13 as LED for testing purposes
int buttonState = 0; //sets button 1 as off
int buttonState2 = 0; // sets button 2 as off
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode (buttonPin, INPUT); // sets button as input
pinMode (ledPin, OUTPUT); // sets led as output
myservo.write(90); // starts servo at 90 degrees
}
void loop()
{
buttonState = digitalRead(buttonPin);
buttonState2 = digitalRead(buttonPin2);
if (buttonState == HIGH)
{
digitalWrite(ledPin, HIGH);
for(pos = 90; pos < 110; pos += 1) // goes from 90 degrees to 110 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable pos
delay(15); // waits 15ms for the servo to reach the position
}
delay (1500);
for(pos = 110; pos>=90; pos-=1) // goes from 110 degrees to 90 degrees
{
myservo.write(pos); // tell servo to go to position in variable pos
delay(15); // waits 15ms for the servo to reach the position
}
}
else {
digitalWrite(ledPin, LOW);
}
if (buttonState2 == HIGH)
{
digitalWrite(ledPin, HIGH);
for(pos = 90; pos >=70; pos -= 1) // goes from 90 degrees to 70 degrees in steps of 1 degree
{
myservo.write(pos); // tell servo to go to position in variable pos
delay(15); // waits 15ms for the servo to reach the position
}
delay (1500);
for(pos = 70; pos <=90; pos+=1) // goes from 70 degrees to 90 degrees
{
myservo.write(pos); // tell servo to go to position in variable pos
delay(15); // waits 15ms for the servo to reach the position
}
}
else {
digitalWrite(ledPin, LOW);
}
}

Karim

You might also like