ESP32 - Display TFT LCD Touch ILI9341 ILI9488 ST7789 com Interface SPI

Vamos construir um projeto que dá vida a um display TFT SPI colorido em um ESP32. O ESP32 é um microcontrolador dual-core poderoso, com Wi-Fi, Bluetooth e muitos GPIOs - e o seu barramento SPI de hardware VSPI facilita rodar um display TFT de alta velocidade nas taxas que o painel suporta.

O que vamos construir:

Este projeto aborda displays TFT LCD SPI com e sem touch. Ele funciona com painéis de 1.3, 1.54, 2.2, 2.4, 2.8, 3.2 e 3.5 polegadas controlados pelos chips ILI9341, ILI9488 ou ST7789.

Display TFT SPI com ESP32

O Que É o Display TFT SPI?

Um módulo TFT SPI combina um LCD colorido com um CI controlador que aceita comandos de desenho por um barramento SPI de 4 fios. A biblioteca suporta três chips comuns:

  • ILI9341 - cores RGB565 de 16 bits, SPI de até 40 MHz.
  • ILI9488 - cores RGB666 de 18 bits via SPI, até 24 MHz.
  • ST7789 - cores RGB565 de 16 bits, SPI de até 40 MHz.

Recomendação: Se você ainda não comprou um display, recomendamos o controlador ST7789. Ele é fácil de encontrar, funciona com a velocidade SPI total de 40 MHz e é a escolha mais simples para novos projetos.

O desenho é feito pela API Adafruit GFX, que inclui formas, texto, fontes personalizadas e saída de bitmaps.

Observação: O ESP32 usa lógica de 3.3V. A maioria dos módulos TFT SPI funciona com 3.3V. Verifique a especificação de tensão do seu módulo antes de fazer a ligação.

Pinagem

A maioria dos displays TFT LCD SPI tem os seguintes pinos:

Pinos do display:

Pino Função
VCC Alimentação
GND Terra
CS Chip Select — colocado em nível baixo para selecionar o display no barramento SPI
DC / RS Seleção de Dado / Comando — nível alto para dados de pixel, nível baixo para comandos
RST Reset por hardware — opcional; ligue ao 3.3V se não for usado
MOSI / SDI / SDA Entrada de dados SPI (MCU → display)
SCK / CLK Clock SPI
MISO / SDO Saída de dados SPI (display → MCU) — opcional para uso apenas como display
LED / BL / BLK Alimentação da luz de fundo — conecte ao 3.3V ou a um pino PWM para controlar o brilho

Pinos do cartão SD (se a sua aplicação precisar acessar o cartão SD):

Pino Função
SD_CS / TF_CS Chip Select do cartão SD
MOSI / SDI MOSI — dados do MCU para o cartão SD
SCK / CLK SCK — clock SPI
MISO / SDO MISO — dados do cartão SD para o MCU

Nos displays TFT que suportam touch, há pinos de toque adicionais (se a sua aplicação usar a função de toque e o display a suportar):

Pino Função
T_CS Chip Select do controlador de toque
T_CLK SCK — clock SPI
T_DIN MOSI — dados do MCU para o controlador de toque
T_DO MISO — dados do controlador de toque para o MCU
T_IRQ Interrupção de toque — opcional; sinaliza quando a tela está sendo tocada

Observação: Alguns módulos de display sem touch também têm os pinos T_CS, T_CLK, T_DIN, T_DO e T_IRQ. Eles não funcionam nessas placas — o CI controlador de toque não está montado. Eles aparecem porque a PCB reutiliza o mesmo layout da versão com touch para reduzir as variações de fabricação.

Pinagem do display TFT SPI

Diagrama de Ligação

Observação — o SDO (MISO) é opcional: A linha SDO (MISO) só transporta dados do display de volta para a placa. Nenhum dos códigos de exemplo deste tutorial lê dados do display, então este pino pode ficar desconectado. Em módulos em que o controlador de toque compartilha o mesmo barramento SPI, uma linha SDO conectada pode interferir na comunicação, por isso é recomendável deixá-la desconectada.

Sem Touch

Conecte o MOSI ao GPIO23, o SCK ao GPIO18 e o MISO ao GPIO19 do ESP32. CS, DC e RST podem usar qualquer GPIO disponível — GPIO5, GPIO2 e GPIO4 são usados nos exemplos.

Display:

Pino do TFT Pino do ESP32 Descrição
VCC 3.3V Alimentação (somente 3.3V)
GND GND Terra
CS GPIO5 Chip Select
DC / RS GPIO2 Seleção de Dado / Comando
RST GPIO4 Reset (opcional)
MOSI / SDI GPIO23 MOSI do SPI de hardware (VSPI)
SCK GPIO18 Clock do SPI de hardware (VSPI)
MISO / SDO GPIO19 MISO do SPI de hardware (VSPI, opcional)
LED / BL 3.3V Alimentação da luz de fundo

Cartão SD (se a sua aplicação precisar acessar o cartão SD):

Pino do SD Pino do ESP32 Descrição
SD_CS / TF_CS qualquer GPIO livre Chip Select do cartão SD
MOSI / SDI GPIO23 Compartilhado com o MOSI do display (GPIO23)
SCK / CLK GPIO18 Compartilhado com o SCK do display (GPIO18)
MISO / SDO GPIO19 Compartilhado com o MISO do display (GPIO19)
Diagrama de ligação do ESP32 com display TFT SPI sem touch

This image is created using Fritzing. Click to enlarge image

Se você não sabe como alimentar o ESP32 e outros componentes, veja as instruções no tutorial a seguir: Como alimentar o ESP32.

Observação: O diagrama acima mostra a ligação correta. Na prática, não é fácil conectar dois fios no mesmo furo do header de pinos do ESP32. Uma solução prática é usar uma placa breakout com bornes de parafuso para ESP32 — dois fios podem ser presos no mesmo borne de parafuso, ou um fio no borne e outro no pino do header ao lado.

Diagrama de ligação do ESP32 com display TFT SPI sem touch usando bornes de parafuso

This image is created using Fritzing. Click to enlarge image

Com Touch

Conecte o controlador de toque XPT2046 ao barramento VSPI do ESP32, compartilhando o GPIO23, o GPIO18 e o GPIO19 com o display.

Display:

Pino do TFT Pino do ESP32 Descrição
VCC 3.3V Alimentação (somente 3.3V)
GND GND Terra
CS GPIO5 Chip Select
DC / RS GPIO2 Seleção de Dado / Comando
RST GPIO4 Reset (opcional)
MOSI / SDI GPIO23 MOSI do SPI de hardware (VSPI)
SCK GPIO18 Clock do SPI de hardware (VSPI)
MISO / SDO GPIO19 MISO do SPI de hardware (VSPI, opcional)
LED / BL 3.3V Alimentação da luz de fundo

Controlador de toque (se a sua aplicação usar a função de toque e o display a suportar):

Pino de Toque Pino do ESP32 Descrição
T_CS qualquer GPIO livre Chip Select do toque
T_IRQ qualquer GPIO livre Interrupção de toque (opcional)
T_DIN GPIO23 Compartilhado com o MOSI do display (GPIO23)
T_CLK GPIO18 Compartilhado com o SCK do display (GPIO18)
T_DO GPIO19 Compartilhado com o MISO do display (GPIO19)
Diagrama de ligação do ESP32 com display TFT SPI com touch

This image is created using Fritzing. Click to enlarge image

Observação: O diagrama acima mostra a ligação correta. Na prática, não é fácil conectar dois fios no mesmo furo do header de pinos do ESP32. Uma solução prática é usar uma placa breakout com bornes de parafuso para ESP32 — dois fios podem ser presos no mesmo borne de parafuso, ou um fio no borne e outro no pino do header ao lado.

Diagrama de ligação do ESP32 com display TFT SPI com touch usando bornes de parafuso

