Skip to content

ESP32 HMI 5.0-inch Arduino Tutorial

Overview


The example tutorial is an environmental monitoring project, demonstrate how to create a UI and use a DHT20 sensor to obtain the environment temperature and humidity and display it on the screen; and how to control the LED on and off by the buttons on the screen.

In this tutorial, we will show you how to design the UI with SquareLine Studio, and show you how to upload the code with Arduino IDE.

gif2

Hardware Preparation


CrowPanel ESP32 5.0'' HMI Crowtail-DHT20 Crowtail-LED
CrowPanel-ESP32-5-0inch.png CROWTAIL-DHT20 CROWTAIL-LED
BUYNOW BUYNOW BUYNOW

Design UI file with SquareLine Studio


Get Started with SquareLine Studio

Please click the card below to learn how to download the SquareLine Studio, and how to export the demo UI file.

GetStartedWithSquareLine

Please click download to download the demo for "Example Demonstration" section in "Get Started with SquareLine Studio".

Design UI file with SquareLine Studio

Let's start learning how to create our own UI after getting an initial understanding of SquareLine Studio.

  1. Open the SquareLine Studio and create a project.

    A. In the latest version of SLS, select "Elecrow"->"DIS07050H...Arduino-IDE"

    SLS-UI-1-1

    B. In the earlier version of SLS, select "Arduino"->"Arduino with TFT_eSPI".

    SLS-UI-1

    Note:

    When select the Arduino framwork, there's only one option "Arduino with TFT_eSPI". By choosing this, the squareline studio will generate a template code suitable for the TFT_eSPI library. However, squareline studio not only supports the TFT_eSPI library, it supports a variety of libraries to suit different hardware and application needs. For example, Adafruit_GFX library, LovyanGFX etc.

    After using SLS to generate UI code, we then use different graphics libraries according to different hardware and modify the corresponding code to display the content you design.

    Set the name of the project, set the screen resolution to 800*480, set the color depth to 16bit, and keep other default settings. After setting, click CREATE to create the project.

    SLS-UI-2

    • 16-bit color depth: can represent 65,536 colors through RGB 5:6:5 sub-pixel representation, that is, each RGB channel occupies 5 bits and 1 bit (a total of 16 bits) to represent colors.
  2. After creation, enter the following interface with a blank background.

    SLS-UI-3

  3. In the "Assets" area, click "ADD FILE TO ASSETS" to add custom images or icons.

    Please click download to download the custom images used in this tutorial.

    SLS-UI-4

    Note:

    Images only support PNG format. The pixels of the image need to be smaller than the pixel size of the screen used in your project. The size of each image should not exceed 100k, preferably within 30k, to provide a smooth display effect.

  4. Add background.

    Find "Inspector"->"STYLE SETTING", click to expand "STYLE(MAIN)", then click the 2nd "Background". Check the "Bg Image" and select the background image.

    SLS-UI-5

    SLS-UI-6

  5. Add Label widget to display temperature and humidity.

    Click "Label" in the "Widgets" area, and "Label1" will be added to the current Screen.

    SLS-UI-7

    The position and size of the label can be adjusted by dragging the mouse. You can also directly enter numbers in the Inspector→LABEL→Transform to adjust.

    SLS-UI-8

    You can set the font color and other attributes in STYLE SETTING→STYLE(MAIN).

    SLS-UI-9

    Add a Label2 to display the humidity value in the same way. You can also directly right-click the Label1 to duplicate it.

    SLS-UI-10

    Then set different positions for the Label2.

    SLS-UI-11

    Modify the text content to display a default value.

    SLS-UI-18

  6. Add Button widget to control the LED.

    Click "Button" in the "Widgets" area, and "Button1" will be added to the current Screen.

    SLS-UI-12

    The position and size of the label can be adjusted by dragging the mouse. You can also directly enter numbers in the Inspector→BUTTON→Transform to adjust.

    SLS-UI-13

    Add an identification symbol to the button. The button in this tutorial controls the LED switch, so you only need to mark the button "on" and "off". You can add LABEL widgets or add a background images to the button. This tutorial will demonstrate how to add a background image to a button.

    Click the Button1, then find Inspector->STYLE SETTINGS ->STYLE(MAIN) ->Background, and select the image.

    SLS-UI-14

    SLS-UI-15

    In the same way, duplicate a Button widget. And drag it to the corresponding position to modify different background image.

    SLS-UI-16

    SLS-UI-17

    Set the status of the button to identify different states.

    In "Inspector"->"STYLE SETTINGS"->"STATE", set display white background color by DEFAULT and red when on the PRESSED state.

    SLS-UI-19

    SLS-UI-20

    Make the same settings for the "OFF" button.

  7. Add events to buttons.

    Note: Because the button controls the on and off of the LED, we can add any event here to generate the code framework for the button event when exporting the UI file. We will modify the code of the button event to control the LED latter.

    Select the button and click "ADD EVENT".

    SLS-UI-21

    Select "released" as the trigger condition, select a trigger event in "Action". It will be modified in the generated program to achieve the LED control function.

    SLS-UI-22

    Complete the event. Here I choose to change the screen, and the screen to be switched is Screen1.

    SLS-UI-23

    Add event to Button2 (OFF) in the same way.

    SLS-UI-24

  8. Export UI files.

    Click "File" -> "Project Settings" and make settings for the exported file.

    SLS-UI-25

    Set the export path of the file (set the path according to your own file).

    SLS-UI-26

    Fill in lvgl.h in LVGL Include Path. Check "Flat export(exports all files to one folder )".

    Then click "APPLY CHANGES".

    Tips: After selecting the flat export, the output files will be in the same folder, so that the output code does not need to modify the path in the program. If not, the output files will be classified and placed in different folders. The compiler may not be able to recognize different paths, which will cause some trouble. In this case, the user needs to modify it manually, so it is recommended to select all files to be output to the same folder.

    SLS-UI-27

    Export UI files. The exported files will be in the path we set earlier.

    SLS-UI-28

    SLS-UI-29

    In order to be used with the main program, all UI files generated need to be placed in the same folder as the main program.

    Please click download to download the main program(and the expert UI is included).

    SLS-UI-30

  9. Modify the button event code.

