You need to log in to create posts and topics.

376_TFT ILI9341 AND TOUCHSCREEN FOR CONTROL PANEL

The TFT ILI9341, along with its touchscreen, forms a very useful combination for creating a touch control panel. It is ideal for controlling devices and their functions, eliminating the need for separate keyboards and creating a compact device that offers greater convenience and saves space. The hardware we have assembled here consists of the TFT and the overlaid transparent touchscreen panel. We have prepared an aesthetically pleasing yet simple menu that controls a tri-color LED, three individual LEDs, a relay, a stepper motor, and a DC motor with an encoder capable of bidirectional movement. Upon starting the program, the aforementioned devices can be controlled, as well as the additive color of the tri-color LED. We have also added a touchscreen calibration routine with three calibration points. This value is automatically saved in ROM, but the calibration can be accessed at any time by clicking on any point in the title area of ​​the panel.

PROGRAM:

Including comments with a very clear structure. highlight the extra libraries for compilation: SPI.h, EEPROM.h, Servo.h, Adafruit_GFX.h
and Adafruit_ILI9341.h.

// DISPLAY ILI9341 WITH TOUCHSCREEN. DEFRAN26A

#include <SPI.h>
#include <EEPROM.h>
#include <Servo.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
const uint8_t TFT_CS = 10;
const uint8_t TFT_DC = 12;
const uint8_t XP = 9;
const uint8_t XM = A1;
const uint8_t YP = A0;
const uint8_t YM = 8;
// MOSI on D11, SCK on D13. TFT reset held high in the SimulIDE circuit.
// Hardware SPI. D12 is used for D/C in this write-only setup.
Adafruit_ILI9341 tft(TFT_CS, TFT_DC);
constexpr uint16_t BACKGROUND = 0xC6BF;  // Bright sky blue.
constexpr uint16_t HEADER = 0x581F;      // Electric violet.
constexpr uint16_t GOLD = 0xFFE0;
constexpr uint16_t CALIBRATION_BACKGROUND = 0x10AA;
constexpr uint16_t WHITE = 0xFFFF;
bool pressed = false;
bool touchDetected = false;
uint8_t releasedSamples = 0;
int16_t rawX[3], rawY[3];
const int16_t targetX[] = {24, 215, 24};
const int16_t targetY[] = {48, 48, 295};
long determinant = 0;

void drive(uint8_t pin, uint8_t level)
{
  digitalWrite(pin, level);
  pinMode(pin, OUTPUT);
}

bool contact()  // Detect contact between the layers using the Uno pull-up.
{
  pinMode(YM, INPUT);
  digitalWrite(YM, LOW);
  drive(XP, LOW);
  drive(XM, LOW);
  pinMode(YP, INPUT_PULLUP);
  delayMicroseconds(200);
  return digitalRead(YP) == LOW;
}

bool readTouch(int16_t &x, int16_t &y)  // Drive one layer and read the other with its pull-up disabled.
{
  if (!contact()) return false;
  pinMode(YP, INPUT);
  digitalWrite(YP, LOW);
  drive(XP, HIGH);
  delayMicroseconds(200);
  analogRead(YP);
  x = analogRead(YP);
  pinMode(XP, INPUT);
  digitalWrite(XP, LOW);
  pinMode(XM, INPUT);
  drive(YP, HIGH);
  drive(YM, LOW);
  delayMicroseconds(200);
  analogRead(XM);
  y = analogRead(XM);
  return contact();
}

bool newTouch(int16_t &x, int16_t &y)  // Register one press per touch. Three idle samples confirm release.
{
  touchDetected = readTouch(x, y);
  if (!touchDetected)
  {
    if (releasedSamples < 3) ++releasedSamples;
    if (releasedSamples == 3) pressed = false;
    return false;
  }
  releasedSamples = 0;
  if (pressed) return false;
  pressed = true;
  return true;
}

void calibrationTarget(uint8_t index)
{
  tft.fillScreen(CALIBRATION_BACKGROUND);
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.setCursor(10, 10); tft.print(F("Tap cross "));
  tft.print(index + 1);
  tft.print(F("/3"));
  tft.drawFastHLine(targetX[index] - 8, targetY[index], 17, GOLD);
  tft.drawFastVLine(targetX[index], targetY[index] - 8, 17, GOLD);
}

struct TouchCalibration
{
  int16_t x[3];
  int16_t y[3];
  uint16_t checksum;
};

long calibrationDeterminant(const int16_t *x, const int16_t *y)
{
  return (long)(x[1] - x[0]) * (y[2] - y[0])
       - (long)(x[2] - x[0]) * (y[1] - y[0]);
}

