#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>
// Khai báo kết nối màn hình TFT LCD
#define TFT_CLK 13
#define TFT_MISO 12
#define TFT_MOSI 11
#define TFT_CS 10
#define TFT_DC 9
#define TFT_RST 8
// Khai báo kết nối nút bấm
#define BTN_UP 3
#define BTN_DOWN 4
#define BTN_LEFT 2
#define BTN_RIGHT 5
const unsigned long DEBOUNCE_DELAY = 50;
// Tạo đối tượng TFT
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST, TFT_CLK, TFT_RST, TFT_MISO);
// Biến trạng thái và mục tiêu chọn
int selectedOption = 0;
int maxOptions = 3; // Số lựa chọn
void setup() {
Serial.begin(9600);
// Khởi tạo màn hình TFT
tft.begin();
tft.setRotation(3); // Tuỳ chỉnh vị trí màn hình theo môi trường của bạn
// Khởi tạo nút bấm
pinMode(BTN_UP, INPUT_PULLUP);
pinMode(BTN_DOWN, INPUT_PULLUP);
pinMode(BTN_LEFT, INPUT_PULLUP);
pinMode(BTN_RIGHT, INPUT_PULLUP);
// Hiển thị giao diện ban đầu
showMainMenu();
}
void loop() {
// Đọc trạng thái nút bấm
int btnUpState = isButtonPressed(BTN_UP,0);
int btnDownState = isButtonPressed(BTN_DOWN,1);
int btnLeftState = isButtonPressed(BTN_LEFT,2);
int btnRightState = isButtonPressed(BTN_RIGHT,3);
// Kiểm tra nút bấm và xử lý
if (btnUpState) {
selectedOption = (selectedOption - 1 + maxOptions) % maxOptions;
showMainMenu();
}
if (btnDownState) {
selectedOption = (selectedOption + 1) % maxOptions;
showMainMenu();
}
if (btnRightState) {
// Chuyển sang màn hình thông số tương ứng với lựa chọn
showOptionScreen(selectedOption);
Serial.println(selectedOption);
}
// Xử lý các tác vụ khác tại đây
}
bool isButtonPressed(int buttonPin, int i) {
static unsigned long lastDebounceTime[4] = {0,0,0,0};
static int lastButtonState[4] = {HIGH,HIGH,HIGH,HIGH};
int buttonState = digitalRead(buttonPin);
bool buttonPressed = false;
if (buttonState != lastButtonState[i]) {
lastDebounceTime[i] = millis();
lastButtonState[i] = buttonState;
}
if ((millis() - lastDebounceTime[i]) > DEBOUNCE_DELAY) {
if (buttonState == lastButtonState[i]) {
if (buttonState == LOW) {
buttonPressed = true;
}
}
}
return buttonPressed;
}
void showMainMenu() {
/* tft.fillScreen(ILI9341_WHITE);
tft.setCursor(10, 10);
tft.setTextColor(ILI9341_BLACK);
tft.setTextSize(2);
*/
tft.println("Chon mot muc:");
// Hiển thị các lựa chọn
for (int i = 0; i < maxOptions; i++) {
tft.setCursor(30, 40 + i * 30);
if (i == selectedOption) {
tft.setTextColor(ILI9341_GREEN); // Mục tiêu đang được chọn
} else {
tft.setTextColor(ILI9341_WHITE);
}
tft.print("Muc " + String(i));
}
}
void showOptionScreen(int option) {
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(10, 10);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.print("Thong tin muc " + String(option));
// Hiển thị thông số của lựa chọn tại đây
}