#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Khởi tạo màn hình OLED SSD1306
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Chân của Rotary Encoder
#define CLK 2
#define DT 3
#define SW 4
int menuIndex = 0; // Chỉ số của mục menu hiện tại
int lastStateCLK; // Trạng thái trước đó của CLK
bool buttonPressed = false; // Kiểm tra trạng thái của nút nhấn
// Danh sách các mục menu
String menuItems[] = {"Home", "Settings", "Wifi", "About"};
int menuLength = sizeof(menuItems) / sizeof(menuItems[0]);
void setup() {
// put your setup code here, to run once:
// Thiết lập chân cho Rotary Encoder
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
pinMode(SW, INPUT_PULLUP);
// Khởi tạo màn hình OLED SSD1306
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
lastStateCLK = digitalRead(CLK); // Đọc trạng thái ban đầu của CLK
Serial.begin(9600);
// Hiển thị menu ban đầu
displayMenu();
}
void loop() {
// put your main code here, to run repeatedly:
int currentStateCLK = digitalRead(CLK);
// Kiểm tra nếu có thay đổi ở CLK
if (currentStateCLK != lastStateCLK && currentStateCLK == HIGH) {
// Xác định chiều quay của encoder
if (digitalRead(DT) != currentStateCLK) {
menuIndex++;
Serial.print('+');
Serial.println(menuIndex);
if (menuIndex >= menuLength) menuIndex = 0; // Vòng lại mục đầu tiên
} else {
menuIndex--;
Serial.print('-');
Serial.println(menuIndex);
if (menuIndex < 0) menuIndex = menuLength - 1; // Vòng lại mục cuối
}
// Hiển thị menu cập nhật
displayMenu();
}
// Cập nhật trạng thái CLK
lastStateCLK = currentStateCLK;
// Kiểm tra trạng thái của nút nhấn (SW)
if (digitalRead(SW) == LOW) {
if (!buttonPressed) {
buttonPressed = true;
selectMenuItem();
}
} else {
buttonPressed = false;
}
}
// Hàm hiển thị menu
void displayMenu() {
display.clearDisplay();
for (int i = 0; i < menuLength; i++) {
if (i == menuIndex) {
display.setTextColor(SSD1306_BLACK, SSD1306_WHITE); // Mục đang chọn sẽ có nền trắng, chữ đen
} else {
display.setTextColor(SSD1306_WHITE); // Các mục khác có chữ trắng, nền đen
}
display.setCursor(0, i * 10); // Cách dòng 10 pixel để phù hợp với màn hình
display.println(menuItems[i]);
}
display.display();
}
// Hàm thực hiện hành động khi chọn một mục
void selectMenuItem() {
display.clearDisplay();
display.setCursor(0, 0);
display.setTextColor(SSD1306_WHITE);
display.print("Selected: ");
display.println(menuItems[menuIndex]);
display.display();
delay(1000); // Dừng 1 giây để hiển thị mục đã chọn
displayMenu(); // Quay lại menu
}