#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <XPT2046_Touchscreen.h>

// 引脚定义
#define TFT_CS 15
#define TFT_DC 2
#define TFT_RST 4
#define TOUCH_CS 5
#define LED_PIN 25

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
XPT2046_Touchscreen ts(TOUCH_CS);

bool ledState = false;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);

  tft.begin();
  ts.begin();

  tft.fillScreen(ILI9341_BLACK);
  tft.setRotation(1);

  drawButton(false); // 初始状态绘制按钮
}

void loop() {
  if (ts.touched()) {
    TS_Point p = ts.getPoint();

    // 校准触摸点坐标
    int x = map(p.y, 200, 3800, 0, 240);
    int y = map(p.x, 200, 3800, 0, 320);

    // 检查触摸是否在按钮范围内
    if (x > 50 && x < 200 && y > 100 && y < 160) {
      ledState = !ledState;
      digitalWrite(LED_PIN, ledState ? HIGH : LOW);
      drawButton(ledState);
      delay(300); // 防抖
    }
  }
}

// 绘制按钮
void drawButton(bool state) {
  if (state) {
    tft.fillRoundRect(50, 100, 150, 60, 10, ILI9341_GREEN);
    tft.setTextColor(ILI9341_BLACK);
    tft.setTextSize(2);
    tft.setCursor(80, 120);
    tft.print("ON");
  } else {
    tft.fillRoundRect(50, 100, 150, 60, 10, ILI9341_RED);
    tft.setTextColor(ILI9341_WHITE);
    tft.setTextSize(2);
    tft.setCursor(80, 120);
    tft.print("OFF");
  }
}
Loading
ili9341-cap-touch