ESP32 TFT屏幕:无线投屏到你的局域网

文章目录

  • 前言
  • 一、硬件准备
  • 二、软件准备
  • 1.下载Arduino IDE
  • 2.配置ESP32的开发环境
  • 3.导入所需要的库
  • 三、 硬件连接
  • 四、 代码
  • 五、关于Arduino

  • 前言

    首先,本教程参考B站UP主super大大怪i的开源资料,在此对UP主表示感谢,本人在此基础上做了一些改动以适配我的屏幕和单片机,在下文会提到。本方案实现起来并不困难,硬件比较简单,大约几个小时就可以搞定。然后你就可以在单片机的屏幕上开心地玩原神了。


    一、硬件准备

    首先你需要一块ESP32开发板,本人使用的是一块ESP32-WROOM-32核心板,关于ESP32各个型号的区别可以进入乐鑫官网查看。

    其次是一块屏幕,我使用的是一块2.8寸(240*320)的tft屏幕,原作者使用的屏幕尺寸较小,故换了块大的,驱动是ST7789,使用spi通信协议。

    电脑,这个不用说了。
    能开热点的手机,因为ESP32无法连接处2.4G网络外的其他网络,校园网可能连不上,所以最好用手机开热点使用。

    二、软件准备

    1.下载Arduino IDE

    Arduino IDE这个是我们的编译环境,之前也试过PIO感觉不稳定所以没用,Arduino IDE推荐大家到Arduino的官网下载,最新的版本是2.0新添加了很多功能,颜值也很高,强烈推荐下最新版。

    2.配置ESP32的开发环境

    软件下载完成之后需要配置ESP32的开发环境,打开Arduino IDE的界面,点击文件——>首选项
    在打开的界面中粘贴如下语句,点击确定

    https://dl.espressif.com/dl/package_esp32_index.json
    


    接着重启软件,点击工具——>开发板——>开发板管理器,搜索栏输入ESP32点击第一个下载即可

    下载完成后再次重启软件,点击开发板找到ESP32 Arduino,选择ESP32 Dev Module

    如图所示,配置完成

    3.导入所需要的库

    我们需要导入TFT_eSPI和TJpg_Decoder两个库,TFT_eSPI是一个功能强大的TFT屏幕驱动库,TJpg_Decoder库用于JEPG的解码。
    在管理库中搜索tft,下载TFT_eSPI库,TJpg_Decoder库同理

    添加完成后可以在库中找到相应的库文件

    三、 硬件连接

    #define TFT_MOSI 13 // In some display driver board, it might be written as "SDA" and so on.
    #define TFT_SCLK 14
    #define TFT_CS   15  // Chip select control pin
    #define TFT_DC   2  // Data Command control pin
    #define TFT_RST  4 // Reset pin (could connect to Arduino RESET pin)
    #define TFT_BL   33  // LED back-light
    
    

    另外,tft屏幕的VCC需要连接单片机上的5V引脚,屏幕需要和单片机共地。
    可以使用面包板制作,当然,也可以和我一样使用洞洞板,这样会极大地增加稳定性。

    四、 代码

    在编写程序之前,首先需要对TFT_eSPI这个库中地部分定义更改以适应我的屏幕,打开Aruino的库文件保存目录,我的在C:\Users\expert\OneDrive\文档\Arduino\libraries(每个人的目录位置可能不同),打开找到TFT_eSPI
    找到User_Setup.h这个头文件,用notepad++或者记事本打开

    我们需要做如下改动,选择屏幕驱动这里我用的是ST7789

    选择使用BGR配色方案,这里如果选择了RGB屏幕颜色可能会反转

    选择屏幕的分辨率,我的屏幕是320*240

    选择屏幕的SPI驱动引脚,这里我就使用了ESP32默认的就好(理论上来说可以把引脚配置到任意的GPIO上)

    其他的配置默认即可

    总体头文件如下

    //                            USER DEFINED SETTINGS
    //   Set driver type, fonts to be loaded, pins used and SPI control method etc
    //
    //   See the User_Setup_Select.h file if you wish to be able to define multiple
    //   setups and then easily select which setup file is used by the compiler.
    //
    //   If this file is edited correctly then all the library example sketches should
    //   run without the need to make any more changes for a particular hardware setup!
    //   Note that some sketches are designed for a particular TFT pixel width/height
    
    // User defined information reported by "Read_User_Setup" test & diagnostics example
    #define USER_SETUP_INFO "User_Setup"
    
    // Define to disable all #warnings in library (can be put in User_Setup_Select.h)
    //#define DISABLE_ALL_LIBRARY_WARNINGS
    
    // ##################################################################################
    //
    // Section 1. Call up the right driver file and any options for it
    //
    // ##################################################################################
    
    // Define STM32 to invoke optimised processor support (only for STM32)
    //#define STM32
    
    // Defining the STM32 board allows the library to optimise the performance
    // for UNO compatible "MCUfriend" style shields
    //#define NUCLEO_64_TFT
    //#define NUCLEO_144_TFT
    
    // STM32 8 bit parallel only:
    // If STN32 Port A or B pins 0-7 are used for 8 bit parallel data bus bits 0-7
    // then this will improve rendering performance by a factor of ~8x
    //#define STM_PORTA_DATA_BUS
    //#define STM_PORTB_DATA_BUS
    
    // Tell the library to use parallel mode (otherwise SPI is assumed)
    //#define TFT_PARALLEL_8_BIT
    //#defined TFT_PARALLEL_16_BIT // **** 16 bit parallel ONLY for RP2040 processor ****
    
    // Display type -  only define if RPi display
    //#define RPI_DISPLAY_TYPE // 20MHz maximum SPI
    
    // Only define one driver, the other ones must be commented out
    //#define ILI9341_DRIVER       // Generic driver for common displays
    //#define ILI9341_2_DRIVER     // Alternative ILI9341 driver, see https://github.com/Bodmer/TFT_eSPI/issues/1172
    //#define ST7735_DRIVER      // Define additional parameters below for this display
    //#define ILI9163_DRIVER     // Define additional parameters below for this display
    //#define S6D02A1_DRIVER
    //#define RPI_ILI9486_DRIVER // 20MHz maximum SPI
    //#define HX8357D_DRIVER
    //#define ILI9481_DRIVER
    //#define ILI9486_DRIVER
    //#define ILI9488_DRIVER     // WARNING: Do not connect ILI9488 display SDO to MISO if other devices share the SPI bus (TFT SDO does NOT tristate when CS is high)
    #define ST7789_DRIVER      // Full configuration option, define additional parameters below for this display
    //#define ST7789_2_DRIVER    // Minimal configuration option, define additional parameters below for this display
    //#define R61581_DRIVER
    //#define RM68140_DRIVER
    //#define ST7796_DRIVER
    //#define SSD1351_DRIVER
    //#define SSD1963_480_DRIVER
    //#define SSD1963_800_DRIVER
    //#define SSD1963_800ALT_DRIVER
    //#define ILI9225_DRIVER
    //#define GC9A01_DRIVER
    
    // Some displays support SPI reads via the MISO pin, other displays have a single
    // bi-directional SDA pin and the library will try to read this via the MOSI line.
    // To use the SDA line for reading data from the TFT uncomment the following line:
    
    // #define TFT_SDA_READ      // This option is for ESP32 ONLY, tested with ST7789 and GC9A01 display only
    
    // For ST7735, ST7789 and ILI9341 ONLY, define the colour order IF the blue and red are swapped on your display
    // Try ONE option at a time to find the correct colour order for your display
    
     //#define TFT_RGB_ORDER TFT_RGB  // Colour order Red-Green-Blue
      #define TFT_RGB_ORDER TFT_BGR  // Colour order Blue-Green-Red
    
    // For M5Stack ESP32 module with integrated ILI9341 display ONLY, remove // in line below
    
    // #define M5STACK
    
    // For ST7789, ST7735, ILI9163 and GC9A01 ONLY, define the pixel width and height in portrait orientation
    // #define TFT_WIDTH  80
    // #define TFT_WIDTH  128
    // #define TFT_WIDTH  172 // ST7789 172 x 320
     #define TFT_WIDTH  240 // ST7789 240 x 240 and 240 x 320
    // #define TFT_HEIGHT 160
    // #define TFT_HEIGHT 128
    // #define TFT_HEIGHT 240 // ST7789 240 x 240
     #define TFT_HEIGHT 320 // ST7789 240 x 320
    // #define TFT_HEIGHT 240 // GC9A01 240 x 240
    
    // For ST7735 ONLY, define the type of display, originally this was based on the
    // colour of the tab on the screen protector film but this is not always true, so try
    // out the different options below if the screen does not display graphics correctly,
    // e.g. colours wrong, mirror images, or stray pixels at the edges.
    // Comment out ALL BUT ONE of these options for a ST7735 display driver, save this
    // this User_Setup file, then rebuild and upload the sketch to the board again:
    
    // #define ST7735_INITB
    // #define ST7735_GREENTAB
    // #define ST7735_GREENTAB2
    // #define ST7735_GREENTAB3
    // #define ST7735_GREENTAB128    // For 128 x 128 display
    // #define ST7735_GREENTAB160x80 // For 160 x 80 display (BGR, inverted, 26 offset)
    // #define ST7735_REDTAB
    // #define ST7735_BLACKTAB
    // #define ST7735_REDTAB160x80   // For 160 x 80 display with 24 pixel offset
    
    // If colours are inverted (white shows as black) then uncomment one of the next
    // 2 lines try both options, one of the options should correct the inversion.
    
    // #define TFT_INVERSION_ON
    #define TFT_INVERSION_OFF
    
    
    // ##################################################################################
    //
    // Section 2. Define the pins that are used to interface with the display here
    //
    // ##################################################################################
    
    // If a backlight control signal is available then define the TFT_BL pin in Section 2
    // below. The backlight will be turned ON when tft.begin() is called, but the library
    // needs to know if the LEDs are ON with the pin HIGH or LOW. If the LEDs are to be
    // driven with a PWM signal or turned OFF/ON then this must be handled by the user
    // sketch. e.g. with digitalWrite(TFT_BL, LOW);
    
    // #define TFT_BL   32            // LED back-light control pin
    // #define TFT_BACKLIGHT_ON HIGH  // Level to turn ON back-light (HIGH or LOW)
    
    
    
    // We must use hardware SPI, a minimum of 3 GPIO pins is needed.
    // Typical setup for ESP8266 NodeMCU ESP-12 is :
    //
    // Display SDO/MISO  to NodeMCU pin D6 (or leave disconnected if not reading TFT)
    // Display LED       to NodeMCU pin VIN (or 5V, see below)
    // Display SCK       to NodeMCU pin D5
    // Display SDI/MOSI  to NodeMCU pin D7
    // Display DC (RS/AO)to NodeMCU pin D3
    // Display RESET     to NodeMCU pin D4 (or RST, see below)
    // Display CS        to NodeMCU pin D8 (or GND, see below)
    // Display GND       to NodeMCU pin GND (0V)
    // Display VCC       to NodeMCU 5V or 3.3V
    //
    // The TFT RESET pin can be connected to the NodeMCU RST pin or 3.3V to free up a control pin
    //
    // The DC (Data Command) pin may be labelled AO or RS (Register Select)
    //
    // With some displays such as the ILI9341 the TFT CS pin can be connected to GND if no more
    // SPI devices (e.g. an SD Card) are connected, in this case comment out the #define TFT_CS
    // line below so it is NOT defined. Other displays such at the ST7735 require the TFT CS pin
    // to be toggled during setup, so in these cases the TFT_CS line must be defined and connected.
    //
    // The NodeMCU D0 pin can be used for RST
    //
    //
    // Note: only some versions of the NodeMCU provide the USB 5V on the VIN pin
    // If 5V is not available at a pin you can use 3.3V but backlight brightness
    // will be lower.
    
    
    // ###### EDIT THE PIN NUMBERS IN THE LINES FOLLOWING TO SUIT YOUR ESP8266 SETUP ######
    
    // For NodeMCU - use pin numbers in the form PIN_Dx where Dx is the NodeMCU pin designation
    #define TFT_CS   PIN_D8  // Chip select control pin D8
    #define TFT_DC   PIN_D3  // Data Command control pin
    #define TFT_RST  PIN_D4  // Reset pin (could connect to NodeMCU RST, see next line)
    //#define TFT_RST  -1    // Set TFT_RST to -1 if the display RESET is connected to NodeMCU RST or 3.3V
    
    //#define TFT_BL PIN_D1  // LED back-light (only for ST7789 with backlight control pin)
    
    //#define TOUCH_CS PIN_D2     // Chip select pin (T_CS) of touch screen
    
    //#define TFT_WR PIN_D2       // Write strobe for modified Raspberry Pi TFT only
    
    
    // ######  FOR ESP8266 OVERLAP MODE EDIT THE PIN NUMBERS IN THE FOLLOWING LINES  ######
    
    // Overlap mode shares the ESP8266 FLASH SPI bus with the TFT so has a performance impact
    // but saves pins for other functions. It is best not to connect MISO as some displays
    // do not tristate that line when chip select is high!
    // Note: Only one SPI device can share the FLASH SPI lines, so a SPI touch controller
    // cannot be connected as well to the same SPI signals.
    // On NodeMCU 1.0 SD0=MISO, SD1=MOSI, CLK=SCLK to connect to TFT in overlap mode
    // On NodeMCU V3  S0 =MISO, S1 =MOSI, S2 =SCLK
    // In ESP8266 overlap mode the following must be defined
    
    //#define TFT_SPI_OVERLAP
    
    // In ESP8266 overlap mode the TFT chip select MUST connect to pin D3
    //#define TFT_CS   PIN_D3
    //#define TFT_DC   PIN_D5  // Data Command control pin
    //#define TFT_RST  PIN_D4  // Reset pin (could connect to NodeMCU RST, see next line)
    //#define TFT_RST  -1  // Set TFT_RST to -1 if the display RESET is connected to NodeMCU RST or 3.3V
    
    
    // ###### EDIT THE PIN NUMBERS IN THE LINES FOLLOWING TO SUIT YOUR ESP32 SETUP   ######
    
    // For ESP32 Dev board (only tested with ILI9341 display)
    // The hardware SPI can be mapped to any pins
    
    //#define TFT_MISO 19
    //#define TFT_MOSI 23
    //#define TFT_SCLK 18
    //#define TFT_CS   15  // Chip select control pin
    //#define TFT_DC    2  // Data Command control pin
    //#define TFT_RST   4  // Reset pin (could connect to RST pin)
    //#define TFT_RST  -1  // Set TFT_RST to -1 if display RESET is connected to ESP32 board RST
    
    // For ESP32 Dev board (only tested with GC9A01 display)
    // The hardware SPI can be mapped to any pins
    
    #define TFT_MOSI 13 // In some display driver board, it might be written as "SDA" and so on.
    #define TFT_SCLK 14
    #define TFT_CS   15  // Chip select control pin
    #define TFT_DC   2  // Data Command control pin
    #define TFT_RST  4 // Reset pin (could connect to Arduino RESET pin)
    #define TFT_BL   33  // LED back-light
    
    //#define TOUCH_CS 21     // Chip select pin (T_CS) of touch screen
    
    //#define TFT_WR 22    // Write strobe for modified Raspberry Pi TFT only
    
    // For the M5Stack module use these #define lines
    //#define TFT_MISO 19
    //#define TFT_MOSI 23
    //#define TFT_SCLK 18
    //#define TFT_CS   14  // Chip select control pin
    //#define TFT_DC   27  // Data Command control pin
    //#define TFT_RST  33  // Reset pin (could connect to Arduino RESET pin)
    //#define TFT_BL   32  // LED back-light (required for M5Stack)
    
    // ######       EDIT THE PINs BELOW TO SUIT YOUR ESP32 PARALLEL TFT SETUP        ######
    
    // The library supports 8 bit parallel TFTs with the ESP32, the pin
    // selection below is compatible with ESP32 boards in UNO format.
    // Wemos D32 boards need to be modified, see diagram in Tools folder.
    // Only ILI9481 and ILI9341 based displays have been tested!
    
    // Parallel bus is only supported for the STM32 and ESP32
    // Example below is for ESP32 Parallel interface with UNO displays
    
    // Tell the library to use 8 bit parallel mode (otherwise SPI is assumed)
    //#define TFT_PARALLEL_8_BIT
    
    // The ESP32 and TFT the pins used for testing are:
    //#define TFT_CS   33  // Chip select control pin (library pulls permanently low
    //#define TFT_DC   15  // Data Command control pin - must use a pin in the range 0-31
    //#define TFT_RST  32  // Reset pin, toggles on startup
    
    //#define TFT_WR    4  // Write strobe control pin - must use a pin in the range 0-31
    //#define TFT_RD    2  // Read strobe control pin
    
    //#define TFT_D0   12  // Must use pins in the range 0-31 for the data bus
    //#define TFT_D1   13  // so a single register write sets/clears all bits.
    //#define TFT_D2   26  // Pins can be randomly assigned, this does not affect
    //#define TFT_D3   25  // TFT screen update performance.
    //#define TFT_D4   17
    //#define TFT_D5   16
    //#define TFT_D6   27
    //#define TFT_D7   14
    
    // ######       EDIT THE PINs BELOW TO SUIT YOUR STM32 SPI TFT SETUP        ######
    
    // The TFT can be connected to SPI port 1 or 2
    //#define TFT_SPI_PORT 1 // SPI port 1 maximum clock rate is 55MHz
    //#define TFT_MOSI PA7
    //#define TFT_MISO PA6
    //#define TFT_SCLK PA5
    
    //#define TFT_SPI_PORT 2 // SPI port 2 maximum clock rate is 27MHz
    //#define TFT_MOSI PB15
    //#define TFT_MISO PB14
    //#define TFT_SCLK PB13
    
    // Can use Ardiuno pin references, arbitrary allocation, TFT_eSPI controls chip select
    //#define TFT_CS   D5 // Chip select control pin to TFT CS
    //#define TFT_DC   D6 // Data Command control pin to TFT DC (may be labelled RS = Register Select)
    //#define TFT_RST  D7 // Reset pin to TFT RST (or RESET)
    // OR alternatively, we can use STM32 port reference names PXnn
    //#define TFT_CS   PE11 // Nucleo-F767ZI equivalent of D5
    //#define TFT_DC   PE9  // Nucleo-F767ZI equivalent of D6
    //#define TFT_RST  PF13 // Nucleo-F767ZI equivalent of D7
    
    //#define TFT_RST  -1   // Set TFT_RST to -1 if the display RESET is connected to processor reset
                            // Use an Arduino pin for initial testing as connecting to processor reset
                            // may not work (pulse too short at power up?)
    
    // ##################################################################################
    //
    // Section 3. Define the fonts that are to be used here
    //
    // ##################################################################################
    
    // Comment out the #defines below with // to stop that font being loaded
    // The ESP8366 and ESP32 have plenty of memory so commenting out fonts is not
    // normally necessary. If all fonts are loaded the extra FLASH space required is
    // about 17Kbytes. To save FLASH space only enable the fonts you need!
    
    #define LOAD_GLCD   // Font 1. Original Adafruit 8 pixel font needs ~1820 bytes in FLASH
    #define LOAD_FONT2  // Font 2. Small 16 pixel high font, needs ~3534 bytes in FLASH, 96 characters
    #define LOAD_FONT4  // Font 4. Medium 26 pixel high font, needs ~5848 bytes in FLASH, 96 characters
    #define LOAD_FONT6  // Font 6. Large 48 pixel font, needs ~2666 bytes in FLASH, only characters 1234567890:-.apm
    #define LOAD_FONT7  // Font 7. 7 segment 48 pixel font, needs ~2438 bytes in FLASH, only characters 1234567890:-.
    #define LOAD_FONT8  // Font 8. Large 75 pixel font needs ~3256 bytes in FLASH, only characters 1234567890:-.
    //#define LOAD_FONT8N // Font 8. Alternative to Font 8 above, slightly narrower, so 3 digits fit a 160 pixel TFT
    #define LOAD_GFXFF  // FreeFonts. Include access to the 48 Adafruit_GFX free fonts FF1 to FF48 and custom fonts
    
    // Comment out the #define below to stop the SPIFFS filing system and smooth font code being loaded
    // this will save ~20kbytes of FLASH
    #define SMOOTH_FONT
    
    
    // ##################################################################################
    //
    // Section 4. Other options
    //
    // ##################################################################################
    
    // For RP2040 processor and SPI displays, uncomment the following line to use the PIO interface.
    //#define RP2040_PIO_SPI // Leave commented out to use standard RP2040 SPI port interface
    
    // For the RP2040 processor define the SPI port channel used (default 0 if undefined)
    //#define TFT_SPI_PORT 1 // Set to 0 if SPI0 pins are used, or 1 if spi1 pins used
    
    // For the STM32 processor define the SPI port channel used (default 1 if undefined)
    //#define TFT_SPI_PORT 2 // Set to 1 for SPI port 1, or 2 for SPI port 2
    
    // Define the SPI clock frequency, this affects the graphics rendering speed. Too
    // fast and the TFT driver will not keep up and display corruption appears.
    // With an ILI9341 display 40MHz works OK, 80MHz sometimes fails
    // With a ST7735 display more than 27MHz may not work (spurious pixels and lines)
    // With an ILI9163 display 27 MHz works OK.
    
    // #define SPI_FREQUENCY   1000000
    // #define SPI_FREQUENCY   5000000
    // #define SPI_FREQUENCY  10000000
    // #define SPI_FREQUENCY  20000000
    #define SPI_FREQUENCY  27000000
    // #define SPI_FREQUENCY  40000000
    // #define SPI_FREQUENCY  55000000 // STM32 SPI1 only (SPI2 maximum is 27MHz)
    // #define SPI_FREQUENCY  80000000
    
    // Optional reduced SPI frequency for reading TFT
    #define SPI_READ_FREQUENCY  20000000
    
    // The XPT2046 requires a lower SPI clock rate of 2.5MHz so we define that here:
    #define SPI_TOUCH_FREQUENCY  2500000
    
    // The ESP32 has 2 free SPI ports i.e. VSPI and HSPI, the VSPI is the default.
    // If the VSPI port is in use and pins are not accessible (e.g. TTGO T-Beam)
    // then uncomment the following line:
    //#define USE_HSPI_PORT
    
    // Comment out the following #define if "SPI Transactions" do not need to be
    // supported. When commented out the code size will be smaller and sketches will
    // run slightly faster, so leave it commented out unless you need it!
    
    // Transaction support is needed to work with SD library but not needed with TFT_SdFat
    // Transaction support is required if other SPI devices are connected.
    
    // Transactions are automatically enabled by the library for an ESP32 (to use HAL mutex)
    // so changing it here has no effect
    
    // #define SUPPORT_TRANSACTIONS
    
    

    配置完库文件之后,下面是主程序,打开你的手机热点,并使用电脑连接热点,填好WFI密码和名称连接电脑烧录即可

    #include <TFT_eSPI.h>
    #include <SPI.h>
    #include <WiFi.h>
    #include <TJpg_Decoder.h>
    #include <pgmspace.h>
    
    uint16_t  PROGMEM dmaBuffer1[32*32]; // Toggle buffer for 32*32 MCU block, 1024bytes
    uint16_t  PROGMEM dmaBuffer2[32*32]; // Toggle buffer for 32*32 MCU block, 1024bytes
    uint16_t* dmaBufferPtr = dmaBuffer1;
    bool dmaBufferSel = 0;
    
    TFT_eSPI tft = TFT_eSPI(); 
    TFT_eSprite clk = TFT_eSprite(&tft);
    char* ssid     = ""; //填写你的wifi名字
    char* password = ""; //填写你的wifi密码
    int httpPort = 8081; //设置监听端口
    WiFiServer server; //初始化一个服务端对象
    uint8_t buff[7000] PROGMEM= {0};//每一帧的临时缓存
    uint8_t img_buff[50000] PROGMEM= {0};//用于存储tcp传过来的图片
    uint16_t size_count=0;//计算一帧的字节大小
    
    bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t* bitmap)
    {
      if ( y >= tft.height() ) return 0;
     
      // Double buffering is used, the bitmap is copied to the buffer by pushImageDMA() the
      // bitmap can then be updated by the jpeg decoder while DMA is in progress
      if (dmaBufferSel) dmaBufferPtr = dmaBuffer2;
      else dmaBufferPtr = dmaBuffer1;
      dmaBufferSel = !dmaBufferSel; // Toggle buffer selection
      //  pushImageDMA() will clip the image block at screen boundaries before initiating DMA
      tft.pushImageDMA(x, y, w, h, bitmap, dmaBufferPtr); // Initiate DMA - blocking only if last DMA is not complete
      return 1;
    }
    
    byte loadNum = 6;
    void loading(byte delayTime){//启动动画
      clk.setColorDepth(8);
      
      clk.createSprite(200, 50);
      clk.fillSprite(0x0000);
    
      clk.drawRoundRect(0,0,200,16,8,0xFFFF);
      clk.fillRoundRect(3,3,loadNum,10,5,0xFFFF);
      clk.setTextDatum(CC_DATUM);
      clk.setTextColor(TFT_GREEN, 0x0000); 
      clk.drawString("Connecting to WiFi",100,40,2);
      clk.pushSprite(20,67);//20 110
      clk.deleteSprite();
      loadNum += 1;
      if(loadNum>=195){
        loadNum = 195;
      }
      delay(delayTime);
    }
    
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      tft.begin();
      tft.initDMA();
      tft.setRotation(0);//横屏
      tft.fillScreen(TFT_BLACK);//黑色
      tft.setTextColor(TFT_BLACK,TFT_WHITE);
      
      WiFi.begin(ssid, password); //连接wifi
      delay(1000); //等待1秒
      while (WiFi.status() != WL_CONNECTED) {
        for(byte n=0;n<10;n++){ //每500毫秒检测一次状态
          loading(50);
        }
      }
       while(loadNum < 195){ //让动画走完
        loading(3);
      }
      if (WiFi.status() == WL_CONNECTED) //判断如果wifi连接成功
      { 
        
        //client.setNoDelay(false);//关闭Nagle算法
        Serial.println("wifi is connected!");
        Serial.print("SSID: ");
        Serial.println(WiFi.SSID());
        IPAddress ip = WiFi.localIP();
        Serial.print("IP Address: ");
        Serial.println(ip);
        Serial.println("Port: "+String(httpPort));
        //tft.setSwapBytes(true);
        tft.setRotation(1);
        tft.fillScreen(TFT_BLACK);//黑色
        tft.setTextColor(TFT_BLACK,TFT_WHITE);
        tft.drawString("Wifi Have Connected To "+String(WiFi.SSID()),20,20,2);
    
        tft.drawString("IP: "+ip.toString(),20,40,2);
        tft.drawString("Port: "+String(httpPort),20,60,2);
        Serial.println("Waiting a client to connect.........");
        server.begin(httpPort); //服务器启动监听端口号
        server.setNoDelay(true);
      }
        TJpgDec.setJpgScale(1);
        TJpgDec.setSwapBytes(true);
        TJpgDec.setCallback(tft_output);//解码成功回调函数
    }
    uint16_t read_count=0;//读取buff的长度
    uint8_t pack_size[2];//用来装包大小字节
    uint16_t frame_size;//当前帧大小
    float start_time,end_time;//帧处理开始和结束时间
    float receive_time,deal_time;//帧接收和解码时间
    
    void loop() {
      // put your main code here, to run repeatedly:
      //沾包问题 recv阻塞,长时间收不到数据就会断开
      //断开连接原因,读取buff太快,上位机发送太快造成buff溢出,清空缓冲区会断开(FLUSH)
      WiFiClient client = server.available(); //尝试建立客户对象
      if(client){
        Serial.println("[New Client!]");
        client.write("ok");//向上位机发送下一帧发送指令
        
        while(client.connected())//如果客户端处于连接状态client.connected()
        {
          client.write("no");//向上位机发送当前帧未写入完指令
          while(client.available()){
            while (client.available()) {//检测缓冲区是否有数据
                 if(read_count==0)
                  {
                    start_time=millis();
                    client.read(pack_size,2);//读取帧大小
                    frame_size=pack_size[0]+(pack_size[1]<<8);
                 }
                 read_count=client.read(buff,7000);//向缓冲区读取数据
                 memcpy(&img_buff[size_count],buff,read_count);//将读取的buff字节地址复制给img_buff数组
                 size_count=size_count+read_count;//计数当前帧字节位置
      //           Serial.println(size_count);
                 if(img_buff[frame_size-3]==0xaa && img_buff[frame_size-2]==0xbb && img_buff[frame_size-1]==0xcc)//判断末尾数据是否当前帧校验位
                 {
                  receive_time=millis()-start_time;
                  deal_time=millis();
                  img_buff[frame_size-3]=0;img_buff[frame_size-2]=0;img_buff[frame_size-1]=0;//清除标志位
                  tft.startWrite();//必须先使用startWrite,以便TFT芯片选择保持低的DMA和SPI通道设置保持配置
                  TJpgDec.drawJpg(0,0,img_buff, sizeof(img_buff));//在左上角的0,0处绘制图像——在这个草图中,DMA请求在回调tft_output()中处理
                  tft.endWrite();//必须使用endWrite来释放TFT芯片选择和释放SPI通道吗
      //            memset(&img_buff,0,sizeof(img_buff));//清空buff
                  size_count=0;//下一帧
                  read_count=0;
                  client.write("ok");//向上位机发送下一帧发送指令
                  end_time = millis(); //计算mcu刷新一张图片的时间,从而算出1s能刷新多少张图,即得出最大刷新率
                  Serial.printf("帧大小:%d " ,frame_size);Serial.print("MCU处理速度:"); Serial.print(1000 / (end_time - start_time), 2); Serial.print("Fps");
                  Serial.printf("帧接收耗时:%.2fms,帧解码显示耗时:%.2fms\n",receive_time,(millis()-deal_time));
                  break;
                  }       
            }
          }
        }
        client.stop();
        Serial.println("连接中断,请复位重新创建服务端");
      }
    }
    

    复位ESP32,然后你会观察到如下画面表示连接成功

    打开电脑上的上位机软件,地址,填写配置IP和端口号,这两个需要和屏幕上显示的内容相同

    选择投屏区域、尺寸和质量,同步还是异步(会对传输速度产生影响)点击开启投屏后按下ESP32的复位键,屏幕上就会出现投屏的画面。

    五、关于Arduino

    如果你对Arduino不太了解,这里强烈推荐你去看一下太极创客的教程,这是目前为止我看到的最良心的Arduino教程,同时,我也看到有很多人对使用Arduino IDE的编译环境有偏见,觉得代码封装层次太高,配置简单学不到东西,其实大可不必这样,在单片机中创意和想法是大于技术的,如果你是电子类专业,学习Arduino可以作为继续学习51系类单片机,stm32等ARM架构单片机甚至是树莓派等平台的入门。如果你是非电类专业,Arduino可以帮你了解到单片机的开发乐趣。不要忘了,Arduino有着全世界最大的开源社区,连稚晖君的HoloCubic 都是使用和Arduino相似的PIO开发的。
    最后不要忘了点赞关注,有问题可以发到评论区交流。

    物联沃分享整理
    物联沃-IOTWORD物联网 » ESP32 TFT屏幕:无线投屏到你的局域网

    发表评论