This image is created using Fritzing. Click to enlarge image

Se o seu MCU tem duas ou mais interfaces SPI de hardware, você pode atribuir cada periférico (display, cartão SD, controlador de toque) a um barramento SPI dedicado. Se o seu MCU tem apenas uma interface SPI de hardware, os três periféricos compartilham as mesmas três linhas de dados (MOSI, SCK, MISO) — no ESP32, elas são o GPIO23, o GPIO18 e o GPIO19. Cada periférico tem o seu próprio pino CS, então apenas um fica ativo por vez. A biblioteca DIYables_TFT_SPI gerencia tanto o display quanto o controlador de toque XPT2046 por meio de uma única API — não é necessária uma biblioteca SPI separada para a parte de toque.

Instalação da Biblioteca

  1. Conecte a placa ESP32 ao seu computador pela porta USB-C.
  2. Abra a Arduino IDE. Selecione a variante da sua placa ESP32 no menu de placas e escolha a porta COM correta.
  3. Abra o painel Libraries.
  4. Pesquise "DIYables_TFT_SPI". Localize a entrada da DIYables.
  5. Clique em Install e aceite a instalação de todas as dependências.
  • Search for DIYables TFT SPI created by DIYables.io and click the Install button.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Library Manager
Type:
All
Topic:
All
DIYables TFT SPI by DIYables.io
Works with both touch and non-touch versions of the same SPI TFT modules. Supports ILI9341 (240x320, 16-bit RGB565), ILI9488 (320x480, 18-bit RGB666), and ST7789 (240x320, 16-bit RGB565) displays over SPI. Includes built-in driver for XPT2046 / HR2046 / ADS7843 SPI touch controllers and 4-wire resistive touch panels - no separate touch library required. Use the display-only API for non-touch panels, or add initTouchSPI() to enable touch on modules that include a touch controller. Extends Adafruit GFX for full graphics support. Works with any Arduino-compatible board that has SPI. More info
1.0.3
INSTALL
Newbiely.ino
···
1 void setup() {
Output
Serial Monitor
Ln 1, Col 1
ESP32 Dev Module on COM15
1

Base do Projeto

O sketch base para todo projeto TFT com ESP32 usando esta biblioteca:

#include <DIYables_TFT_SPI.h> #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Uncomment the line that matches your driver chip: // DIYables_ILI9341_SPI TFT_display(240, 320, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(320, 480, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(240, 320, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); void setup() { TFT_display.begin(); TFT_display.setRotation(1); } void loop() { // drawing code here }

Mãos à Obra - Desenhar Formas

O exemplo DrawShapes desenha toda a variedade de formas básicas da Adafruit GFX: círculos, triângulos, retângulos, retângulos arredondados e linhas.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Created by DIYables This example code is in the public domain Product page: https://diyables.io */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> // ============================================= // Wiring (ESP32) // ============================================= // TFT pins (always required) // TFT module ESP32 // ------------ --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // CS -> GPIO5 (TFT_CS_PIN) // RESET -> GPIO4 (TFT_RST_PIN) // DC / RS -> GPIO2 (TFT_DC_PIN) // SDI / MOSI -> GPIO23 (hardware SPI MOSI / VSPI) // SCK -> GPIO18 (hardware SPI SCK / VSPI) // SDO / MISO -> GPIO19 (only needed when reading from display / VSPI) // LED -> 3.3V (or any GPIO via initBacklight) // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 // MOSI and SCK use default hardware SPI pins // ============================================= // Create display object (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); #define BLACK DIYables_TFT_SPI::colorRGB(0, 0, 0) #define BLUE DIYables_TFT_SPI::colorRGB(0, 0, 255) #define RED DIYables_TFT_SPI::colorRGB(255, 0, 0) #define GREEN DIYables_TFT_SPI::colorRGB(0, 255, 0) #define ORANGE DIYables_TFT_SPI::colorRGB(255, 165, 0) #define PINK DIYables_TFT_SPI::colorRGB(255, 192, 203) #define VIOLET DIYables_TFT_SPI::colorRGB(148, 0, 211) #define TURQUOISE DIYables_TFT_SPI::colorRGB(64, 224, 208) #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) // Helper to draw a filled diamond void fillDiamond(int cx, int cy, int h, int v, uint16_t color) { int x0 = cx, y0 = cy - v; int x1 = cx + h, y1 = cy; int x2 = cx, y2 = cy + v; int x3 = cx - h, y3 = cy; TFT_display.fillTriangle(x0, y0, x1, y1, x2, y2, color); TFT_display.fillTriangle(x0, y0, x2, y2, x3, y3, color); } void setup() { TFT_display.begin(); TFT_display.setRotation(1); // Landscape } void loop() { TFT_display.fillScreen(WHITE); uint16_t w = TFT_display.width(); uint16_t h = TFT_display.height(); // Scale positions relative to screen size with better spacing int col1 = w / 8; int col2 = w * 3 / 8; int col3 = w * 5 / 8; int col4 = w * 7 / 8; int row1 = h / 4; int row2 = h / 2; int row3 = h * 3 / 4; // Outlined circle TFT_display.drawCircle(col1, row1, 30, RED); // Filled circle TFT_display.fillCircle(col2, row1, 30, RED); // Outlined triangle TFT_display.drawTriangle(col3 - 30, row1 + 25, col3 + 30, row1 + 25, col3, row1 - 25, BLUE); // Filled triangle TFT_display.fillTriangle(col4 - 30, row1 + 25, col4 + 30, row1 + 25, col4, row1 - 25, GREEN); // Outlined rectangle TFT_display.drawRect(col1 - 35, row2 - 20, 70, 40, ORANGE); // Filled rectangle TFT_display.fillRect(col2 - 35, row2 - 20, 70, 40, TURQUOISE); // Outlined round rectangle TFT_display.drawRoundRect(col3 - 35, row2 - 20, 70, 40, 10, VIOLET); // Filled round rectangle TFT_display.fillRoundRect(col4 - 35, row2 - 20, 70, 40, 10, PINK); // Outlined diamond (centered between col1 and col2) int diamond1_x = (col1 + col2) / 2; TFT_display.drawLine(diamond1_x, row3 - 30, diamond1_x + 25, row3, GREEN); TFT_display.drawLine(diamond1_x + 25, row3, diamond1_x, row3 + 30, GREEN); TFT_display.drawLine(diamond1_x, row3 + 30, diamond1_x - 25, row3, GREEN); TFT_display.drawLine(diamond1_x - 25, row3, diamond1_x, row3 - 30, GREEN); // Filled diamond (centered between col3 and col4) int diamond2_x = (col3 + col4) / 2; fillDiamond(diamond2_x, row3, 25, 30, BLUE); delay(10000); }

Carregar e Testar

  • Ligue o módulo TFT ao ESP32 usando a tabela acima.
  • Conecte o cabo USB-C.
  • Na Arduino IDE, selecione a placa e a porta, cole o código e clique em Upload.
  • Depois do upload, o display é preenchido com uma sequência repetida de formas coloridas.

Referência da API de Desenho

Método Finalidade Uso
begin() Inicializa o display. TFT_display.begin();
setRotation(r) Define a orientação da tela de 0 a 3. TFT_display.setRotation(1);
fillScreen(color) Preenche a tela inteira com uma cor. TFT_display.fillScreen(BLACK);
colorRGB(r,g,b) Cria um valor de cor de 16 bits. colorRGB(255,128,0)
fillCircle(x,y,r,color) Círculo preenchido. TFT_display.fillCircle(120,160,60,RED);
fillRect(x,y,w,h,color) Retângulo preenchido. TFT_display.fillRect(0,0,100,50,BLUE);
drawLine(x0,y0,x1,y1,color) Linha reta entre dois pontos. TFT_display.drawLine(0,0,320,240,WHITE);

Mãos à Obra - Mostrar Texto e Número

O exemplo ShowTextAndNumber usa o mecanismo de texto da Adafruit GFX para imprimir strings e valores numéricos com tamanhos e cores ajustáveis.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Created by DIYables This example code is in the public domain Product page: https://diyables.io */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> // ============================================= // Wiring (ESP32) // ============================================= // TFT pins (always required) // TFT module ESP32 // ------------ --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // CS -> GPIO5 (TFT_CS_PIN) // RESET -> GPIO4 (TFT_RST_PIN) // DC / RS -> GPIO2 (TFT_DC_PIN) // SDI / MOSI -> GPIO23 (hardware SPI MOSI / VSPI) // SCK -> GPIO18 (hardware SPI SCK / VSPI) // SDO / MISO -> GPIO19 (only needed when reading from display / VSPI) // LED -> 3.3V (or any GPIO via initBacklight) // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 // ============================================= // Create display object (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); #define MAGENTA DIYables_TFT_SPI::colorRGB(255, 0, 255) #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) void setup() { Serial.begin(9600); Serial.println(F("TFT SPI Display - Show text and numbers")); TFT_display.begin(); TFT_display.setRotation(1); // Landscape TFT_display.fillScreen(WHITE); // Set text color and size TFT_display.setTextColor(MAGENTA); TFT_display.setTextSize(3); // Sample values float temperature = 23.5; float humidity = 78.6; // Display temperature TFT_display.setCursor(20, 20); TFT_display.print("Temperature: "); TFT_display.print(temperature, 1); TFT_display.print(char(247)); TFT_display.println("C"); // Display humidity TFT_display.setCursor(20, 60); TFT_display.print("Humidity: "); TFT_display.print(humidity, 1); TFT_display.print("%"); } void loop() { }

Carregar e Testar

  • Faça a ligação e o upload como acima.
  • O display mostra várias linhas de texto e números em cores e tamanhos diferentes.

Referência da API de Desenho

Método Finalidade Uso
setTextColor(color) Define a cor do texto. TFT_display.setTextColor(WHITE);
setTextSize(size) Aumenta o texto. Tamanho 1 = 6×8 px, tamanho 2 = 12×16 px. TFT_display.setTextSize(2);
setCursor(x, y) Coloca o cursor de texto no pixel (x, y). TFT_display.setCursor(10, 20);
print(value) Imprime uma string ou um número na posição do cursor. TFT_display.print("ESP32!");
println(value) Imprime e avança o cursor para a próxima linha. TFT_display.println(42);

Mãos à Obra - Desenhar Imagem

Vamos construir um visualizador de imagens. O exemplo DrawImage carrega um bitmap RGB565 colorido da memória flash de programa do ESP32 e o mostra no display. Os dados dos pixels são declarados no bitmap.h como um array const uint16_t com PROGMEM. No ESP32, os dados em PROGMEM são mapeados da flash para o espaço de endereçamento virtual, então a imagem é desenhada sem consumir nenhuma RAM do heap.

Copie o bitmap.h para a pasta do sketch antes de compilar.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Created by DIYables This example code is in the public domain Product page: https://diyables.io */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> #include "bitmap.h" // ============================================= // Wiring (ESP32) // ============================================= // TFT pins (always required) // TFT module ESP32 // ------------ --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // CS -> GPIO5 (TFT_CS_PIN) // RESET -> GPIO4 (TFT_RST_PIN) // DC / RS -> GPIO2 (TFT_DC_PIN) // SDI / MOSI -> GPIO23 (hardware SPI MOSI / VSPI) // SCK -> GPIO18 (hardware SPI SCK / VSPI) // SDO / MISO -> GPIO19 (only needed when reading from display / VSPI) // LED -> 3.3V (or any GPIO via initBacklight) // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 // ============================================= // Create display object (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) int img_width = 120; int img_height = 53; void setup() { Serial.begin(9600); Serial.println(F("TFT SPI Display - Draw Image")); TFT_display.begin(); uint16_t SCREEN_WIDTH = TFT_display.width(); uint16_t SCREEN_HEIGHT = TFT_display.height(); int x = (SCREEN_WIDTH - img_width) / 2; int y = (SCREEN_HEIGHT - img_height) / 2; TFT_display.fillScreen(WHITE); TFT_display.drawRGBBitmap(x, y, myBitmap, img_width, img_height); } void loop() { delay(2000); TFT_display.invertDisplay(true); delay(2000); TFT_display.invertDisplay(false); }

Carregar e Testar

  • Coloque o bitmap.h na mesma pasta do sketch.
  • Ligue o módulo TFT ao ESP32 como mostrado acima (MOSI=GPIO23, SCK=GPIO18, MISO=GPIO19, CS=GPIO5, DC=GPIO2, RST=GPIO4). Use 3.3V no VCC.
  • Conecte o cabo USB-C.
  • Na Arduino IDE, selecione a placa e a porta e clique em Upload.
  • O display mostra a imagem bitmap da memória flash.

Referência da API de Desenho

Método Finalidade Uso
drawRGBBitmap(x,y,bitmap,w,h) Desenha um bitmap RGB565 em PROGMEM com o canto superior esquerdo em (x, y). TFT_display.drawRGBBitmap(0, 0, myImage, 240, 320);
fillScreen(color) Limpa o display antes de desenhar a imagem. TFT_display.fillScreen(BLACK);

Mãos à Obra - Desenhar Imagem do Cartão SD

Vamos construir um visualizador de imagens do cartão SD. O exemplo DrawImageSDcard lê uma imagem binária RGB565 bruta de um cartão micro SD e envia os dados dos pixels para o display em blocos. O ESP32 controla tanto o cartão SD quanto o display no mesmo barramento VSPI, alternando as linhas CS para decidir com qual deles se comunicar.

Ligue o módulo SD ao GPIO23 (MOSI), GPIO18 (SCK) e GPIO19 (MISO). Defina um pino CS separado para o módulo SD como SD_CS_PIN no sketch.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Created by DIYables This example code is in the public domain Product page: https://diyables.io */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> #include <SD.h> // ============================================= // Wiring (ESP32) // ============================================= // TFT + SD module pins // TFT + SD module ESP32 // ----------------------- --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // TFT CS -> GPIO5 (TFT_CS_PIN) // TFT RESET -> GPIO4 (TFT_RST_PIN) // TFT DC / RS -> GPIO2 (TFT_DC_PIN) // SD CS -> GPIO14 (SD_CS) // SDI / MOSI (shared) -> GPIO23 (hardware SPI MOSI / VSPI) // SDO / MISO (shared) -> GPIO19 (hardware SPI MISO / VSPI) // SCK (shared) -> GPIO18 (hardware SPI SCK / VSPI) // LED -> 3.3V (or any GPIO via initBacklight) // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 #define SD_CS 14 // SD card chip select (must differ from TFT_CS_PIN) // ============================================= // Create display object (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) #define BUFFPIXEL 20 File bmpFile; uint16_t SCREEN_WIDTH; uint16_t SCREEN_HEIGHT; // Helper functions to read BMP file header uint16_t read16(File &f) { uint16_t result; result = f.read(); result |= (f.read() << 8); return result; } uint32_t read32(File &f) { uint32_t result; result = f.read(); result |= ((uint32_t)f.read() << 8); result |= ((uint32_t)f.read() << 16); result |= ((uint32_t)f.read() << 24); return result; } int32_t readS32(File &f) { int32_t result; result = f.read(); result |= ((uint32_t)f.read() << 8); result |= ((uint32_t)f.read() << 16); result |= ((uint32_t)f.read() << 24); return result; } bool getBMPDimensions(const char *filename, uint32_t &w, uint32_t &h) { File f = SD.open(filename); if (!f) return false; if (read16(f) != 0x4D42) { f.close(); return false; } read32(f); // file size read32(f); // reserved read32(f); // image offset read32(f); // DIB header size w = read32(f); int32_t sh = readS32(f); h = (sh < 0) ? -sh : sh; f.close(); return true; } void drawBMP(const char *filename, int x, int y) { bmpFile = SD.open(filename); if (!bmpFile) { Serial.println("File not found"); return; } if (read16(bmpFile) != 0x4D42) { Serial.println("Not a BMP file"); bmpFile.close(); return; } uint32_t fileSize = read32(bmpFile); read32(bmpFile); // Reserved uint32_t imageOffset = read32(bmpFile); uint32_t dibHeaderSize = read32(bmpFile); uint32_t bmpWidth = read32(bmpFile); int32_t bmpHeight = readS32(bmpFile); bool topDown = false; if (bmpHeight < 0) { bmpHeight = -bmpHeight; topDown = true; } if (read16(bmpFile) != 1) { Serial.println("Invalid BMP file"); bmpFile.close(); return; } uint16_t depth = read16(bmpFile); if (depth != 24) { Serial.println("Only 24-bit BMP is supported"); bmpFile.close(); return; } if (read32(bmpFile) != 0) { Serial.println("Unsupported BMP compression"); bmpFile.close(); return; } bmpFile.seek(imageOffset); uint8_t sdbuffer[3 * BUFFPIXEL]; uint16_t color; uint32_t rowSize = (bmpWidth * 3 + 3) & ~3; if (x >= SCREEN_WIDTH || y >= SCREEN_HEIGHT) return; uint32_t maxRow = min((uint32_t)bmpHeight, (uint32_t)(SCREEN_HEIGHT - y)); uint32_t maxCol = min(bmpWidth, (uint32_t)(SCREEN_WIDTH - x)); for (uint32_t row = 0; row < maxRow; row++) { int32_t rowPos = topDown ? row : bmpHeight - 1 - row; uint32_t filePosition = imageOffset + rowPos * rowSize; bmpFile.seek(filePosition); for (uint32_t col = 0; col < maxCol; col += BUFFPIXEL) { uint32_t pixelsToRead = min((uint32_t)BUFFPIXEL, maxCol - col); bmpFile.read(sdbuffer, 3 * pixelsToRead); for (uint32_t i = 0; i < pixelsToRead; i++) { uint8_t b = sdbuffer[i * 3]; uint8_t g = sdbuffer[i * 3 + 1]; uint8_t r = sdbuffer[i * 3 + 2]; color = DIYables_TFT_SPI::colorRGB(r, g, b); if ((x + col + i) < SCREEN_WIDTH && (y + row) < SCREEN_HEIGHT) { TFT_display.drawPixel(x + col + i, y + row, color); } } } } bmpFile.close(); Serial.println("BMP drawn"); } void setup() { Serial.begin(9600); if (!SD.begin(SD_CS)) { Serial.println("SD card initialization failed!"); return; } Serial.println("SD card initialized."); TFT_display.begin(); TFT_display.setRotation(1); // Landscape SCREEN_WIDTH = TFT_display.width(); SCREEN_HEIGHT = TFT_display.height(); TFT_display.fillScreen(WHITE); uint32_t imgWidth, imgHeight; if (getBMPDimensions("diyables.bmp", imgWidth, imgHeight)) { int x = (SCREEN_WIDTH - imgWidth) / 2; int y = (SCREEN_HEIGHT - imgHeight) / 2; drawBMP("diyables.bmp", x, y); } else { Serial.println("Failed to get BMP dimensions"); } } void loop() { }

Carregar e Testar

  • Ligue o módulo SD ao barramento VSPI do ESP32. Compartilhe os GPIO23/18/19 com o display. Conecte o CS do SD ao pino definido como SD_CS_PIN.
  • Copie um arquivo de imagem binária RGB565 bruta para a raiz do cartão SD. As dimensões devem corresponder ao seu painel.
  • Conecte o cabo USB-C.
  • Na Arduino IDE, selecione a placa e a porta e clique em Upload.
  • O display mostra a imagem enviada do cartão SD.

Referência da API de Desenho

Método Finalidade Uso
startWrite() Abre uma sessão de escrita SPI direta e ativa o CS do display. TFT_display.startWrite();
setAddrWindow(x0,y0,x1,y1) Define a região retangular de escrita de pixels no painel. TFT_display.setAddrWindow(0, 0, 239, 319);
pushColors(buf, len) Envia um buffer de valores de pixel RGB565 para o display. TFT_display.pushColors(buf, 512);
endWrite() Fecha a sessão SPI e libera o CS do display. TFT_display.endWrite();

Mãos à Obra - Usar Fonte Externa

Vamos construir uma exibição de texto personalizada. O exemplo UseExternalFont substitui a fonte padrão de 5×7 pixels por uma fonte vetorial mais nítida, compatível com a Adafruit GFX. Basta uma chamada a setFont() para melhorar a tipografia. Chamar setFont(NULL) restaura a fonte embutida original a qualquer momento.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Created by DIYables This example code is in the public domain Product page: https://diyables.io */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> #include <Fonts/FreeSansBold12pt7b.h> // ============================================= // Wiring (ESP32) // ============================================= // TFT pins (always required) // TFT module ESP32 // ------------ --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // CS -> GPIO5 (TFT_CS_PIN) // RESET -> GPIO4 (TFT_RST_PIN) // DC / RS -> GPIO2 (TFT_DC_PIN) // SDI / MOSI -> GPIO23 (hardware SPI MOSI / VSPI) // SCK -> GPIO18 (hardware SPI SCK / VSPI) // SDO / MISO -> GPIO19 (only needed when reading from display / VSPI) // LED -> 3.3V (or any GPIO via initBacklight) // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 // ============================================= // Create display object (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); #define MAGENTA DIYables_TFT_SPI::colorRGB(255, 0, 255) #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) void setup() { Serial.begin(9600); Serial.println(F("TFT SPI Display - Use external font")); TFT_display.begin(); TFT_display.setFont(&FreeSansBold12pt7b); TFT_display.setRotation(1); // Landscape TFT_display.fillScreen(WHITE); TFT_display.setTextColor(MAGENTA); TFT_display.setTextSize(1); float temperature = 23.5; float humidity = 78.6; TFT_display.setCursor(20, 30); TFT_display.print("Temperature: "); TFT_display.print(temperature, 1); TFT_display.print(char(247)); TFT_display.println("C"); TFT_display.setCursor(20, 70); TFT_display.print("Humidity: "); TFT_display.print(humidity, 1); TFT_display.print("%"); } void loop() { }

Carregar e Testar

  • Ligue o módulo TFT ao ESP32 como mostrado acima.
  • Conecte o cabo USB-C.
  • Na Arduino IDE, selecione a placa e a porta e clique em Upload.
  • O display mostra o texto com a fonte personalizada.

Referência da API de Desenho

Método Finalidade Uso
setFont(&FontName) Ativa uma fonte personalizada compatível com GFX. Passe NULL para restaurar a fonte embutida de 5×7. TFT_display.setFont(&FreeSans12pt7b);
setCursor(x, y) Posiciona o cursor de texto na coordenada de pixel indicada. TFT_display.setCursor(10, 40);
setTextColor(color) Define a cor do texto seguinte. TFT_display.setTextColor(WHITE);
print(text) Imprime uma string na posição do cursor usando a fonte ativa. TFT_display.print("ESP32 Project");

Mãos à Obra - Obter Ponto de Toque

Vamos construir um leitor de coordenadas de toque. O exemplo TouchGetPoint inicializa o XPT2046 no barramento VSPI do ESP32 e imprime os valores brutos do ADC no Serial Monitor sempre que a tela é pressionada. Este é o primeiro passo para um projeto com touch: entender a faixa de valores brutos que o seu painel produz.

Ligação (todos os sinais em 3.3V):

Pino de Toque Pino do ESP32 Descrição
T_CLK GPIO18 SCK — compartilhado com o display
T_DIN GPIO23 MOSI — compartilhado com o display
T_DO GPIO19 MISO — compartilhado com o display
T_CS GPIO15 Chip Select do toque
T_IRQ GPIO27 Interrupção de toque (opcional)
/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Touch Get Point Example ----------------------- This example demonstrates how to read and display touch coordinates using a DIYables SPI TFT display with a 4-wire resistive touch panel. When you touch the screen, the sketch prints the mapped (screen) X and Y coordinates to the Serial Monitor and draws a red dot at the touched location. NOTE: Run the TouchCalibration example first and paste the calibration values into setTouchCalibration() below if the touch coordinates are inaccurate. Created by DIYables This example code is in the public domain Product page: https://diyables.io */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> // ============================================= // Wiring (ESP32) // ============================================= // TFT pins (always required) // TFT module ESP32 // ------------ --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // CS -> GPIO5 (TFT_CS_PIN) // RESET -> GPIO4 (TFT_RST_PIN) // DC / RS -> GPIO2 (TFT_DC_PIN) // SDI / MOSI -> GPIO23 (hardware SPI MOSI / VSPI) // SCK -> GPIO18 (hardware SPI SCK / VSPI) // SDO / MISO -> GPIO19 (only needed when reading from display / VSPI) // LED -> 3.3V (or any GPIO via initBacklight) // // XPT2046 / HR2046 / ADS7843 SPI touch controller // (modules with pins: T_CS, T_CLK, T_DIN, T_DO, T_IRQ) // Touch pin ESP32 // ------------ --------------------------------- // T_CS -> GPIO15 (TOUCH_CS_PIN) // T_IRQ -> GPIO27 (TOUCH_IRQ_PIN, optional - use -1 to skip) // T_CLK -> GPIO18 (shared with display SCK / VSPI) // T_DIN -> GPIO23 (shared with display MOSI / VSPI) // T_DO -> GPIO19 (shared with display MISO / VSPI) // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 // MOSI and SCK use default hardware SPI pins // ============================================= // Touch pin definitions (XPT2046 / HR2046 SPI touch controller) // ============================================= #define TOUCH_CS_PIN 15 // T_CS (any GPIO) #define TOUCH_IRQ_PIN -1 // T_IRQ (any GPIO, or -1 if not connected) // ============================================= // ============================================= // Calibration values. // Run the TouchCalibration example and update these if touch is inaccurate. // Typical raw ranges: // - XPT2046 / HR2046 : ~200..3900 (default below) // - 4-wire resistive : ~100..900 // ============================================= #define TOUCH_LEFT_X 300 #define TOUCH_RIGHT_X 3700 #define TOUCH_TOP_Y 300 #define TOUCH_BOT_Y 3700 // ============================================= // Create display object (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); #define RED DIYables_TFT_SPI::colorRGB(255, 0, 0) #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) void setup() { Serial.begin(9600); TFT_display.begin(); TFT_display.setRotation(0); TFT_display.fillScreen(WHITE); TFT_display.initTouchSPI(TOUCH_CS_PIN, TOUCH_IRQ_PIN); // If touch X is mirrored on your board, uncomment: //TFT_display.setTouchInvertX(true); // If touch Y is mirrored on your board, uncomment: //TFT_display.setTouchInvertY(false); TFT_display.setTouchCalibration(TOUCH_LEFT_X, TOUCH_RIGHT_X, TOUCH_TOP_Y, TOUCH_BOT_Y); Serial.println("Touch the screen to see coordinates."); } void loop() { int x, y; if (TFT_display.getTouch(x, y)) { Serial.print("Touch at: "); Serial.print(x); Serial.print(", "); Serial.println(y); TFT_display.fillCircle(x, y, 4, RED); delay(200); } }

Carregar e Testar

  • Ligue o XPT2046 ao barramento VSPI do ESP32, compartilhando os GPIO23/18/19 com o display. T_CS→GPIO15, T_IRQ→GPIO27.
  • Conecte o cabo USB-C.
  • Na Arduino IDE, selecione a placa e a porta e clique em Upload.
  • Abra o Serial Monitor em 9600 baud. Toque no display para ver os valores brutos de X, Y e Z impressos.

Referência da API de Desenho

Método Finalidade Uso
initTouchSPI(cs, irq) Inicializa o XPT2046 no barramento SPI compartilhado. Passe -1 em irq se o pino de interrupção não estiver conectado. TFT_display.initTouchSPI(14, 27);
readTouchRaw(x, y, z) Retorna os valores brutos do ADC do controlador, sem calibração. Retorna true quando a tela está pressionada. TFT_display.readTouchRaw(x, y, z);

Mãos à Obra - Desenho por Toque

Vamos construir um aplicativo de pintura com o dedo. O exemplo TouchDraw combina o controlador de toque XPT2046 com a API de desenho do display. Cada posição de toque é convertida em uma coordenada de pixel calibrada, e um pequeno círculo preenchido é desenhado ali, criando um traço conforme o dedo se move.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Touch Draw Lines Example ------------------------- Draws lines on the screen following the pen. - Touch and drag on the screen to draw. - Lift the pen to stop drawing. - Touch again to start a new line from the last point. NOTE: Run the TouchCalibration example and update setTouchCalibration() below if the touch coordinates are inaccurate. Created by DIYables This example code is in the public domain Product page: https://diyables.io */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> // ============================================= // Wiring (ESP32) // ============================================= // TFT pins (always required) // TFT module ESP32 // ------------ --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // CS -> GPIO5 (TFT_CS_PIN) // RESET -> GPIO4 (TFT_RST_PIN) // DC / RS -> GPIO2 (TFT_DC_PIN) // SDI / MOSI -> GPIO23 (hardware SPI MOSI / VSPI) // SCK -> GPIO18 (hardware SPI SCK / VSPI) // SDO / MISO -> GPIO19 (only needed when reading from display / VSPI) // LED -> 3.3V (or any GPIO via initBacklight) // // XPT2046 / HR2046 / ADS7843 SPI touch controller // (modules with pins: T_CS, T_CLK, T_DIN, T_DO, T_IRQ) // Touch pin ESP32 // ------------ --------------------------------- // T_CS -> GPIO15 (TOUCH_CS_PIN) // T_IRQ -> GPIO27 (TOUCH_IRQ_PIN, optional - use -1 to skip) // T_CLK -> GPIO18 (shared with display SCK / VSPI) // T_DIN -> GPIO23 (shared with display MOSI / VSPI) // T_DO -> GPIO19 (shared with display MISO / VSPI) // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 // ============================================= // Touch pin definitions (XPT2046 / HR2046 SPI touch controller) // ============================================= #define TOUCH_CS_PIN 15 // T_CS (any GPIO) #define TOUCH_IRQ_PIN -1 // T_IRQ (any GPIO, or -1 if not connected) // ============================================= // ============================================= // Calibration values. // Run the TouchCalibration example and update these if touch is inaccurate. // Typical raw ranges: // - XPT2046 / HR2046 : ~200..3900 (default below) // - 4-wire resistive : ~100..900 // ============================================= #define TOUCH_LEFT_X 300 #define TOUCH_RIGHT_X 3700 #define TOUCH_TOP_Y 300 #define TOUCH_BOT_Y 3700 // ============================================= // Create display object (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); #define RED DIYables_TFT_SPI::colorRGB(255, 0, 0) #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) #define PEN_RADIUS 3 void setup() { TFT_display.begin(); TFT_display.setRotation(0); TFT_display.fillScreen(WHITE); TFT_display.initTouchSPI(TOUCH_CS_PIN, TOUCH_IRQ_PIN); // If touch X is mirrored on your board, uncomment: //TFT_display.setTouchInvertX(true); // If touch Y is mirrored on your board, uncomment: //TFT_display.setTouchInvertY(false); TFT_display.setTouchCalibration(TOUCH_LEFT_X, TOUCH_RIGHT_X, TOUCH_TOP_Y, TOUCH_BOT_Y); } void loop() { int x, y; if (TFT_display.getTouch(x, y)) { TFT_display.fillCircle(x, y, PEN_RADIUS, RED); } }

Carregar e Testar

  • Ligue o XPT2046 ao ESP32 como descrito na seção Obter Ponto de Toque acima.
  • Conecte o cabo USB-C.
  • Na Arduino IDE, selecione a placa e a porta e clique em Upload.
  • Arraste o dedo pelo display para pintar na tela.

Referência da API de Desenho

Método Finalidade Uso
initTouchSPI(cs, irq) Inicializa o XPT2046 no barramento VSPI compartilhado. TFT_display.initTouchSPI(14, 27);
setTouchCalibration(minX,maxX,minY,maxY) Converte os valores brutos do ADC em coordenadas de pixel da tela. Obtenha os quatro valores com o exemplo TouchCalibration. TFT_display.setTouchCalibration(200, 3800, 300, 3700);
setTouchInvertX(invert) / setTouchInvertY(invert) Inverte o eixo de toque quando X ou Y está espelhado no seu painel ou lote específico. Chame ANTES de setTouchCalibration(). TFT_display.setTouchInvertY(true);
getTouch(x, y) Retorna as coordenadas de toque calibradas em pixels da tela. Retorna true enquanto a tela está pressionada. if (TFT_display.getTouch(x, y)) { ... }
fillCircle(x, y, r, color) Desenha um pequeno ponto na posição do toque para formar a pintura. TFT_display.fillCircle(x, y, 3, RED);

Mãos à Obra - Botão Touch

Vamos construir um painel de botões touch. O exemplo TouchButton desenha botões retangulares como regiões coloridas no display e depois verifica as coordenadas de toque a cada iteração do loop. Quando um ponto de toque cai dentro dos limites de um botão, o botão é destacado e a ação é executada. Este é o padrão básico de qualquer interface touch com ESP32.

O T_IRQ é opcional. Passe -1 como argumento irq para usar o modo de verificação contínua (polling) sem o pino de interrupção.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Touch Button Press/Release Example ------------------------------------ This example shows how to detect press and release events on a rectangular button using a DIYables SPI TFT display with a 4-wire resistive touch panel. When you touch inside the button, it changes colour and shows "PRESSED". When you release, it returns to its original state. NOTE: Run the TouchCalibration example and update setTouchCalibration() below if the touch coordinates are inaccurate. Created by DIYables This example code is in the public domain Product page: https://diyables.io */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> // ============================================= // Wiring (ESP32) // ============================================= // TFT pins (always required) // TFT module ESP32 // ------------ --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // CS -> GPIO5 (TFT_CS_PIN) // RESET -> GPIO4 (TFT_RST_PIN) // DC / RS -> GPIO2 (TFT_DC_PIN) // SDI / MOSI -> GPIO23 (hardware SPI MOSI / VSPI) // SCK -> GPIO18 (hardware SPI SCK / VSPI) // SDO / MISO -> GPIO19 (only needed when reading from display / VSPI) // LED -> 3.3V (or any GPIO via initBacklight) // // XPT2046 / HR2046 / ADS7843 SPI touch controller // (modules with pins: T_CS, T_CLK, T_DIN, T_DO, T_IRQ) // Touch pin ESP32 // ------------ --------------------------------- // T_CS -> GPIO15 (TOUCH_CS_PIN) // T_IRQ -> -1 (TOUCH_IRQ_PIN, optional - use -1 to skip) // T_CLK -> GPIO18 (shared with display SCK / VSPI) // T_DIN -> GPIO23 (shared with display MOSI / VSPI) // T_DO -> GPIO19 (shared with display MISO / VSPI) // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 // ============================================= // Touch pin definitions (XPT2046 / HR2046 SPI touch controller) // ============================================= #define TOUCH_CS_PIN 15 // T_CS (any GPIO) #define TOUCH_IRQ_PIN -1 // T_IRQ (any GPIO, or -1 if not connected) // ============================================= // ============================================= // Calibration values. // Run the TouchCalibration example and update these if touch is inaccurate. // Typical raw ranges: // - XPT2046 / HR2046 : ~200..3900 (default below) // - 4-wire resistive : ~100..900 // ============================================= #define TOUCH_LEFT_X 300 #define TOUCH_RIGHT_X 3700 #define TOUCH_TOP_Y 300 #define TOUCH_BOT_Y 3700 // ============================================= // Create display object (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); #define BLACK DIYables_TFT_SPI::colorRGB( 0, 0, 0) #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) #define GRAY DIYables_TFT_SPI::colorRGB(128, 128, 128) #define RED DIYables_TFT_SPI::colorRGB(255, 0, 0) #define BUTTON_X 30 #define BUTTON_Y 100 #define BUTTON_W 180 #define BUTTON_H 60 #define DEBOUNCE_DELAY 50 bool lastPressed = false; bool stablePressed = false; unsigned long lastDebounceTime = 0; void drawButton(bool pressed) { uint16_t bg = pressed ? GRAY : RED; TFT_display.fillRect(BUTTON_X, BUTTON_Y, BUTTON_W, BUTTON_H, bg); TFT_display.drawRect(BUTTON_X, BUTTON_Y, BUTTON_W, BUTTON_H, BLACK); TFT_display.setTextColor(WHITE, bg); TFT_display.setTextSize(3); TFT_display.setCursor(BUTTON_X + 10, BUTTON_Y + 16); TFT_display.print(pressed ? "PRESSED" : " PRESS "); } void setup() { Serial.begin(9600); TFT_display.begin(); TFT_display.setRotation(0); TFT_display.fillScreen(WHITE); TFT_display.initTouchSPI(TOUCH_CS_PIN, TOUCH_IRQ_PIN); // If touch X is mirrored on your board, uncomment: //TFT_display.setTouchInvertX(true); // If touch Y is mirrored on your board, uncomment: //TFT_display.setTouchInvertY(false); TFT_display.setTouchCalibration(TOUCH_LEFT_X, TOUCH_RIGHT_X, TOUCH_TOP_Y, TOUCH_BOT_Y); drawButton(false); } void loop() { int x, y; bool pressed = false; if (TFT_display.getTouch(x, y)) { if (x >= BUTTON_X && x < (BUTTON_X + BUTTON_W) && y >= BUTTON_Y && y < (BUTTON_Y + BUTTON_H)) { pressed = true; } } if (pressed != lastPressed) { lastDebounceTime = millis(); } lastPressed = pressed; if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) { if (pressed != stablePressed) { stablePressed = pressed; drawButton(stablePressed); Serial.println(stablePressed ? "Button PRESSED" : "Button RELEASED"); } } }

Carregar e Testar

  • Conecte o T_CS ao GPIO15. O T_IRQ pode ficar desconectado.
  • Conecte o cabo USB-C.
  • Na Arduino IDE, selecione a placa e a porta e clique em Upload.
  • Toque em cada botão no display e confirme que ele é destacado e executa sua ação.

Referência da API de Desenho

Método Finalidade Uso
initTouchSPI(cs, irq) Inicializa o XPT2046. Passe -1 em irq para desativar o pino de interrupção. TFT_display.initTouchSPI(14, -1);
setTouchCalibration(minX,maxX,minY,maxY) Aplica a calibração para que getTouch() retorne coordenadas de pixel precisas. TFT_display.setTouchCalibration(200, 3800, 300, 3700);
setTouchInvertX(invert) / setTouchInvertY(invert) Inverte o eixo de toque quando X ou Y está espelhado no seu painel ou lote específico. Chame ANTES de setTouchCalibration(). TFT_display.setTouchInvertY(true);
getTouch(x, y) Obtém a posição de toque calibrada atual. Retorna true enquanto está pressionada. if (TFT_display.getTouch(x, y)) { ... }
fillRect(x, y, w, h, color) Desenha um botão como um retângulo preenchido. TFT_display.fillRect(10, 10, 120, 60, BLUE);

Mãos à Obra - Calibração do Toque

Vamos construir uma ferramenta de calibração. O exemplo TouchCalibration guia você na medição dos valores extremos brutos do ADC do seu painel XPT2046. Toque em cada canto do display quando solicitado e anote os valores mínimos e máximos de X e Y impressos. Esses quatro números são as constantes de setTouchCalibration() em todos os outros projetos com touch.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Touch Screen Calibration Example --------------------------------- This example measures the raw touch coordinates at all four screen corners and prints ready-to-use calibration values to the Serial Monitor. It uses readTouchRaw() directly â€" it does NOT rely on getTouch() or any existing calibration values, so it works even when touch is completely broken. INSTRUCTIONS: 1. Upload this sketch to your board. 2. Open the Serial Monitor (Ctrl+Shift+M) and set baud rate to 9600. 3. The screen shows a blinking red dot in each corner, numbered 1â€"4: 1 = Top-left 2 = Top-right 3 = Bottom-right 4 = Bottom-left 4. Press and HOLD firmly on the blinking dot. Keep holding until the Serial Monitor prints "Captured!" for that corner. 5. Release, then wait for the next dot to appear and repeat. 6. After all 4 corners, the Serial Monitor prints the calibration values and a ready-to-use setTouchCalibration() call. Copy it into your sketch. NOTE: While waiting, the Serial Monitor continuously prints the live raw Z/X/Y readings so you can confirm that touch is being detected. Created by DIYables This example code is in the public domain Product page: https://diyables.io */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> // ============================================= // Wiring (ESP32) // ============================================= // TFT pins (always required) // TFT module ESP32 // ------------ --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // CS -> GPIO5 (TFT_CS_PIN) // RESET -> GPIO4 (TFT_RST_PIN) // DC / RS -> GPIO2 (TFT_DC_PIN) // SDI / MOSI -> GPIO23 (hardware SPI MOSI / VSPI) // SCK -> GPIO18 (hardware SPI SCK / VSPI) // SDO / MISO -> GPIO19 (only needed when reading from display / VSPI) // LED -> 3.3V (or any GPIO via initBacklight) // // XPT2046 / HR2046 / ADS7843 SPI touch controller // (modules with pins: T_CS, T_CLK, T_DIN, T_DO, T_IRQ) // Touch pin ESP32 // ------------ --------------------------------- // T_CS -> GPIO15 (TOUCH_CS_PIN) // T_IRQ -> GPIO27 (TOUCH_IRQ_PIN, optional - use -1 to skip) // T_CLK -> GPIO18 (shared with display SCK / VSPI) // T_DIN -> GPIO23 (shared with display MOSI / VSPI) // T_DO -> GPIO19 (shared with display MISO / VSPI) // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 // ============================================= // Touch pin definitions (XPT2046 / HR2046 SPI touch controller) // ============================================= #define TOUCH_CS_PIN 15 // T_CS (any GPIO) #define TOUCH_IRQ_PIN -1 // T_IRQ (any GPIO, or -1 if not connected) // ============================================= // ============================================= // Create display object (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN); // Minimum pressure to count as a valid touch. #define TOUCH_Z_MIN 10 // How many consecutive valid samples required before a corner is accepted. #define SAMPLES_NEEDED 10 // Delay between samples (ms). #define SAMPLE_DELAY_MS 30 #define DOT_RADIUS 12 #define BLACK DIYables_TFT_SPI::colorRGB( 0, 0, 0) #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) #define RED DIYables_TFT_SPI::colorRGB(255, 0, 0) // Corner pixel positions â€" filled in setup() once display size is known. // Order: 0=top-left, 1=top-right, 2=bottom-right, 3=bottom-left int cx[4], cy[4]; // Captured averaged raw values per corner. int cap_x[4], cap_y[4]; // ----------------------------------------------------------------------- void drawDot(int corner, bool on) { uint16_t color = on ? RED : WHITE; TFT_display.fillCircle(cx[corner], cy[corner], DOT_RADIUS, color); TFT_display.setTextSize(2); TFT_display.setTextColor(BLACK, color); TFT_display.setCursor(cx[corner] - 6, cy[corner] - 8); TFT_display.print(corner + 1); } void captureCorner(int corner) { const char* names[] = { "Top-left", "Top-right", "Bottom-right", "Bottom-left" }; Serial.println(); Serial.print("Corner "); Serial.print(corner + 1); Serial.print(" ("); Serial.print(names[corner]); Serial.println(")"); Serial.println(" Press and HOLD firmly on the blinking dot."); Serial.println(" Keep holding until you see 'Captured!'"); unsigned long lastBlink = 0; unsigned long lastPrint = 0; bool dotOn = false; int goodSamples = 0; long sumX = 0, sumY = 0; while (true) { // Blink the dot if (millis() - lastBlink > 400) { lastBlink = millis(); dotOn = !dotOn; drawDot(corner, dotOn); } int raw_x, raw_y, z; TFT_display.readTouchRaw(raw_x, raw_y, z); // Print live readings every 500 ms if (millis() - lastPrint > 500) { lastPrint = millis(); Serial.print(" Z="); Serial.print(z); Serial.print(" X="); Serial.print(raw_x); Serial.print(" Y="); Serial.println(raw_y); } if (z >= TOUCH_Z_MIN) { sumX += raw_x; sumY += raw_y; goodSamples++; if (goodSamples >= SAMPLES_NEEDED) { cap_x[corner] = sumX / goodSamples; cap_y[corner] = sumY / goodSamples; Serial.print(" Captured! raw_x="); Serial.print(cap_x[corner]); Serial.print(" raw_y="); Serial.println(cap_y[corner]); drawDot(corner, false); delay(500); return; } } else { goodSamples = 0; sumX = 0; sumY = 0; } delay(SAMPLE_DELAY_MS); } } // ----------------------------------------------------------------------- void setup() { Serial.begin(9600); TFT_display.begin(); TFT_display.setRotation(0); // Always calibrate in rotation 0 TFT_display.fillScreen(WHITE); TFT_display.initTouchSPI(TOUCH_CS_PIN, TOUCH_IRQ_PIN); // If touch X is mirrored on your board, uncomment the line below // BEFORE calibrating (so the printed values match your panel): //TFT_display.setTouchInvertX(true); // If touch Y is mirrored on your board, uncomment: //TFT_display.setTouchInvertY(false); int w = TFT_display.width(); int h = TFT_display.height(); int m = DOT_RADIUS + 4; cx[0] = m; cy[0] = m; cx[1] = w - m; cy[1] = m; cx[2] = w - m; cy[2] = h - m; cx[3] = m; cy[3] = h - m; Serial.println("=== Touch Calibration ==="); for (int i = 0; i < 4; i++) { captureCorner(i); } // Derive calibration values from the four corners int min_x = (cap_x[0] + cap_x[3]) / 2; // left edge int max_x = (cap_x[1] + cap_x[2]) / 2; // right edge int min_y = (cap_y[0] + cap_y[1]) / 2; // top edge int max_y = (cap_y[2] + cap_y[3]) / 2; // bottom edge Serial.println(); Serial.println("=== Calibration Results ==="); Serial.print(" Left X (min_x): "); Serial.println(min_x); Serial.print(" Right X (max_x): "); Serial.println(max_x); Serial.print(" Top Y (min_y): "); Serial.println(min_y); Serial.print(" Bot Y (max_y): "); Serial.println(max_y); Serial.println(); Serial.println("Copy this line into your sketch:"); Serial.print(" TFT_display.setTouchCalibration("); Serial.print(min_x); Serial.print(", "); Serial.print(max_x); Serial.print(", "); Serial.print(min_y); Serial.print(", "); Serial.print(max_y); Serial.println(");"); TFT_display.fillScreen(WHITE); TFT_display.setTextColor(BLACK); TFT_display.setTextSize(2); TFT_display.setCursor(10, 10); TFT_display.println("Done! Check"); TFT_display.setCursor(10, 35); TFT_display.println("Serial Monitor"); } void loop() {}

Carregar e Testar

  • Ligue o XPT2046 ao ESP32 como descrito na seção Obter Ponto de Toque.
  • Conecte o cabo USB-C.
  • Na Arduino IDE, selecione a placa e a porta e clique em Upload.
  • Abra o Serial Monitor em 9600 baud. Siga as instruções na tela e toque em cada canto.
  • Anote os quatro valores impressos e use-os em setTouchCalibration() nos seus outros projetos com touch.

Referência da API de Desenho

Método Finalidade Uso
initTouchSPI(cs, irq) Inicializa o controlador de toque XPT2046. TFT_display.initTouchSPI(14, 27);
readTouchRaw(x, y, z) Lê os valores brutos do ADC para determinar a faixa de calibração. TFT_display.readTouchRaw(x, y, z);
setTouchCalibration(minX,maxX,minY,maxY) Armazena as constantes de calibração para que getTouch() converta corretamente os valores brutos em coordenadas de pixel. TFT_display.setTouchCalibration(200, 3800, 300, 3700);
setTouchInvertX(invert) / setTouchInvertY(invert) Inverte o eixo de toque quando X ou Y está espelhado no seu painel ou lote específico. Chame ANTES de executar a calibração para que os valores armazenados correspondam ao seu painel. TFT_display.setTouchInvertY(true);

Mãos à Obra - SPI Personalizado

Vamos construir em um barramento SPI personalizado. O ESP32 tem dois controladores SPI de hardware: VSPI e HSPI. O exemplo CustomSPI mostra como criar uma instância de SPIClass para o barramento HSPI e passá-la para o construtor do display. Isso libera o barramento VSPI para outros periféricos, como cartões SD ou módulos de sensores que compartilham o SPI.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-tft-lcd-touch-display-spi */ /* Created by DIYables This example code is in the public domain Product page: https://diyables.io This example demonstrates how to use a custom (non-default) SPI bus with the DIYables TFT SPI library. This is useful on boards that have multiple SPI interfaces, such as: - ESP32: HSPI / VSPI - Arduino Giga / Portenta: SPI1 - Raspberry Pi Pico: SPI1 */ // ============================================= // Single include brings in the base class plus all driver classes. // ============================================= #include <DIYables_TFT_SPI.h> // ============================================= // Wiring (ESP32 - VSPI by default) // ============================================= // TFT pins using VSPI (default SPI on ESP32) // TFT module ESP32 VSPI // ------------ --------------------------------- // VCC -> 3.3V (NOT 5V!) // GND -> GND // CS -> GPIO5 (TFT_CS_PIN) // RESET -> GPIO4 (TFT_RST_PIN) // DC / RS -> GPIO2 (TFT_DC_PIN) // SDI / MOSI -> GPIO23 (VSPI MOSI) // SCK -> GPIO18 (VSPI SCK) // SDO / MISO -> GPIO19 (VSPI MISO) // LED -> 3.3V (or any GPIO via initBacklight) // // To use HSPI instead, uncomment the HSPI section below and wire: // MOSI -> GPIO13, SCK -> GPIO14, MISO -> GPIO12 // ============================================= // ============================================= // SPI pin definitions (adjust for your board) // ============================================= #define TFT_CS_PIN 5 #define TFT_DC_PIN 2 #define TFT_RST_PIN 4 // Panel resolution in native (portrait) orientation - change to match your module #define TFT_WIDTH 240 #define TFT_HEIGHT 320 // ============================================= // Select alternate SPI bus (uncomment for your board) // ============================================= // --- ESP32: use HSPI --- // SPIClass hspi(HSPI); // #define MY_SPI &hspi // --- ESP32: use VSPI (default) --- #define MY_SPI &SPI // --- Arduino Giga / Portenta / RP2040: use SPI1 --- // #define MY_SPI &SPI1 // ============================================= // Create display object with custom SPI bus // (uncomment matching driver) // ============================================= // DIYables_ILI9341_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN, MY_SPI); // DIYables_ILI9488_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN, MY_SPI); DIYables_ST7789_SPI TFT_display(TFT_WIDTH, TFT_HEIGHT, TFT_CS_PIN, TFT_DC_PIN, TFT_RST_PIN, MY_SPI); #define BLACK DIYables_TFT_SPI::colorRGB(0, 0, 0) #define WHITE DIYables_TFT_SPI::colorRGB(255, 255, 255) #define RED DIYables_TFT_SPI::colorRGB(255, 0, 0) #define GREEN DIYables_TFT_SPI::colorRGB(0, 255, 0) #define BLUE DIYables_TFT_SPI::colorRGB(0, 0, 255) void setup() { Serial.begin(9600); // For ESP32 HSPI: optionally remap pins before begin() // hspi.begin(14, 12, 13, -1); // SCK, MISO, MOSI, SS TFT_display.begin(); TFT_display.setRotation(1); // Landscape TFT_display.fillScreen(BLACK); uint16_t w = TFT_display.width(); uint16_t h = TFT_display.height(); // Draw a simple test pattern TFT_display.fillRect(0, 0, w / 3, h, RED); TFT_display.fillRect(w / 3, 0, w / 3, h, GREEN); TFT_display.fillRect(w * 2 / 3, 0, w / 3, h, BLUE); TFT_display.setTextColor(WHITE); TFT_display.setTextSize(2); TFT_display.setCursor(10, h / 2 - 10); TFT_display.print("Custom SPI bus OK"); } void loop() { // Nothing to do }

Carregar e Testar

  • Ligue o display TFT aos pinos HSPI do ESP32 ou ao barramento SPI personalizado que você definir no sketch.
  • Conecte o cabo USB-C.
  • Na Arduino IDE, selecione a placa e a porta e clique em Upload.
  • O display inicia no barramento SPI selecionado e mostra um padrão de barras coloridas para confirmar que funcionou.

Referência da API de Desenho

Método Finalidade Uso
SPIClass myBus(HSPI) Cria uma instância de SPIClass ligada ao controlador HSPI (GPIO14/12/13/15). SPIClass HSPI_bus(HSPI);
DIYables_ILI9341_SPI(w,h,cs,dc,rst,spi) Construtor que aceita um ponteiro para qualquer SPIClass. Usa &SPI (VSPI) por padrão quando omitido. DIYables_ILI9341_SPI tft(240, 320, 5, 2, 4, &HSPI_bus);
begin() Inicializa o display no barramento SPI configurado. TFT_display.begin();

Solução de Problemas

Problema Causa Solução
Tela em branco Pinos SPI errados ou alimentação errada Use os pinos VSPI GPIO23/18/19; verifique se o VCC está em 3.3V
Imagem embaralhada Driver errado ativo Descomente apenas o construtor correspondente
Imagem deslocada Largura/altura do construtor não correspondem Ajuste os valores às dimensões reais do seu painel
Sem resposta ao toque Faltam os dados de calibração Execute o exemplo TouchCalibration e copie os valores impressos
Porta não aparece Falta o driver USB Instale o driver USB CP210x ou CH340 para a sua placa

Plataformas Suportadas

A biblioteca é construída sobre a API SPI padrão do Arduino e suporta todas as variantes de ESP32 compatíveis com Arduino (architectures=*).

※ NOSSAS MENSAGENS

  • Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!