uint16_t calibrationChecksum(const TouchCalibration &data);

uint16_t calibrationChecksum(const TouchCalibration &data)
{
  uint16_t checksum = 0xA413;
  for (uint8_t i = 0; i < 3; ++i)
  {
    checksum = (checksum * 31U) ^ data.x[i];
    checksum = (checksum * 31U) ^ data.y[i];
  }
  return checksum;
}

bool loadCalibration()
{
  TouchCalibration data;
  EEPROM.get(0, data);
  for (uint8_t i = 0; i < 3; ++i)
    if (data.x[i] < 0 || data.x[i] > 1023 || data.y[i] < 0 || data.y[i] > 1023)
      return false;
  if (data.checksum != calibrationChecksum(data)) return false;
  const long savedDeterminant = calibrationDeterminant(data.x, data.y);
  if (labs(savedDeterminant) < 10000) return false;
  for (uint8_t i = 0; i < 3; ++i)
  {
    rawX[i] = data.x[i];
    rawY[i] = data.y[i];
  }
  determinant = savedDeterminant;
  return true;
}

void saveCalibration()
{
  TouchCalibration data = {};
  for (uint8_t i = 0; i < 3; ++i)
  {
    data.x[i] = rawX[i];
    data.y[i] = rawY[i];
  }
  data.checksum = calibrationChecksum(data);
  EEPROM.put(0, data);
}

void calibrate()
{
  do
  {
    for (uint8_t i = 0; i < 3; ++i)
    {
      calibrationTarget(i);
      unsigned long lastReport = millis();
      while (!newTouch(rawX[i], rawY[i]))
      {
        if (millis() - lastReport >= 2000)
        {
          lastReport = millis();
          Serial.print(F("Waiting for touch. A0 (YP) = "));
          Serial.println(analogRead(YP));
        }
        delay(10);
      }
      Serial.print(F("Calibration "));
      Serial.print(i + 1);
      Serial.print(F(" ADC X="));
      Serial.print(rawX[i]);
      Serial.print(F(" Y="));
      Serial.println(rawY[i]);
    }
    determinant = calibrationDeterminant(rawX, rawY);
    if (labs(determinant) < 10000)
      Serial.println(F("Calibration failed. Tap all three crosses again."));
  }
  while (labs(determinant) < 10000);
  saveCalibration();
}

constexpr uint16_t CARD = 0xFFFF;
constexpr uint16_t BORDER = 0x8CFB;
constexpr uint16_t MUTED = 0x42EE;
constexpr uint8_t ledPins[] = {7, 5, 6, 2, 3, 4};
constexpr uint16_t accents[] = {0xF948, 0x02FF, 0x04AC, 0xE360, 0xA237, 0x0492};
constexpr uint8_t ledCount = sizeof(ledPins) / sizeof(ledPins[0]);
bool ledOn[ledCount] = {};
constexpr uint8_t relayPin = A3;
constexpr uint8_t motorPlusPin = A4;
constexpr uint8_t motorMinusPin = A5;
constexpr int relaySwitchY = 206;
constexpr uint8_t servoPin = A2;
constexpr uint16_t INK = 0x1148;
Servo servoMotor;
bool relayOn = false;
constexpr uint8_t MOTOR_BUTTON_Y = 242;
constexpr uint8_t MOTOR_BUTTON_HEIGHT = 21;
uint8_t motorState = 1; // CCW, OFF, CW.
int servoAngle = 0;
int8_t heldServoDirection = 0;
unsigned long lastServoStep = 0;
constexpr unsigned long SERVO_HOLD_DELAY = 400;
constexpr unsigned long SERVO_REPEAT_INTERVAL = 140;
unsigned long servoRepeatDelay = SERVO_HOLD_DELAY;

int ledGroupX(uint8_t index)
{
  return 10 + (index / 3) * 114;
}

int ledRowY(uint8_t index)
{
  return 85 + (index % 3) * 35;
}

void drawLedGroups()
{
  const __FlashStringHelper *titles[] = {F("RGB"), F("MON")};
  const uint16_t colors[] = {0xFDC0, 0x27BD};
  for (uint8_t group = 0; group < 2; ++group)
  {
    const int x = ledGroupX(group * 3);
    tft.fillRoundRect(x, 52, 106, 143, 9, CARD);
    tft.drawRoundRect(x, 52, 106, 143, 9, BORDER);
    tft.fillRoundRect(x + 4, 56, 98, 25, 6, colors[group]);
    tft.setTextSize(2);
    tft.setTextColor(INK);
    tft.setCursor(x + 35, 61);
    tft.print(titles[group]);
    tft.drawFastHLine(x + 10, 114, 86, BORDER);
    tft.drawFastHLine(x + 10, 149, 86, BORDER);
  }
}

