#include <Adafruit_GFX.h> // Core graphics library
#include <Adafruit_ILI9341.h> // ILI9341 driver for TFT
#include <TouchScreen.h> // Touchscreen library
// TFT display pins
#define TFT_CS 10
#define TFT_RST 9
#define TFT_DC 8
// Touchscreen pins (analog pins for XP, YP, and digital pins for XM, YM)
#define YP A3 // Must be an analog pin, use "A" prefix
#define XM A2 // Must be an analog pin, use "A" prefix
#define YM 9 // Can be a digital pin
#define XP 8 // Can be a digital pin
// Calibration for touch screen
#define TS_MINX 150
#define TS_MAXX 920
#define TS_MINY 120
#define TS_MAXY 900
// Threshold for pressure sensing
#define MINPRESSURE 10
#define MAXPRESSURE 1000
// Initialize TFT and touch screen objects
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
void setup() {
Serial.begin(9600);
// Initialize the TFT display
tft.begin();
tft.setRotation(1); // Set rotation for landscape mode, change as needed
tft.fillScreen(ILI9341_BLACK); // Clear the screen to black
// Display initial message
tft.setTextSize(2);
tft.setTextColor(ILI9341_WHITE);
tft.setCursor(40, 100);
tft.print("Touch the screen");
// Draw a test rectangle to detect touch
tft.drawRect(50, 150, 120, 60, ILI9341_RED);
}
void loop() {
// Read the touch point
TSPoint p = ts.getPoint();
// If pressure is within a valid range
if (p.z > MINPRESSURE && p.z < MAXPRESSURE)
{
// Map the touch coordinates to the display coordinates
int x = map(p.x, TS_MINX, TS_MAXX, 0, tft.width());
int y = map(p.y, TS_MINY, TS_MAXY, 0, tft.height());
// Check if the touch is within the rectangle drawn on the screen
if (x > 50 && x < 170 && y > 150 && y < 210) {
// Change the rectangle color on touch
tft.fillRect(50, 150, 120, 60, ILI9341_GREEN);
tft.setCursor(60, 165);
tft.setTextColor(ILI9341_BLACK);
tft.print("Touched!");
delay(500); // Wait before resetting the rectangle
// Reset the rectangle after a delay
tft.fillRect(50, 150, 120, 60, ILI9341_RED);
}
// Debug output: Print the touch coordinates
Serial.print("X = "); Serial.print(x);
Serial.print("\tY = "); Serial.print(y);
Serial.print("\tPressure = "); Serial.println(p.z);
}
// Reset the pin modes for touch after reading
pinMode(XM, OUTPUT);
pinMode(YP, OUTPUT);
}
Loading
ili9341-cap-touch
ili9341-cap-touch