#include <Adafruit_GFX.h> // Core graphics library
#include <SPI.h> // Required for display
#include <Adafruit_ILI9341.h>
#include <Arduino.h> // Required for FT6206
#include <Adafruit_FT6206.h>
// Define pin numbers for relay control
#define RELAY_PIN 7
// The FT6206 uses hardware I2C (SCL/SDA)
Adafruit_FT6206 ctp = Adafruit_FT6206();
// The display also uses hardware SPI, plus #9 & #10
#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// Size of the color selection boxes and the paintbrush size
#define BOXSIZE 80
#define PENRADIUS 3
int oldcolor, currentcolor;
bool relayState = false;
void setup(void) {
Serial.begin(115200);
Serial.println(F("Relay Control with Touch Screen"));
// Set up the relay pin as an output
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW); // Initially turn off the relay
Wire.begin(10, 8); // Redefine the first I2C port to be on pins 10/8
tft.begin();
if (!ctp.begin(40)) { // Pass in the 'sensitivity' coefficient
Serial.println("Couldn't start FT6206 touchscreen controller");
while (1);
}
Serial.println("Capacitive touchscreen started");
tft.fillScreen(ILI9341_BLACK);
// Draw the buttons
drawButton(10, 10, BOXSIZE, BOXSIZE, "OFF", ILI9341_RED, ILI9341_WHITE);
drawButton(110, 10, BOXSIZE, BOXSIZE, "ON", ILI9341_GREEN, ILI9341_WHITE);
// Select the current color 'red'
currentcolor = ILI9341_RED;
}
void loop() {
delay(10);
// Wait for a touch
if (!ctp.touched()) {
return;
}
// Retrieve a point
TS_Point p = ctp.getPoint();
// Flip it around to match the screen.
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 areas
if (p.y >= 10 && p.y <= 90) {
if (p.x >= 10 && p.x <= 90) {
// Toggle the relay state when the "OFF" button is touched
relayState = false;
digitalWrite(RELAY_PIN, relayState ? HIGH : LOW);
drawButton(10, 10, BOXSIZE, BOXSIZE, "OFF", ILI9341_RED, ILI9341_WHITE);
drawButton(110, 10, BOXSIZE, BOXSIZE, "ON", ILI9341_GREEN, ILI9341_WHITE);
} else if (p.x >= 110 && p.x <= 190) {
// Toggle the relay state when the "ON" button is touched
relayState = true;
digitalWrite(RELAY_PIN, relayState ? HIGH : LOW);
drawButton(10, 10, BOXSIZE, BOXSIZE, "OFF", ILI9341_RED, ILI9341_WHITE);
drawButton(110, 10, BOXSIZE, BOXSIZE, "ON", ILI9341_GREEN, ILI9341_WHITE);
}
}
}
void drawButton(int x, int y, int width, int height, const char* label, uint16_t color, uint16_t textColor) {
tft.fillRect(x, y, width, height, color);
tft.drawRect(x, y, width, height, textColor);
int labelWidth = strlen(label) * 6; // Approximate width based on character count
int labelX = x + (width - labelWidth) / 2;
int labelY = y + (height - 8) / 2;
tft.setTextColor(textColor);
tft.setCursor(labelX, labelY);
tft.print(label);
}