void drawToggle(uint8_t index)
{
  const int x = ledGroupX(index);
  const int y = ledRowY(index);
  const bool on = ledOn[index];
  const __FlashStringHelper *labels[] = {F("RED"), F("BLUE"), F("GREEN"), F("M1"), F("M2"), F("M3")};
  tft.setTextSize(1);
  tft.setTextColor(INK);
  tft.setCursor(x + 11, y + 2); tft.print(labels[index]);
  tft.fillRect(x + 11, y + 16, 24, 8, CARD);
  tft.setTextColor(MUTED);
  tft.setCursor(x + 11, y + 16); tft.print(on ? F("ON") : F("OFF"));
  tft.fillRoundRect(x + 56, y + 3, 38, 20, 10, on ? accents[index] : BORDER);
  tft.fillRoundRect(x + (on ? 76 : 59), y + 6, 14, 14, 7, WHITE);
}

void drawRelay()
{
  tft.fillRoundRect(10, 201, 220, 30, 9, 0xFEDA);
  tft.drawRoundRect(10, 201, 220, 30, 9, BORDER);
  tft.setTextSize(2);
  tft.setTextColor(INK);
  tft.setCursor(20, 208); tft.print(F("RELAY"));
  tft.setTextSize(1);
  tft.setCursor(145, 212); tft.print(relayOn ? F("ON") : F("OFF"));
  tft.fillRoundRect(180, relaySwitchY, 38, 20, 10, relayOn ? 0xB240 : BORDER);
  tft.fillRoundRect(relayOn ? 200 : 183, relaySwitchY + 3, 14, 14, 7, WHITE);
}

void drawMotor()
{
  const __FlashStringHelper *labels[] = {F("CCW"), F("OFF"), F("CW")};
  const uint16_t colors[] = {0x02BE, 0xFBCD, 0x0434};
  tft.fillRoundRect(10, 237, 220, 31, 9, 0xA7F3);
  tft.drawRoundRect(10, 237, 220, 31, 9, BORDER);
  tft.setTextColor(INK);
  tft.setTextSize(2);
  tft.setCursor(20, 245); tft.print(F("MOTOR"));
  tft.setTextSize(1);
  for (uint8_t i = 0; i < 3; ++i)
  {
    const int x = 91 + 44 * i;
    tft.fillRoundRect(x, MOTOR_BUTTON_Y, 39, MOTOR_BUTTON_HEIGHT, 5, i == motorState ? colors[i] : CARD);
    tft.drawRoundRect(x, MOTOR_BUTTON_Y, 39, MOTOR_BUTTON_HEIGHT, 5, BORDER);
    tft.setTextColor(i == motorState && i != 1 ? WHITE : INK);
    tft.setCursor(x + (i == 2 ? 13 : 10), 249);
    tft.print(labels[i]);
  }
}

void drawServo()
{
  tft.fillRoundRect(10, 274, 220, 35, 9, 0xF59F);
  tft.drawRoundRect(10, 274, 220, 35, 9, BORDER);
  tft.setTextColor(INK);
  tft.setTextSize(2);
  tft.setCursor(20, 284); tft.print(F("SERVO"));
  for (uint8_t i = 0; i < 3; i += 2)
  {
    const int x = 91 + 44 * i;
    const bool left = i == 0;
    tft.fillRoundRect(x, 281, 39, 22, 5, left ? 0x781F : 0x02BE);
    const int tip = x + (left ? 10 : 28);
    tft.fillTriangle(tip, 292, x + 19, 286, x + 19, 298, WHITE);
    tft.fillRect(x + (left ? 19 : 11), 290, 9, 5, WHITE);
  }
  constexpr int angleBoxX = 135;
  constexpr int angleBoxWidth = 39;
  tft.fillRoundRect(angleBoxX, 281, angleBoxWidth, 22, 5, CARD);
  tft.drawRoundRect(angleBoxX, 281, angleBoxWidth, 22, 5, BORDER);
  tft.setTextSize(1);
  const int digits = servoAngle >= 100 ? 3 : (servoAngle >= 10 ? 2 : 1);
  const int digitWidth = digits * 6;
  const int textX = angleBoxX + (angleBoxWidth - digitWidth - 5) / 2;
  tft.setCursor(textX, 288);
  tft.print(servoAngle);
  tft.drawCircle(textX + digitWidth + 2, 289, 1, INK);
}

