I want to move a servo from position 0° to 180° when a push-button is being pressed. The servo should only stay at 180° when the button is pressed, so when I release it the servo should go back to 0° again. I have tried a couple of times, but the servo immediately goes to 180° without the button being pressed. What am I doing wrong?
(The resistor is 10k Ω)
Link to the Adruino hardware:
https://drive.google.com/file/d/1PmUy4P5cDaRq-YdIyxlf4c5gyaA4LGD0/view?usp=sharing
The compleate code:
// include the servo and button library
#include <Servo.h>
#include <Button.h>
// create a servo and button object
Servo myServo;
Button btnMoveServo(12);
// define the servo pin
const byte servoPin = 9;
void setup() {
// attach the servo to pin 9 and start the button
myServo.attach(servoPin);
btnMoveServo.begin();
}
void loop() {
// make the servo move when the button is pressed
if(btnMoveServo.pressed()){
myServo.write(180);
}
}
That's odd because there's nothing in your code that would EVER move the servo to 180. As you don't set it to anything special the attach() will move it to 90 and the button only seems to try to write(0) to it.
Steve
That was a mistake, I was meant to write 180 and not 0. The code is corrected now, thanks for noticing.
Do you think you might need some extra code to move the servo somewhere else if the button isn't pressed? At the moment it seems you move it to 180 when the button is pressed then leave it there forever.
Steve
slipstick:
Do you think you might need some extra code to move the servo somewhere else if the button isn't pressed? At the moment it seems you move it to 180 when the button is pressed then leave it there forever.
Steve
I've got it to work now, thank you! I wrote this line of code for the servo to move back again once the button is released:
void loop() {
// make the servo move to 180 degrees when the button is pressed
if(btnMoveServo.pressed()){
while(!btnMoveServo.released()){
myServo.write(180);
}
}
// make the servo go back to 0 degrees when released
else{
myServo.write(0);
}
}
That brings me another question: How do I make the servo go back to 0 if I release the button mid-movement? The links below shows a video example of what I mean:
How the servo is currently moving:
https://drive.google.com/file/d/19PVaZUJWTxwS2tQUSUsUdXtix8sI-WFx/view?usp=sharing
How I want the servo to move:
https://drive.google.com/file/d/1Wh4Bokb1R1CBWBDJ5Hizc4gOc5hh4G0y/view?usp=sharing
(video 2 is edited for demonstration)