Open the main program. And all the UI file in the same folder will open too.

SLS-UI-31

First, define an extern variable in the ui.h file to store the status of the LED. In the main program, the LED light is controlled to turn on and off by judging the status of this variable.

extern int led;

SLS-UI-41

Then find "FUNCTION" in the ui.c file. Here is the corresponding code generated when we add events in SquareLine.

SLS-UI-33

Comment out or delete the code circled in red in the picture above, add new code to assign a value to the LED variable.

  • When button 1 (ON button) is pressed, set the LED value to 1.

    SLS-UI-34

  • When button 2 (OFF button) is pressed, set the LED value to 0.

    SLS-UI-35

The UI file export is completed, and the button event function is also modified. Next we're going to learn about the Arduino main program and learn how to upload the code to the board.

Build the Project with Arduino IDE


Get Started with Arduino IDE

Please click the card below to learn how to install Arduino IDE, and install ESP32 board in the Arduino IDE.

GetStartedWithArduinoIDE.png

Install Libraries

In this project, we will use the following libraries:

#include <lvgl.h>
#include <Crowbits_DHT20.h>
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <LovyanGFX.hpp>
#include <lgfx/v1/platforms/esp32s3/Panel_RGB.hpp>
#include <lgfx/v1/platforms/esp32s3/Bus_RGB.hpp>
//UI
#include "ui.h"
  • #include <lvgl.h> : library for graphical interfaces.
  • #include <Adafruit_GFX.h>: to draw graphics on various display devices.
  • #include <Crowbits_DHT20.h>: to read data from the DHT20 temperature and humidity sensor.
  • #include <LovyanGFX.hpp>: The LovyanGFX library is a library for drawing graphics on embedded systems, providing rich graphics functions and APIs.
  • lgfx/v1/platforms/esp32s3/Panel_RGB.hppand lgfx/v1/platforms/esp32s3/Bus_RGB.hpp: These two libraries are part of the LovyanGFX library, specifically for driving RGB color panels on ESP32-S3 microcontrollers. Panel_RGB.hpp provides functions for communicating with RGB panels, while Bus_RGB.hpp provides functions for communicating with RGB buses, which are often used to control devices such as LCD screens.
  • touch.h: touch drive.
  • #include "ui.h": is a custom header file that contain UI-related functions or definitions.