void drawPanel()
{
  tft.fillScreen(BACKGROUND);
  tft.setTextSize(2);
  tft.setTextColor(WHITE);
  tft.fillRoundRect(10, 8, 220, 35, 8, HEADER);
  tft.setCursor(42, 12); tft.print(F("CONTROL PANEL"));
  tft.setTextSize(1);
  tft.setTextColor(GOLD);
  tft.setCursor(57, 31); tft.print(F("Tap here to calibrate"));
  drawLedGroups();
  for (uint8_t i = 0; i < ledCount; ++i) drawToggle(i);
  drawRelay();
  drawMotor();
  drawServo();
}

void setup()
{
  Serial.begin(9600);
  for (uint8_t pin : ledPins) drive(pin, LOW);
  drive(relayPin, HIGH);  // The relay coil is wired to +5 V.
  drive(motorPlusPin, LOW);
  drive(motorMinusPin, LOW);
  servoMotor.attach(servoPin);
  servoMotor.write(0);
  tft.begin(4000000);
  tft.setRotation(0);
  if (!loadCalibration()) calibrate();
  drawPanel();
}

void stepServo(int8_t direction)
{
  const int nextAngle = servoAngle + direction * 10;
  if (nextAngle < 0 || nextAngle > 180) return;
  servoAngle = nextAngle;
  servoMotor.write(servoAngle);
  drawServo();
}

void loop()
{
  int16_t xRaw, yRaw;
  delay(10);
  const bool firstTouch = newTouch(xRaw, yRaw);
  if (!pressed) heldServoDirection = 0;
  if (!touchDetected || (!firstTouch && heldServoDirection == 0)) return;
  const long dx = xRaw - rawX[0];
  const long dy = yRaw - rawY[0];
  const long horizontal = dx * (rawY[2] - rawY[0]) - dy * (rawX[2] - rawX[0]);
  const long vertical = dy * (rawX[1] - rawX[0]) - dx * (rawY[1] - rawY[0]);
  const long x = targetX[0] + horizontal * (targetX[1] - targetX[0]) / determinant;
  const long y = targetY[0] + vertical * (targetY[2] - targetY[0]) / determinant;
  int8_t servoDirection = 0;
  if (y >= 281 && y < 303)
  {
    if (x >= 91 && x < 130) servoDirection = -1;
    if (x >= 179 && x < 218) servoDirection = 1;
  }
  if (!firstTouch)
  {
    if (servoDirection != heldServoDirection)
    {
      heldServoDirection = 0;
      return;
    }
    if (millis() - lastServoStep >= servoRepeatDelay)
    {
      stepServo(heldServoDirection);
      lastServoStep = millis();
      servoRepeatDelay = SERVO_REPEAT_INTERVAL;
    }
    return;
  }
  if (servoDirection != 0)
  {
    heldServoDirection = servoDirection;
    stepServo(servoDirection);
    lastServoStep = millis();
    servoRepeatDelay = SERVO_HOLD_DELAY;
    return;
  }
  // The full title bar opens calibration. newTouch waits for release before accepting the first calibration point.
  if (x >= 10 && x < 230 && y >= 8 && y < 43)
  {
    calibrate();
    drawPanel();
    return;
  }
  for (uint8_t i = 0; i < ledCount; ++i)
  {
    const int left = ledGroupX(i);
    const int top = ledRowY(i);
    if (x >= left + 56 && x < left + 94 && y >= top + 3 && y < top + 23)
    {
      ledOn[i] = !ledOn[i];
      digitalWrite(ledPins[i], ledOn[i] ? HIGH : LOW);
      drawToggle(i);
      return;
    }
  }
  if (x >= 180 && x < 218 && y >= relaySwitchY && y < relaySwitchY + 20)
  {
    relayOn = !relayOn;
    digitalWrite(relayPin, relayOn ? LOW : HIGH);
    drawRelay();
    return;
  }
  for (uint8_t i = 0; i < 3; ++i)
  {
    const int left = 91 + 44 * i;
    if (x >= left && x < left + 39 && y >= MOTOR_BUTTON_Y && y < MOTOR_BUTTON_Y + MOTOR_BUTTON_HEIGHT)
    {
      if (motorState == i) return;
      digitalWrite(motorPlusPin, LOW);
      digitalWrite(motorMinusPin, LOW);
      motorState = i;
      if (i == 0) digitalWrite(motorMinusPin, HIGH);
      if (i == 2) digitalWrite(motorPlusPin, HIGH);
      drawMotor();
      return;
    }
  }
}

FILES PROVIDED:

The attached ZIP file includes: the schematic, the "ino" file, the "exe" file, and all subcircuits used in this project, all located in the "data" directory. Simulide version 1.2 or higher is required.

Uploaded files: