ESP32 HMI 3.5-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.
Hardware Preparation¶
CrowPanel ESP32 3.5'' HMI | Crowtail-DHT20 | Crowtail-LED |
---|---|---|
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.
Please click 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.
-
Open the SquareLine Studio and create a project. Select "Arduino"->"Arduino with TFT_eSPI".
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 320*240, set the color depth to 16bit, and keep other default settings. After setting, click CREATE to create the project.
- 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.
-
After creation, enter the following interface with a blank background.
-
In the "Assets" area, click "ADD FILE TO ASSETS" to add custom images or icons.
Please click to download the custom images used in this tutorial.
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.
-
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.
-
Add Label widget to display temperature and humidity.
Click "Label" in the "Widgets" area, and "Label1" will be added to the current Screen.
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.
You can set the font color and other attributes in STYLE SETTING→STYLE(MAIN).
Add a Label2 to display the humidity value in the same way. You can also directly right-click the Label1 to duplicate it.
Then set different positions for the Label2.
Modify the text content to display a default value.
-
Add Button widget to control the LED.
Click "Button" in the "Widgets" area, and "Button1" will be added to the current Screen.
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.
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.
In the same way, duplicate a Button widget. And drag it to the corresponding position to modify different background image.
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.
Make the same settings for the "OFF" button.
-
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".
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.
Complete the event. Here I choose to change the screen, and the screen to be switched is Screen1.
Add event to Button2 (OFF) in the same way.
-
Export UI files.
Click "File" -> "Project Settings" and make settings for the exported file.
Set the export path of the file (set the path according to your own file).
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.
Export UI files. The exported files will be in the path we set earlier.
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 to download the main program(and the expert UI is included).
-
Modify the button event code.
Open the main program. And all the UI file in the same folder will open too.
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.
Then find "FUNCTION" in the ui.c file. Here is the corresponding code generated when we add events in SquareLine.
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.
- When button 2 (OFF button) is pressed, set the LED value to 0.
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.
Install Libraries¶
In this project, we will use the following libraries:
#include <lvgl.h>
#include <TFT_eSPI.h> //screen driver library
#include <Arduino.h>
#include <Crowbits_DHT20.h> //Temperature and humidity sensor library
//UI
#include "ui.h"
#include <Arduino.h>
: contains the Arduino core library, providing commonly used functions and data types.#include <lvgl.h>
and#include <TFT_eSPI.h>
: are libraries for graphical interfaces, used for display control and drawing.#include "ui.h"
: is a custom header file that contain UI-related functions or definitions.#include <Crowbits_DHT20.h>
: to read data from the DHT20 temperature and humidity sensor.
Please click to download the libraries we modified.
Then click "File" -> "Preferences" -> "Setting" to check the sketchbook location. Place the libraries downloaded to the sketchbook location.
Tips:
-
If you install the TFT_eSPI libraries by Library Manager, you need to modify User_Setup.h file accordding to the hardware specification.(Please refer to the library provided)
-
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)
Code Explanation¶
Basic Definition
/*Define an variable to set the state of the led*/
int led;
//Screen resolution definition, the resolution of 3.5 inches is 480*320
/*Changing the screen resolution*/
static const uint16_t screenWidth = 480;
static const uint16_t screenHeight = 320;
/*Define buffer variables to initialize the LVGL display driver and prepare a buffer to store pixel data that will be rendered to the screen. The size of this buffer is preferably about 1/10 of the product of screen pixel values, which can take into account both the main control performance and the smoothness of the screen display. Taking 8 as an example here, the display will be smoother.*/
static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf1[ screenWidth * screenHeight / 8 ];
// Initialize DHT20 sensor
Crowbits_DHT20 dht20;
TFT_eSPI lcd = TFT_eSPI(); /* TFT Example */
Function
/* Display Refresh */
/*The function of this code is to use the LCD object to perform the display refresh operation based on the given refresh area and color data, and notify the display driver to complete the refresh operation through the LVGL library. w * h indicates the number of color data, and true indicates that the color data written is 16 bits.*/
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.startWrite();
lcd.setAddrWindow( area->x1, area->y1, w, h );
lcd.pushColors( ( uint16_t * )&color_p->full, w * h, true );
lcd.endWrite();
lv_disp_flush_ready( disp );
}
/*Read Touchpad*/
/*The function of this code is to read the input status and coordinate information of the touch screen and store the results in the specified data structure. If the touch screen is touched, the coordinate information of the touch screen will also be printed to the serial monitor.
The number 600 represents the timeout in milliseconds, which is the maximum amount of time to wait while waiting for touch screen input.
When the lcd.getTouch function is called, it will try to read the input status and coordinate information of the touch screen. If the input is successfully read within 600 milliseconds, the function will return true, indicating that the touch screen was touched. If no input is read within 600 milliseconds, the function will return false, indicating that the touch screen was not touched.
This timeout can be adjusted as needed. A shorter timeout may prevent all coordinate points from being accurately captured when swiping quickly on the touch screen, while a longer timeout may increase response time. This timeout value can be adjusted appropriately according to specific application scenarios and requirements.*/
uint16_t touchX, touchY;
void my_touchpad_read( lv_indev_drv_t * indev_driver, lv_indev_data_t * data )
{
bool touched = lcd.getTouch( &touchX, &touchY, 600);
if ( !touched )
{
data->state = LV_INDEV_STATE_REL;
}
else
{
data->state = LV_INDEV_STATE_PR;
/*Setting the coordinates*/
data->point.x = touchX;
data->point.y = touchY;
Serial.print( "Data x " );
Serial.println( touchX );
Serial.print( "Data y " );
Serial.println( touchY );
}
}
Set Up Part
//Serial port initialization
Serial.begin( 115200 ); /*Initializing the Serial Port*/
Serial2.begin( 9600 ); /*Initialize Serial Port 2*/
//LED IO Pins
pinMode(25, OUTPUT);
digitalWrite(25, LOW);
//DHT20 pin setting and initialization. DHT20 use the I2C interface
Wire.begin(22, 21);
dht20.begin();
//LVGL initialization
lv_init();
lcd.begin();
lcd.fillScreen(TFT_BLACK);
delay(300);
//Backlight Pins
pinMode(27, OUTPUT);
digitalWrite(27, HIGH);
lcd.setRotation(1);
/*Screen display initialization, initialize the drawing buffer by calling the lv_disp_draw_buf_init function. This function accepts three parameters: &draw_buf is a pointer to the lv_disp_draw_buf_t structure, buf1 is the buffer used to store pixel data, and the last parameter is NULL to indicate that no additional buffer is used. The buffer size is calculated as screenWidth * screenHeight / 8 and associated with the draw buffer structure.*/
lv_disp_draw_buf_init( &draw_buf, buf1, NULL, screenWidth * screenHeight / 8 );
/*Initializing the display*/
static lv_disp_drv_t disp_drv;/*A static variable disp_drv of type lv_disp_drv_t is defined, which is used to store related configuration and information of the display device driver*/
lv_disp_drv_init( &disp_drv );
/*Change the following line to 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 (virtual) input device driver. The function of this code is to initialize a virtual input device driver and associate it with the LVGL framework in order to handle the interaction of the input device. Among them, by setting the input device type, defining the read callback function and other steps, the necessary configuration and functions are provided for the input device driver*/
/*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
//UI initialization
ui_init();
}
Main Program Part
void loop()
{
/*Obtain the temperature and humidity data and use a char array to store it. Use two integer variables a and b to store the obtained temperature and humidity*/
char DHT_buffer[6];
int a = (int)dht20.getTemperature();
int b = (int)dht20.getHumidity();
//Store the value in an array through conversion and display it on the label
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);
/*Judge 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(25, HIGH);
//*In the ui.c program, press the "OFF" button to set the LED to 0. At this time, the LED light is controlled to be turned off*/
if(led == 0)
digitalWrite(25, LOW);
lv_timer_handler(); /* let the GUI do its work */
delay( 10 );
}
The Complete Code
#include <lvgl.h>
#include <TFT_eSPI.h>
#include <demos/lv_demos.h>
#include<Arduino.h>
#include <Crowbits_DHT20.h>
//UI
#include "ui.h"
int led;
/*Changing the screen resolution*/
static const uint16_t screenWidth = 480;
static const uint16_t screenHeight = 320;
static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf1[ screenWidth * screenHeight / 8 ];
TFT_eSPI lcd = TFT_eSPI(); /* TFT Example */
// Initialize DHT20 sensor
Crowbits_DHT20 dht20;
uint16_t calData[5] = { 353, 3568, 269, 3491, 7 };
/* 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.startWrite();
lcd.setAddrWindow( area->x1, area->y1, w, h );
lcd.pushColors( ( uint16_t * )&color_p->full, w * h, true );
lcd.endWrite();
lv_disp_flush_ready( disp );
}
uint16_t touchX, touchY;
/*Read Touchpad*/
void my_touchpad_read( lv_indev_drv_t * indev_driver, lv_indev_data_t * data )
{
bool touched = lcd.getTouch( &touchX, &touchY, 600);
if ( !touched )
{
data->state = LV_INDEV_STATE_REL;
}
else
{
data->state = LV_INDEV_STATE_PR;
/*Setting the coordinates*/
data->point.x = touchX;
data->point.y = touchY;
Serial.print( "Data x " );
Serial.println( touchX );
Serial.print( "Data y " );
Serial.println( touchY );
}
}
void setup()
{
Serial.begin( 115200 ); /*Initializing the Serial Port*/
Serial2.begin( 9600 ); /*Initialize Serial Port 2*/
//IO Port Pins
pinMode(25, OUTPUT);
digitalWrite(25, HIGH);
Wire.begin(22, 21);
dht20.begin();
lv_init();
lcd.begin();
lcd.fillScreen(TFT_BLACK);
delay(300);
lcd.setTouch( calData );
//Backlight Pins
pinMode(27, OUTPUT);
digitalWrite(27, HIGH);
lcd.setRotation(1);
lv_disp_draw_buf_init( &draw_buf, buf1, NULL, screenWidth * screenHeight / 8 );
/*Initializing the display*/
static lv_disp_drv_t disp_drv;
lv_disp_drv_init( &disp_drv );
/*Change the following line to 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 (virtual) 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 );
ui_init();
}
void loop()
{
Serial.print(led);
char DHT_buffer[6];
int a = (int)dht20.getTemperature();
int b = (int)dht20.getHumidity();
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);
if(led == 1)
digitalWrite(25, HIGH);
if(led == 0)
digitalWrite(25, LOW);
lv_timer_handler(); /* let the GUI do its work */
delay( 10 );
}
Upload the Code¶
-
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 3.5-inch to the computer via a USB-C cable.
-
Select Board: click "Tools" -> "Board" -> "esp32" and select "ESP32-WROOM-DA Module"(select ESP32 Dev Module also be good)
-
Select Port
-
Upload the code
-
After the program is successfully uploaded, connect the DHT20 sensor to the IIC port and the LED to GPIO_D, 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.
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(IO25) port, and upload the following code to the board. The LED will blinking.
#define D_PIN 25
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);
}
Example2: Control an external OLED screen through I2C.¶
Connect the OLED screen to IIC port.
Install the U8g2 library(Copy the U8g2 folder in the libraries downloaded above to the .../arduino/libraries directory). Then upload the following code to the board.
#include <U8g2lib.h>
#include <Wire.h>
#define I2C_SDA 22
#define I2C_SCL 21
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /*clock=*/I2C_SCL, /*data=*/I2C_SDA, /*reset=*/U8X8_PIN_NONE);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
//OLED
u8g2.begin();
u8g2.enableUTF8Print(); // enable UTF8 support for the Arduino print() function
u8g2.setFont(u8g2_font_ncenB14_tr);
u8g2.setFontDirection(0);
for (int i = 128; i > -78; i -= 20)
{
u8g2.firstPage();
do {
u8g2.drawStr(i, 25, "ELECROW");
delay(2);
} while ( u8g2.nextPage() );
}
}
void loop() {
}
Example3: Play music¶
Plug the speaker into SPK port. Please check if you have installed the library XT_DAC_Audio(Copy the XT_DAC_Audio folder in the libraries downloaded above to the .../arduino/libraries directory). Upload the following code to the board.
#include "MusicDefinitions.h"
#include "SoundData.h"
#include "XT_DAC_Audio.h"
//SPEAK
// Data for the melody. Note followed by optional change in playing length in 1/4 beats. See documentation for more details
int8_t PROGMEM TwinkleTwinkle[] = {
NOTE_C5, NOTE_C5, NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5, NOTE_G5, BEAT_2,
NOTE_F5, NOTE_F5, NOTE_E5, NOTE_E5, NOTE_D5, NOTE_D5, NOTE_C5, BEAT_2,
NOTE_G5, NOTE_G5, NOTE_F5, NOTE_F5, NOTE_E5, NOTE_E5, NOTE_D5, BEAT_2,
NOTE_G5, NOTE_G5, NOTE_F5, NOTE_F5, NOTE_E5, NOTE_E5, NOTE_D5, BEAT_2,
NOTE_C5, NOTE_C5, NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5, NOTE_G5, BEAT_2,
NOTE_F5, NOTE_F5, NOTE_E5, NOTE_E5, NOTE_D5, NOTE_D5, NOTE_C5, BEAT_4,
NOTE_SILENCE, BEAT_5, SCORE_END
};
XT_DAC_Audio_Class DacAudio(26, 0); // Create the main player class object. Use GPIO 25, one of the 2 DAC pins and timer 0
XT_Wav_Class ForceWithYou(Force); // create WAV object and pass in the WAV data
XT_MusicScore_Class Music(TwinkleTwinkle, TEMPO_ALLEGRO, INSTRUMENT_PIANO); // The music score object, pass in the Music data
XT_Sequence_Class Sequence; // The sequence object, you add your sounds above to this object (see setup below)
void setup() {
// put your setup code here, to run once:
Serial.begin( 9600 );
Sequence.AddPlayItem(&ForceWithYou); // Add the first sound item, this will play first
Sequence.AddPlayItem(&Music); // Add the music score, this will play after the first item
DacAudio.Play(&Sequence); // Play the sequence, will play just the once and then stop
}
void loop() {
// put your main code here, to run repeatedly:
DacAudio.FillBuffer();//Play
// DacAudio.StopAllSounds(); //Stop Playing
}
Example4: Initialize SD Card slot¶
Please check if you have installed the SD library(Copy the SD 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>
#define SD_MOSI 23
#define SD_MISO 19
#define SD_SCK 18
#define SD_CS 5
void setup() {
// put your setup code here, to run once:
Serial.begin( 9600 ); /*初始化串口*/
//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:
}
//SD卡初始化
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;
}
//遍历SD卡目录
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();
}
}
Example5: Initialize the touch¶
Please check if you have install the library TFT_eSPI(Copy the TFT_eSPI folder in the libraries downloaded above to the .../arduino/libraries directory). Upload the following code to the board, and open the serial monitor to check the touch information.
#include <TFT_eSPI.h>
TFT_eSPI lcd = TFT_eSPI();
uint16_t touchX, touchY;
uint16_t calData[5] = { 353, 3568, 269, 3491, 7 };
void setup() {
// put your setup code here, to run once:
Serial.begin( 9600 ); /*Initialize serial port*/
//LCD Initialize
lcd.begin();
lcd.setRotation(1); /* Rotate */
//Calibration mode. One is four-corner positioning, and the other is direct positioning by directly inputting analog values.
//Screen calibration
// touch_calibrate();
lcd.setTouch(calData);
/*Initialization*/
}
void loop() {
// put your main code here, to run repeatedly:
bool touched = lcd.getTouch( &touchX, &touchY, 600);
if ( touched )
{
Serial.print( "Data x " );
Serial.println( touchX );
Serial.print( "Data y " );
Serial.println( touchY );
}
}
void touch_calibrate()
{
uint16_t calData[5];
uint8_t calDataOK = 0;
Serial.println("Touch-screen calibration");
//calibration
Serial.println("Please touch the corners as directed");
// lv_timer_handler();
lcd.calibrateTouch(calData, TFT_MAGENTA, TFT_BLACK, 15);
Serial.println("calibrateTouch(calData, TFT_MAGENTA, TFT_BLACK, 15)");
Serial.println(); Serial.println();
Serial.println("//Use this calibration code in setup():");
Serial.print("uint16_t calData[5] = ");
Serial.print("{ ");
for (uint8_t i = 0; i < 5; i++)
{
Serial.print(calData[i]);
if (i < 4) Serial.print(", ");
}
Serial.println(" };");
Serial.print(" tft.setTouch(calData);");
Serial.println(); Serial.println();
}
Example6: 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() {
}
Example7: Initialize the WIFI¶
Please check if you have installed the bilrary 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() {
}
Example8: Connect Crowtail-GPS module via UART to Get Location¶
//at 9600 bps 8-N-1
#include <SoftwareSerial.h>
SoftwareSerial SoftSerial(6, 7);
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
}