Please click download to download the libraries we modified.

Then click "File" -> "Preferences" -> "Setting" to check the sketchbook location. Place the libraries downloaded to the sketchbook location.

SLS-UI-36

SLS-UI-37

Tips:

  • If you install the lvgl libraries by Library Manager, you need to copy the demos folder and examples folder and paste them to src folder. And modify the lv_conf_template.h file and rename it to lv_conf.h, and place it in libraries folder.(Please refer to the library provided)

SLS-UI-38

SLS-UI-39

SLS-UI-40

Code Explanation

Basic Definition

  • LGFX class, which is a subclass of lgfx::LGFX_Device. The main function is to configure and initialize an RGB color panel, and then connect it to the RGB bus on the ESP32-S3 microcontroller to display graphics on the panel.

    class LGFX : public lgfx::LGFX_Device
    {
    public:
    
      lgfx::Bus_RGB     _bus_instance;
      lgfx::Panel_RGB   _panel_instance;
    
      LGFX(void)
      {
        {
          auto cfg = _bus_instance.config();
          cfg.panel = &_panel_instance;
          
          cfg.pin_d0  = GPIO_NUM_8; // B0
          cfg.pin_d1  = GPIO_NUM_3;  // B1
          cfg.pin_d2  = GPIO_NUM_46;  // B2
          cfg.pin_d3  = GPIO_NUM_9;  // B3
          cfg.pin_d4  = GPIO_NUM_1;  // B4
          
          cfg.pin_d5  = GPIO_NUM_5;  // G0
          cfg.pin_d6  = GPIO_NUM_6; // G1
          cfg.pin_d7  = GPIO_NUM_7;  // G2
          cfg.pin_d8  = GPIO_NUM_15;  // G3
          cfg.pin_d9  = GPIO_NUM_16; // G4
          cfg.pin_d10 = GPIO_NUM_4;  // G5
          
          cfg.pin_d11 = GPIO_NUM_45; // R0
          cfg.pin_d12 = GPIO_NUM_48; // R1
          cfg.pin_d13 = GPIO_NUM_47; // R2
          cfg.pin_d14 = GPIO_NUM_21; // R3
          cfg.pin_d15 = GPIO_NUM_14; // R4
    
          cfg.pin_henable = GPIO_NUM_40;
          cfg.pin_vsync   = GPIO_NUM_41;
          cfg.pin_hsync   = GPIO_NUM_39;
          cfg.pin_pclk    = GPIO_NUM_0;
          cfg.freq_write  = 15000000;
    
          cfg.hsync_polarity    = 0;
          cfg.hsync_front_porch = 8;
          cfg.hsync_pulse_width = 4;
          cfg.hsync_back_porch  = 43;
          
          cfg.vsync_polarity    = 0;
          cfg.vsync_front_porch = 8;
          cfg.vsync_pulse_width = 4;
          cfg.vsync_back_porch  = 12;
    
          cfg.pclk_active_neg   = 1;
          cfg.de_idle_high      = 0;
          cfg.pclk_idle_high    = 0;
    
          _bus_instance.config(cfg);
        }
                {
          auto cfg = _panel_instance.config();
          cfg.memory_width  = 800;
          cfg.memory_height = 480;
          cfg.panel_width  = 800;
          cfg.panel_height = 480;
          cfg.offset_x = 0;
          cfg.offset_y = 0;
          _panel_instance.config(cfg);
        }
        _panel_instance.setBus(&_bus_instance);
        setPanel(&_panel_instance);
    
      }
    };
    LGFX lcd;//
    
    /*
    (1) The LGFX class inherits from lgfx::LGFX_Device, which means it will inherit the member variables and methods defined in LGFX_Device.
    
    (2) In the constructor of the LGFX class, we first create an instance of _bus_instance for lgfx::Bus_RGB and an instance of _panel_instance for lgfx::Panel_RGB.
    
    (3) Next, initialize the RGB bus and RGB panel by configuring the parameters of these two instances. In this code, data pins for each color are set, as well as some parameters related to synchronization signals and clocks, to ensure the correct transmission and display of data.
    
    (4) The configuration of _bus_instance and _panel_instance is based on their respective configuration objects, which are lgfx::Bus_RGB::config_t and lgfx::Panel_RGB::config_t.
    
    (5) Finally, set the bus used by the panel by calling _panel_instance.setBus(&_bus_instance), and then call setPanel(&_panel_instance) to set the panel as the panel of the current device.
    
    (6) Finally, a global LGFX object lcd was created for graphical drawing operations using this configured panel elsewhere.
    */
    
  • Define backlight pins, led variables, and screen resolution parameters. And include touch driver.

    #define TFT_BL 2
    int led;
    #include "touch.h"
    /*Changing the screen resolution*/
    static const uint16_t screenWidth;
    static const uint16_t screenHeight;
    
  • Define a buffer variable to initialize the display driver of LVGL and prepare a buffer to store pixel data that will be rendered to the screen. The size of this buffer should be around 1/10 of the product of screen pixel values, which can balance the main control performance and the smoothness of screen display. Taking 10 as an example, the display will be smoother.

    static lv_disp_draw_buf_t draw_buf;
    static lv_color_t buf1[ 800 * 480/ 10 ];
    static lv_disp_drv_t disp_drv;  // Declare a static variable of type lv_disp_drv_t, disp_drv, to store configuration information for the display drive.
    
  • Initialize temperature and humidity sensors and an instance of SPI library

    // Initialize DHT20 sensor
    DHT20 dht20;
    SPIClass& spi = SPI;
    

