#include <Adafruit_GFX.h> // Core graphics library
#include <SPI.h> // this is needed for display
#include <Adafruit_ILI9341.h>
#include <Arduino.h> // this is needed for FT6206
#include <Adafruit_FT6206.h>
// The FT6206 uses hardware I2C (SCL/SDA)
Adafruit_FT6206 ctp = Adafruit_FT6206();
// Define TFT pins for ESP32
#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// Button dimensions and position
#define BUTTON_X 100
#define BUTTON_Y 100
#define BUTTON_W 100
#define BUTTON_H 50
// LED pin
#define LED_PIN 19
void setup(void) {
Serial.begin(115200);
Serial.println(F("Cap Touch Button Example"));
// Initialize the TFT and touchscreen
Wire.setPins(10, 8); // Redefine first I2C port to be on pins 10/8
tft.begin();
if (!ctp.begin(40)) { // Pass in 'sensitivity' coefficient
Serial.println("Couldn't start FT6206 touchscreen controller");
while (1);
}
Serial.println("Capacitive touchscreen started");
// Set up the TFT display
tft.fillScreen(ILI9341_BLACK);
// Draw the button
tft.fillRect(BUTTON_X, BUTTON_Y, BUTTON_W, BUTTON_H, ILI9341_WHITE);
tft.setCursor(BUTTON_X + 20, BUTTON_Y + 15);
tft.setTextColor(ILI9341_BLACK);
tft.setTextSize(2);
tft.println("Press");
// Set up the LED pin
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW); // Ensure the LED is off initially
}
void loop() {
// Wait for a touch
if (!ctp.touched()) {
return;
}
// Retrieve a point
TS_Point p = ctp.getPoint();
// Map touch points to screen coordinates
p.x = map(p.x, 0, 240, 240, 0);
p.y = map(p.y, 0, 320, 320, 0);
// Check if the touch is within the button area
if ((p.x >= BUTTON_X && p.x <= BUTTON_X + BUTTON_W) && (p.y >= BUTTON_Y && p.y <= BUTTON_Y + BUTTON_H)) {
// Turn on the LED
digitalWrite(LED_PIN, HIGH);
// Print to serial monitor
Serial.println("Button pressed");
// Optional: Provide visual feedback on the button press
tft.fillRect(BUTTON_X, BUTTON_Y, BUTTON_W, BUTTON_H, ILI9341_GREEN);
tft.setCursor(BUTTON_X + 20, BUTTON_Y + 15);
tft.setTextColor(ILI9341_WHITE);
tft.println("Press");
delay(200); // Debounce delay
// Reset the button to original color
tft.fillRect(BUTTON_X, BUTTON_Y, BUTTON_W, BUTTON_H, ILI9341_WHITE);
tft.setCursor(BUTTON_X + 20, BUTTON_Y + 15);
tft.setTextColor(ILI9341_BLACK);
tft.println("Press");
// Turn off the LED after the visual feedback
digitalWrite(LED_PIN, LOW);
}
}