|
| 1 | +/* |
| 2 | + * Drive a servo by using a push button |
| 3 | + * Uses the Bounce2 library. This library can be installed using the library manager |
| 4 | + */ |
| 5 | + |
| 6 | +#include <Servo.h> |
| 7 | +#include <SlowMotionServo.h> |
| 8 | +#include <Bounce2.h> |
| 9 | + |
| 10 | +SMSSmoothBounce myServoRight; |
| 11 | +SMSSmoothBounce myServoLeft; |
| 12 | +Bounce myButton; |
| 13 | + |
| 14 | +const byte servoRightPin = 4; |
| 15 | +const byte servoLeftPin = 3; |
| 16 | +const byte buttonPin = 5; |
| 17 | +const byte ledPin = 13; |
| 18 | + |
| 19 | +void setup() |
| 20 | +{ |
| 21 | + pinMode(ledPin, OUTPUT); |
| 22 | + /* when the button is pressed, the input is LOW */ |
| 23 | + pinMode(buttonPin, INPUT_PULLUP); |
| 24 | + |
| 25 | + myButton.attach(buttonPin); |
| 26 | + /* scan interval for debounce */ |
| 27 | + myButton.interval(5); |
| 28 | + |
| 29 | + myServoRight.setMin(750); |
| 30 | + myServoRight.setMax(1800); |
| 31 | + myServoLeft.setMin(1100); |
| 32 | + myServoLeft.setMax(2200); |
| 33 | + |
| 34 | + myServoRight.setSpeed(1.5); |
| 35 | + myServoLeft.setSpeed(1.5); |
| 36 | + |
| 37 | + myServoLeft.setReverted(true); |
| 38 | + |
| 39 | + myServoRight.setInitialPosition(0.0); |
| 40 | + myServoLeft.setInitialPosition(0.0); |
| 41 | + myServoRight.setPin(servoRightPin); |
| 42 | + myServoLeft.setPin(servoLeftPin); |
| 43 | + digitalWrite(ledPin, HIGH); |
| 44 | +} |
| 45 | + |
| 46 | +void loop() |
| 47 | +{ |
| 48 | + static float servoTarget = 0.0; |
| 49 | + |
| 50 | + /* update the state of the button */ |
| 51 | + myButton.update(); |
| 52 | + /* update the position of the servo */ |
| 53 | + SlowMotionServo::update(); |
| 54 | + |
| 55 | + if (myServoRight.isStopped() && myServoLeft.isStopped()) { |
| 56 | + digitalWrite(ledPin, LOW); |
| 57 | + if (myButton.fell()) { |
| 58 | + /* look at the button only when the servo is stopped */ |
| 59 | + /* change the target */ |
| 60 | + servoTarget = 1.0 - servoTarget; |
| 61 | + /* set the new target for the servo */ |
| 62 | + myServoRight.goTo(servoTarget); |
| 63 | + myServoLeft.goTo(servoTarget); |
| 64 | + digitalWrite(ledPin, HIGH); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
0 commit comments