Tin tức - Blog

Code mẫu sản phẩm Màn Hình Cảm Ứng Arduino TFT Shield 2.4 Inch ILI9341

30/06/2026

Code mẫu sản phẩm Màn Hình Cảm Ứng Arduino TFT Shield 2.4 Inch ILI9341 CG000259

#include <MCUFRIEND_kbv.h>

#include <Adafruit_GFX.h>

#include <TouchScreen.h>

 

MCUFRIEND_kbv tft;

// CHÂN CẢM ỨNG

#define YP A1

#define XM A2

#define YM 7

#define XP 6

 

// TRỞ CẢM ỨNG CHẠY DẢI 200-500

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

 

//THÔNG SỐ CALIB

#define TS_LEFT 120

#define TS_RT 900

#define TS_TOP 80

#define TS_BOT 940

 

// XOAY MÀN

#define ROTATION 3

//KÍCH THƯỚC GỐC

const int16_t BASE_W = 240;

const int16_t BASE_H = 320;

 

void setup() {

  Serial.begin(9600);

 

  uint16_t id = tft.readID();

  Serial.print("TFT ID = 0x");

  Serial.println(id, HEX);

 

  if (id == 0xD3D3 || id == 0xFFFF || id == 0x0000) id = 0x9341;

 

  tft.begin(id);

  tft.setRotation(ROTATION);

  tft.fillScreen(0x0000);

 

  tft.setTextColor(0xFFFF);

  tft.setTextSize(2);

  tft.setCursor(10, 10);

  tft.print(" TFT 2.4 ILI9341");

 

  tft.setTextSize(2);

  tft.setCursor(10, 35);

  tft.print("LKCG.VN");

 

}

 

void loop() {

  TSPoint p = ts.getPoint();

 

  pinMode(XM, OUTPUT);

  pinMode(YP, OUTPUT);

 

  if (p.z < 50 || p.z > 1000) return;

 

  //CHỈNH HƯỚNG TỌA ĐỘ

  int16_t x0 = map(p.x, TS_LEFT, TS_RT, 0, BASE_W);  // đảo ngang

  int16_t y0 = map(p.y, TS_BOT, TS_TOP, 0, BASE_H);

  // TS_RT, TS_LEFT

  //TS_TOP, TS_BOT

 

  // Chặn biên tránh tràn

  x0 = constrain(x0, 0, BASE_W - 1);

  y0 = constrain(y0, 0, BASE_H - 1);

 

  // 2) Xoay toạ độ theo rotation thực tế của màn

  uint8_t r = tft.getRotation() & 3;

  int16_t x, y;

 

  switch (r) {

    case 0:  // portrait

      x = x0;

      y = y0;

      break;

 

    case 1:  // landscape

      x = y0;

      y = BASE_W - 1 - x0;

      break;

 

    case 2:  // portrait (ngược)

      x = BASE_W - 1 - x0;

      y = BASE_H - 1 - y0;

      break;

 

    case 3:  // landscape (ngược)

      x = BASE_H - 1 - y0;

      y = x0;

      break;

  }

 

  //  Vẽ điểm chạm + in toạ độ

  // (tft.width/height đã thay đổi theo rotation)

 

  if (x >= 0 && x < tft.width() && y >= 0 && y < tft.height()) {

    tft.fillCircle(x, y, 3, 0xFFFF);

 

    Serial.print("raw(");

    Serial.print(p.x);

    Serial.print(",");

    Serial.print(p.y);

    Serial.print(")  ->  xy(");

    Serial.print(x);

    Serial.print(",");

    Serial.print(y);

    Serial.println(")");

  }

}

 

Bình luận (0)

Viết bình luận :

Hotline
0945485187