#include <ESP32Servo.h>
#include <ezButton.h>
#define BUTTON_PIN1 21 // ESP32 pin GIOP21 connected to button's pin
#define BUTTON_PIN2 22 // ESP32 pin GIOP22 connected to button's pin
#define SERVO_PIN 26 // ESP32 pin GIOP26 connected to servo motor's pin
ezButton button1(BUTTON_PIN1); // create ezButton object that attach to pin 7;
ezButton button2(BUTTON_PIN2); // create ezButton object that attach to pin 6;
Servo servo; // create servo object to control a servo
// variables will change:
int angle = 0; // the current angle of servo motor
int targetAngle = 0; // the target angle for the servo motor
void setup() {
Serial.begin(9600); // initialize serial
button1.setDebounceTime(40); // set debounce time to 40 milliseconds
button2.setDebounceTime(360); // set debounce time to 360 milliseconds
servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object
servo.write(angle);
}
void loop() {
button1.loop(); // MUST call the loop() function first
button2.loop(); // MUST call the loop() function first
int btn1State = button1.getState();
int btn2State = button2.getState();
if (button2.isPressed()) {
// change angle of servo motor
if (targetAngle != 90)
targetAngle = 90;
else if (targetAngle != 0)
targetAngle = 0;
}
if (button1.isPressed()) {
// change angle of servo motor
if (targetAngle != 90)
targetAngle = 90;
else if (targetAngle != 0)
targetAngle = 0;
}
// move servo motor towards the target angle
if (angle != targetAngle) {
if (angle < targetAngle) {
angle++;
} else {
angle--;
}
servo.write(angle);
delay(0); // adjust the delay value to control the speed of the servo motor movement
}
}