#include <Arduino.h>
#include <ESP32Servo.h>
#include <ezButton.h>
#include <LiquidCrystal_I2C.h> // Thư viện điều khiển LCD với I2C
#define BUTTON_PIN 4 // ESP32 pin GPIO21 connected to button's pin
#define SERVO_PIN 26 // ESP32 pin GPIO26 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
LiquidCrystal_I2C lcd2(0x27, 16, 2); // Địa chỉ I2C của LCD là 0x27, màn hình 16x2
// variables will change:
int pos = 90; // 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
lcd2.init(); // Khởi tạo LCD
lcd2.backlight(); // Bật đèn nền LCD
servo.write(pos); // Gửi vị trí ban đầu của servo
lcd2.setCursor(0, 0);
lcd2.print("DONG CUA"); // Hiển thị "DONG CUA" khi khởi động (vị trí 0 độ)
}
void loop() {
button.loop(); // MUST call the loop() function first
if (button.isPressed()) {
// change angle of servo motor
if (pos == 0) {
pos = 90;
lcd2.clear(); // Xóa nội dung cũ trên LCD
lcd2.setCursor(0, 0); // Di chuyển con trỏ về đầu
lcd2.print("MO CUA"); // Hiển thị "MO CUA"
} else if (pos == 90) {
pos = 0;
lcd2.clear(); // Xóa nội dung cũ trên LCD
lcd2.setCursor(0, 0); // Di chuyển con trỏ về đầu
lcd2.print("DONG CUA"); // Hiển thị "DONG CUA"
}
// control servo motor according to the angle
Serial.print("The button is pressed => rotate servo to ");
Serial.print(pos);
Serial.println("°");
servo.write(pos); // Điều khiển servo đến vị trí tương ứng
}
}