Function

  • Screen refresh function, this code is for the refresh function driven by the display in the LittlevGL (LVGL) graphics library. LVGL is an open-source graphics library for embedded systems, used to create graphical user interfaces (GUIs). This function my_disp_flush is a user-defined callback function used to refresh the content of the graphical interface onto the display device.

    /* Display Refresh */
    void my_disp_flush( lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p )
    {
      uint32_t w = ( area->x2 - area->x1 + 1 );
      uint32_t h = ( area->y2 - area->y1 + 1 );
    
       //lcd.fillScreen(TFT_WHITE);
    #if (LV_COLOR_16_SWAP != 0)
     lcd.pushImageDMA(area->x1, area->y1, w, h,(lgfx::rgb565_t*)&color_p->full);
    #else
      lcd.pushImageDMA(area->x1, area->y1, w, h,(lgfx::rgb565_t*)&color_p->full);//
    #endif
      lv_disp_flush_ready( disp );
    }
    
  • A simple touch input device reading function, which is used to convert touch events into the input device data format required by the LVGL library, and output the coordinate information of touch points through serial communication.

    void my_touchpad_read(lv_indev_drv_t *indev_driver, lv_indev_data_t *data)
    {
      if (touch_has_signal())
      {
        if (touch_touched())
        {
          data->state = LV_INDEV_STATE_PR;
    
          /*Set the coordinates*/
          data->point.x = touch_last_x;
          data->point.y = touch_last_y;
          Serial.print( "Data x :" );
          Serial.println( touch_last_x );
    
          Serial.print( "Data y :" );
          Serial.println( touch_last_y );
        }
        else if (touch_released())
        {
          data->state = LV_INDEV_STATE_REL;
        }
      }
      else
      {
        data->state = LV_INDEV_STATE_REL;
      }
      delay(15);
    }
    

Set Up Part

  void setup()
  {
    Serial.begin( 9600 ); /*Initializing the Serial Port*/

    //IO Port Pins
    pinMode(38, OUTPUT);
    digitalWrite(38, LOW);

    //initialization of DHT20 pins(I2C)
    Wire.begin(19, 20);
    dht20.begin();

    lv_init(); // LVGL initialization

    lcd.begin();
    lcd.fillScreen(TFT_BLACK);
    delay(300);

    
    delay(100);
    touch_init(); // Touch initialization


    /*Obtain the width and height of the screen, and initialize the drawing buffer.*/
    screenWidth = lcd.width();
    screenHeight = lcd.height();

    lv_disp_draw_buf_init(&draw_buf, disp_draw_buf, NULL, screenWidth * screenHeight / 10);
    //  lv_disp_draw_buf_init(&draw_buf, disp_draw_buf, NULL, 480 * 272 / 10);
    /* Initialize the display */
    lv_disp_drv_init(&disp_drv);
    /* Change the following line to your display resolution */
    disp_drv.hor_res = screenWidth;
    disp_drv.ver_res = screenHeight;
    disp_drv.flush_cb = my_disp_flush;
    disp_drv.draw_buf = &draw_buf;
    lv_disp_drv_register(&disp_drv);

    /* Initialize the (dummy) input device driver */
    static lv_indev_drv_t indev_drv;
    lv_indev_drv_init(&indev_drv);
    indev_drv.type = LV_INDEV_TYPE_POINTER;
    indev_drv.read_cb = my_touchpad_read;
    lv_indev_drv_register(&indev_drv);

    /*Initialize the (virtual) input device driver*/
    static lv_indev_drv_t indev_drv;//Define the input device driver structure

    lv_indev_drv_init( &indev_drv );//Initialize the input device driver

    indev_drv.type = LV_INDEV_TYPE_POINTER;//Setting the input device type

    indev_drv.read_cb = my_touchpad_read;//Define the read callback function

    lv_indev_drv_register( &indev_drv );//Registering Input Device Drivers

  //Backlight settings
  #ifdef TFT_BL
    pinMode(TFT_BL, OUTPUT);
    digitalWrite(TFT_BL, HIGH);
  #endif


  // UI initialization
    ui_init();
  lv_timer_handler();

  }

