#include <SPI.h>
#include <TFT_eSPI.h>
#include <XPT2046_Touchscreen.h>
// กำหนดขา LED ตามที่ต่อในวงจร
#define LED_RED 27
#define LED_GREEN 22
#define LED_YELLOW 21
// กำหนดขา SPI สำหรับระบบ Touch Screen ของ Cheap Yellow Display
#define XPT2046_IRQ 36
#define XPT2046_MOSI 32
#define XPT2046_MISO 39
#define XPT2046_CLK 25
#define XPT2046_CS 33
SPIClass mySpi = SPIClass(VSPI);
XPT2046_Touchscreen ts(XPT2046_CS, XPT2046_IRQ);
TFT_eSPI tft = TFT_eSPI();
// ตัวแปรเก็บสถานะของ LED (false = ดับ, true = ติด)
bool stateRed = false;
bool stateGreen = false;
bool stateYellow = false;
// ฟังก์ชันสำหรับวาดปุ่มบนหน้าจอ
void drawButton(int x, int y, int w, int h, uint16_t color, String label, bool state) {
// หากสถานะเป็น true ให้แสดงสีปุ่ม หากเป็น false ให้แสดงสีเทาเข้ม
tft.fillRect(x, y, w, h, state ? color : TFT_DARKGREY);
tft.drawRect(x, y, w, h, TFT_WHITE); // ขอบปุ่ม
tft.setTextColor(state ? TFT_BLACK : TFT_WHITE); // ปรับสีตัวอักษรให้ตัดกับพื้น
tft.setTextSize(2);
tft.setCursor(x + 10, y + 30);
tft.print(label);
}
void setup() {
Serial.begin(115200);
// ตั้งค่าขา LED เป็น OUTPUT และเริ่มต้นให้ไฟดับ
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_YELLOW, OUTPUT);
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_YELLOW, LOW);
// เริ่มต้นจอแสดงผล
tft.init();
tft.setRotation(1); // หมุนจอเป็นแนวนอน
tft.fillScreen(TFT_BLACK); // พื้นหลังสีดำ
// เริ่มต้นระบบสัมผัส
mySpi.begin(XPT2046_CLK, XPT2046_MISO, XPT2046_MOSI, XPT2046_CS);
ts.begin(mySpi);
ts.setRotation(1);
// วาดปุ่มทั้ง 3 ปุ่มบนหน้าจอ
drawButton(20, 80, 80, 80, TFT_RED, " RED", stateRed);
drawButton(120, 80, 80, 80, TFT_GREEN, "GREEN", stateGreen);
drawButton(220, 80, 80, 80, TFT_YELLOW, "YELLOW", stateYellow);
}
void loop() {
// ตรวจสอบว่ามีการสัมผัสหน้าจอหรือไม่
if (ts.touched()) {
TS_Point p = ts.getPoint();
// แปลงค่าพิกัดการสัมผัส (ค่าดิบ) ให้ตรงกับความละเอียดจอ (320x240)
int touchX = map(p.x, 200, 3800, 0, 320);
int touchY = map(p.y, 200, 3800, 0, 240);
// ตรวจสอบว่าพิกัดที่กด อยู่ในพื้นที่ของปุ่ม RED หรือไม่
if (touchX > 20 && touchX < 100 && touchY > 80 && touchY < 160) {
stateRed = !stateRed; // สลับสถานะ
digitalWrite(LED_RED, stateRed); // สั่งเปิด/ปิด LED
drawButton(20, 80, 80, 80, TFT_RED, " RED", stateRed); // วาดปุ่มใหม่
delay(300); // หน่วงเวลาป้องกันการกดรัว (Debounce)
}
// ตรวจสอบปุ่ม GREEN
else if (touchX > 120 && touchX < 200 && touchY > 80 && touchY < 160) {
stateGreen = !stateGreen;
digitalWrite(LED_GREEN, stateGreen);
drawButton(120, 80, 80, 80, TFT_GREEN, "GREEN", stateGreen);
delay(300);
}
// ตรวจสอบปุ่ม YELLOW
else if (touchX > 220 && touchX < 300 && touchY > 80 && touchY < 160) {
stateYellow = !stateYellow;
digitalWrite(LED_YELLOW, stateYellow);
drawButton(220, 80, 80, 80, TFT_YELLOW, "YELLOW", stateYellow);
delay(300);
}
}
}Loading
esp32-2432s028r
esp32-2432s028r