donmike25

servo with one push button control

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