Main Program Part

  void loop()
  {

  /*① obtain temperature and humidity data and store it in a char array. First, use two integer variables a and b to store the obtained temperature and humidity separately*/
    char DHT_buffer[6];
    int a = (int)dht20.getTemperature();
    int b = (int)dht20.getHumidity();

  /*Then store the values in the array and display them on the label label through conversion*/
    snprintf(DHT_buffer, sizeof(DHT_buffer), "%d", a);
    lv_label_set_text(ui_Label1, DHT_buffer);
    snprintf(DHT_buffer, sizeof(DHT_buffer), "%d", b);
    lv_label_set_text(ui_Label2, DHT_buffer);

  /*To determine the value of the LED, in the ui. c program, press the "ON" button to set the LED to 1, and control the LED light to turn on.*/
    if(led == 1)
    digitalWrite(38, HIGH);

  /*In the ui. c program, press the "OFF" button to set the LED to 0, and at this time, control the LED to turn off.*/
    if(led == 0)
    digitalWrite(38, LOW);

    lv_timer_handler(); /* let the GUI do its work, only by executing this function can the entire animation run. */
    delay( 10 );
  }

Upload the Code

  1. After completing the installation of the ESP32 board according to "Get Started with Arduino IDE" and the installation of the library according to "Install Libraries", open the program and connect the ESP32 HMI 5.0-inch to the computer via a USB-C cable.

  2. Select Board: click "Tools" -> "Board" -> "esp32" and select "ESP32S3 Dev Module"

    select-board

  3. Board Setting: Under the "Tools" menu, see "Flash Size" select 4MB(32Mb); "Partition scheme" and select "Huge APP(3MB No OTA/1MB SPIFFS)"; "PSRAM" select "OPI PSRAM"

    board-setting

  4. Select Port

    select-port

  5. Upload the code: click the "Upload" icon to upload the code.

    upload-the-code

  6. After the program is successfully uploaded, connect the DHT20 sensor to the IIC port and the LED to GPIO_D (IO38), the temperature and humidity values will be displayed on the screen. Click the ON button on the screen and the LED will turn on. Click the OFF button and the LED will turn off.

gif2

Example Demo of ESP32 HMI Function


Note:

The library used in this section is in the compressed package of the library downloaded above.

Example1: LED blinking.

Connect the LED to GPIO_D(IO38) port, and upload the following code to the board. The LED will blinking.

#define D_PIN 38

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(D_PIN, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(D_PIN, HIGH);
  delay(500);
  digitalWrite(D_PIN, LOW);
  delay(500);
}

GPIO38-LED

Example2: Play music

Plug the speaker into SPK port. Please check if you have installed the library ESP32-audioI2S(Copy the ESP32-audioI2S-master folder in the libraries downloaded above to the .../arduino/libraries directory). Upload the following code to the board.

#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <FS.h>
#include "Audio.h"
Audio audio;

#define I2S_DOUT      17
#define I2S_BCLK      42
#define I2S_LRC       18

//5.0
#define SD_MOSI 11
#define SD_MISO 13
#define SD_SCK 12
#define SD_CS 10

