Created
March 23, 2022 14:31
-
-
Save cmoz/64b1c19d30ac7c4807a59c28bacc219b to your computer and use it in GitHub Desktop.
accurate button and servo movement with debounce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Created by ArduinoGetStarted.com | |
* | |
* This example code is in the public domain | |
* | |
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-servo-motor | |
*/ | |
#include <Servo.h> | |
#include <ezButton.h> | |
// constants won't change | |
const int BUTTON_PIN = 7; // Arduino pin connected to button's pin | |
const int SERVO_PIN = 9; // Arduino pin connected to servo motor's pin | |
ezButton button(BUTTON_PIN); // create ezButton object that attach to pin 7; | |
Servo servo; // create servo object to control a servo | |
// variables will change: | |
int angle = 0; // the current angle of servo motor | |
void setup() { | |
Serial.begin(9600); // initialize serial | |
button.setDebounceTime(50); // set debounce time to 50 milliseconds | |
servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object | |
servo.write(angle); | |
} | |
void loop() { | |
button.loop(); // MUST call the loop() function first | |
if(button.isPressed()) { | |
Serial.println("The button is pressed"); | |
// change angle of servo motor | |
if(angle == 0) | |
angle = 90; | |
else | |
if(angle == 90) | |
angle = 0; | |
// control servo motor arccoding to the angle | |
servo.write(angle); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment