donmike25 icon

servo with one push button control

donmike25 | PRO | 03/22/16 01:18:35 AM UTC | 0 ⭐ | 159 👁️ | Never ⏰ | []
C |

1.74 KB

|

None

|

0 👍

/

0 👎

#include <Servo.h> 
02
03 // Set digital pin numbers:
04 const int servoPin = 8;  // The number of the Servo pin
05 const int buttonPin = 9;  // The number of the Pushbutton pin
06
07 int buttonState = 0;  // Variable for reading the pushbutton status
08 int directionState = 0;  // Variable for reading direction of the servo
09
10 Servo myservo;  // Create servo object to control a servo 
11
12 int pos = 0;  // Variable to store the servo position 
13
14
15 void setup() {
16   myservo.attach(8);  // attaches the servo on pin 8 to the servo object 
17   pinMode(buttonPin, INPUT);  // initialize the pushbutton pin as an input
18 }
19
20 void loop(){
21   // read the state of the pushbutton value:
22   buttonState = digitalRead(buttonPin);
23
24   if (directionState == 0){
25     //The button is pushed
26     if (buttonState == HIGH) {
27       directionState = 1;// The direction for the servo is clockwise
28
29       // goes from 0 degrees to 180 degrees in steps of 1 degree
30       for(pos = 0; pos < 180; pos=pos+1)
31       {
32         myservo.write(pos);  // tell servo to go to position in variable ‘pos’ 
33         delay(15);  // waits 15ms for the servo to reach the position 
34       }
35     }
36
37   } else if (directionState == 1) {
38     // The button is pushed
39     if (buttonState == HIGH) {
40       directionState = 0;  // The direction for the servo is anti-clockwise 
41
42       // goes from 180 degrees to 0 degrees in steps of 1 degree 
43       for(pos = 180; pos>=1; pos=pos–1)
44       {
45         myservo.write(pos);  // tell servo to go to position in variable ‘pos’ 
46         delay(15);  // waits 15ms for the servo to reach the position 
47       }
48     }
49   }
50 }

Comments