void setup() {
  // put your setup code here, to run once:
  Serial.begin( 9600 ); /*Initialize the serial port*/
  pinMode(SD_CS, OUTPUT);      digitalWrite(SD_CS, HIGH);
  SPI.begin(SD_SCK, SD_MISO, SD_MOSI);
  SPI.setFrequency(1000000);
  SD.begin(SD_CS);
  audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
  audio.setVolume(21); // 0...21
  audio.connecttoFS(SD, "/123.mp3");
}

void loop() {
  // put your main code here, to run repeatedly:
  audio.loop();
  //audio.stopSong();//close
}

Example3: Initialize SD Card slot

Please install the SD library and FS library. Upload the following code to the board.

#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <FS.h>

//5.0
#define SD_MOSI 11
#define SD_MISO 13
#define SD_SCK 12
#define SD_CS 10
void setup() {
  // put your setup code here, to run once:
  Serial.begin( 9600 ); /*Initialize the serial port*/
  //SD卡
  SPI.begin(SD_SCK, SD_MISO, SD_MOSI);
  delay(100);
  if (SD_init() == 1)
  {
    Serial.println("Card Mount Failed");
  }
  else
    Serial.println("initialize SD Card successfully");
}

void loop() {
  // put your main code here, to run repeatedly:

}

//Initialize the SD Card
int SD_init()
{

  if (!SD.begin(SD_CS))
  {
    Serial.println("Card Mount Failed");
    return 1;
  }
  uint8_t cardType = SD.cardType();

  if (cardType == CARD_NONE)
  {
    Serial.println("No TF card attached");
    return 1;
  }

  uint64_t cardSize = SD.cardSize() / (1024 * 1024);
  Serial.printf("TF Card Size: %lluMB\n", cardSize);
  listDir(SD, "/", 2);

  //  listDir(SD, "/", 0);
  //  createDir(SD, "/mydir");
  //  listDir(SD, "/", 0);
  //  removeDir(SD, "/mydir");
  //  listDir(SD, "/", 2);
  //  writeFile(SD, "/hello.txt", "Hello ");
  //  appendFile(SD, "/hello.txt", "World!\n");
  //  readFile(SD, "/hello.txt");
  //  Serial.printf("Total space: %lluMB\n", SD.totalBytes() / (1024 * 1024));
  //  Serial.printf("Used space: %lluMB\n", SD.usedBytes() / (1024 * 1024));
  //  Serial.println("SD init over.");

  return 0;
}

//Traverse the SD card directory
void listDir(fs::FS & fs, const char *dirname, uint8_t levels)
{
  //  Serial.printf("Listing directory: %s\n", dirname);

  File root = fs.open(dirname);
  if (!root)
  {
    //Serial.println("Failed to open directory");
    return;
  }
  if (!root.isDirectory())
  {
    Serial.println("Not a directory");
    return;
  }

  File file = root.openNextFile();
  //  i = 0;
  while (file)
  {
    if (file.isDirectory())
    {
      Serial.print("  DIR : ");
      Serial.println(file.name());
      if (levels)
      {
        listDir(fs, file.name(), levels - 1);
      }
    }
    else
    {
      Serial.print("FILE: ");
      Serial.print(file.name());
      //      lcd.setCursor(0, 2 * i);
      //      lcd.printf("FILE:%s", file.name());
      Serial.print("SIZE: ");
      Serial.println(file.size());
      //      lcd.setCursor(180, 2 * i);
      //      lcd.printf("SIZE:%d", file.size());
      //      i += 16;
    }

    file = root.openNextFile();
  }
}

Example4: Initialize the touch

Please check if you have install the library GT911(Copy the gt911 folder in the libraries downloaded above to the .../arduino/libraries directory).

And put the touch.h file in the same directory as the program, as shown below 

touch

Upload the following code to the board, and open the serial monitor to check the touch information.

#include "touch.h"

void setup() {
  // put your setup code here, to run once:
  Serial.begin( 9600 ); /*Initialize the serial port*/
  touch_init();
}

void loop() {
  // put your main code here, to run repeatedly:
  if (touch_has_signal())
  {
    if (touch_touched())
    {
      Serial.print( "Data x :" );
      Serial.println( touch_last_x );

      Serial.print( "Data y :" );
      Serial.println( touch_last_y );
    }
  }
}

Example5: Initialize the interact communication of Bluetooth

Please check if you have installed the library BLE(Copy the BLE folder in the libraries downloaded above to the .../arduino/libraries directory). Upload the following code to the board, and use the phone to search the Bluetooth device.

#include "BLEDevice.h"              //BLE drive library
#include "BLEServer.h"              //BLE server library
#include "BLEUtils.h"               //BLE Utility library
#include "BLE2902.h"                //Feature Add Descriptor Library
#include <BLECharacteristic.h>      //BLE Feature function library
BLEAdvertising* pAdvertising = NULL;
BLEServer* pServer = NULL;
BLEService *pService = NULL;
BLECharacteristic* pCharacteristic = NULL;
#define bleServerName "ESP32SPI-BLE"  //BLE Server name
#define SERVICE_UUID "6479571c-2e6d-4b34-abe9-c35116712345"  //Server UUID
#define CHARACTERISTIC_UUID "826f072d-f87c-4ae6-a416-6ffdcaa02d73"


bool connected_state = false;   //Create device connection identifier

class MyServerCallbacks: public BLEServerCallbacks  //Create connection and disconnection calling classes
{
    void onConnect(BLEServer *pServer)//Start connecting function
    {
      connected_state = true;   //Device is connected correctly
    }
    void onDisconnect(BLEServer *pServer)//disconnect function
    {
      connected_state = false;  //Device connection error
    }

};
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  //BLE
  BLEDevice::init(bleServerName);  //Create BLE and set name
  pServer = BLEDevice::createServer();  //Create BLE server
  pServer->setCallbacks(new MyServerCallbacks());  //Set up connection and disconnection calling classes
  pService = pServer->createService(SERVICE_UUID); //Create BLE service

  pCharacteristic = pService->createCharacteristic(  //Create ble feature(Characterristic_UUID)
                      CHARACTERISTIC_UUID,
                      BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY);
  pCharacteristic->setValue("ELECROW");
  //start broadcast
  pAdvertising = BLEDevice::getAdvertising();  //A bleadvertising class pointer padvertising is defined, which points to bledevice:: getadvertising()
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->start();  //Start broadcasting
  pService->start();
  //  pAdvertising->stop();  //Stop broadcasting
  //  pService->stop();      //Stop service
}

void loop() {

}

BLE

Example6: Initialize the WIFI

Please check if you have installed the library WiFi(Copy the WiFi folder in the libraries downloaded above to the .../arduino/libraries directory). Upload the following code to the board.

#include <WiFi.h>

const char *ssid = "elecrow888"; //Change to your SSID
const char *password = "elecrow2014"; //Change to your password
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  WiFi.setAutoReconnect(true);//Set up automatic reconnection
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.println("connecting");
  }
  Serial.println("WiFi is connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
//  WiFi.disconnect();
}

void loop() {

}

Example7: Connect Crowtail-GPS module via UART to Get Location

Connect the Crowtail-GPS to the UART port.

Upload the following code to the board.

//at 9600 bps 8-N-1

#include <SoftwareSerial.h>

SoftwareSerial SoftSerial(44, 43);
unsigned char buffer[256]; // buffer array for data recieve over serial port
int count=0;     // counter for buffer array 
void setup()
{
  SoftSerial.begin(9600);               // the SoftSerial baud rate   
  Serial.begin(9600);             // the Serial port of Arduino baud rate.

}

void loop()
{
  if (SoftSerial.available())              // if date is comming from softwareserial port ==> data is comming from SoftSerial shield
  {
    while(SoftSerial.available())          // reading data into char array 
    {
      buffer[count++]=SoftSerial.read();     // writing data into array
      if(count == 256)break;
  }
    Serial.write(buffer,count);            // if no data transmission ends, write buffer to hardware serial port
    clearBufferArray();              // call clearBufferArray function to clear the storaged data from the array
    count = 0;                       // set counter of while loop to zero


  }
  if (Serial.available())            // if data is available on hardwareserial port ==> data is comming from PC or notebook
    SoftSerial.write(Serial.read());       // write it to the SoftSerial shield
}
void clearBufferArray()              // function to clear buffer array
{
  for (int i=0; i<count;i++)
    { buffer[i]=NULL;}                  // clear all index of array with command NULL
}

GPS