Have you ever learned about "smart display?” Well today, I present the Display Nextion. How does this differentiate from the others? In addition to the graphics controller, it has a microcontroller connected in the Uart TX RX. For an example: When I want the lamp to appear on the screen (same as the image shown below), I will not need to draw this entire lamp, as I will simply record the drawing on the display and print its ID. This differs from traditional displays, in which I have to execute the desired drawings, pixel by pixel. Therefore, in this "smart display,” all graphic processing is done by Nextion itself. The microcontroller, an Arduino Uno in this case, just keeps sending the code. Important information regarding this is that Display Nextion uses STM32.
In this video today, we will learn about the IDE Nextion Editor, create a simple example without a microcontroller, and simulate in the Nextion simulator. In addition, we’ll create an example using a microcontroller running with Nextion.
In our project, we have a DHT22 sensor for reading values, an Arduino Uno, as well as the Display Nextion, which only has 4 wires: positive, negative, TX, and RX. This model also has an SD card slot, which also serves to boot and load the Bitmap images to be displayed on the screen. In our assembly, which displays temperature and humidity information on the display, we also have an LED.
You can download the Nextion Editor through the link below:
download: Nextion Editor
In the image, we have an overview of the Nextion Editor, exposing the Main Menu, Components, Image and Font Libraries, Exposure Area, Compile Output Area, Event Area, Page Area, and Attribute Edit Area.
• File (create / open / save /import project, open construction folder)
• Tools (source generator)
• Setting (settings, reset layout)
• Compile (compile project)
• Debug (opens the simulator to test the program) - * No physical Nextion is required to test the project.
• Upload (opens a window for uploading the project to Nextion) - * can take a long time
• Device (opens the Nextion model and orientation settings)
• ID (display / hide component IDs in the exposure area)
In the event area, we can configure the events of the components (touch press, touch release ...) and also add codes to execute when the event occurs.
The image shows that, when the release event occurs, "page 1" will be called, which means page 1 will then be displayed on the screen. Note that the number 1 refers to the destination page ID.
When clicking on the Debug menu, a window to simulate our project will open. We can use the microcontroller with the code and this simulator, for example. We do not necessarily need a physical Nextion device.
1. Area for sending commands to the simulator
2. Simulator return area
3. Control area of the microcontroller
4. Command input mode (keyboard Input or User MCU Input)
5. Command destination (Simulator, Nextion, Simulator and Nextion)
To write the project to Nextion, we can do it in two ways:
1. Upload Menu
With Port: either you choose the COM port of your Nextion, or leave it in Auto search, so that the program is in charge of testing everything and at different speeds.
Baud Rate: Choose the upload speed. If Com Port has been Auto search, the program will try all available speeds until you find the correct one.
2. Upload via SD Card
Go to File menu >> Open build folder
Copy the file from your project (.tft extension), and then paste it into your SD Card that you will use in Nextion.
Note 1: In SD, there should only be the file of your project.
Note 2: After copying the file inside the SD Card, place it in the Nextion. When fed, it will identify the file and then "upload" it to its memory. Once this is done, wait for the success message and then remove the SD Card.
The project file can be downloaded through the link below:
download: grafico_dht_light.HMI
Just open it by Nextion Editor to view it.
Add library "ITEADLIB_Arduino_Nextion-master".
Access the link and download the library.
Unzip the file and paste it into the libraries folder of the Arduino IDE.
C: / Program Files (x86) / Arduino / libraries
Before we start coding through the Arduino IDE, we should make a small change to the NexConfig.h file in the library.
* Discuss the serial debug
#define DEBUG_SERIAL_ENABLE -> // # define DEBUG_SERIAL_ENABLE
* Modify the Serial2 setting as the default Serial
#define nexSerial Serial2 -> #define nexSerial Serial
We will include the libraries for communication with the Nextion display and for communication with the DHT22. We also define the variables that store the data of DHT22 and for control of the Led, among others.
#include "Nextion.h" //biblioteca para comunicação com o display NEXTION
#include <SimpleDHT.h> //biblioteca para comunicação com o DHT22 SimpleDHT22 dht22; static int pinDHT22 = 7; //pino que ligamos o DATA do DHT22 no arduino //variáveis que armazenam os dados do DHT22 float temperature = 0; float humidity = 0; uint8_t pinLED = 3; //pino que ligamos o LED no arduino bool isPage0 = true; //variável de controle para saber se é a página ZERO que está em tela bool isLedOn = false; //variável de controle para saber se o LED está aceso char buffer[100] = {0}; //buffer para armazenar dados string //variáveis de controle de tempo, para funcionar como um cronômetro long previousMillis = 0; const int maxTime = 1000;
We declare the Nextion objects here. We also have the array; in which we declare Nextion objects that will have touch event interaction.
/* DECLARAÇÕES DOS OBJETOS DO NEXTION: [pageID, componentID, componentName] */
NexProgressBar progTemp = NexProgressBar(0, 1, "prog_temp"); //Progress Bar temperatura NexProgressBar progHumid = NexProgressBar(0, 16, "prog_humid"); //Progress Bar umidade NexButton btnNext = NexButton(0, 3, "btn_next"); //botão da página 0 NexText txtTemp = NexText(0, 2, "txt_temp"); //texto com o valor da temperatura NexText txtHumid = NexText(0, 5, "txt_humid"); //texto com o valor da umidade NexWaveform waveform = NexWaveform(0, 6, "waveform"); //componente do gráfico de temperatura e umidade NexDSButton btnLight = NexDSButton(1, 1, "btn_light"); //botão de duplo estado para controlar o LED NexSlider slider = NexSlider(1, 2, "slider_pwm"); //slider que controlará o PWM do LED NexText statusPWM = NexText(1, 4, "status_pwm"); //texto com o status do pwm NexVariable valueSlider = NexVariable(1, 5,"valueSlider"); //(objeto do nextion) variável que guarda o valor do slider NexButton btnBack = NexButton(1, 3, "btn_back"); //botão da página 1 NexPage page0 = NexPage(0, 0, "page0"); NexPage page1 = NexPage(1, 0, "page1"); //Nesse array, declaramos os objetos Nextion que terão interação de eventos touch NexTouch *nex_listen_list[] = { &btnLight, &slider, &valueSlider, &btnNext, &btnBack, NULL };
In Setup, we initialize communication with Nextion. In Loop, we work as a listener for the press and release events of the objects used in the display.
void setup() {
Serial.begin(9600); pinMode(pinLED, OUTPUT); nexInit(); //inicializa a comunicação com o nextion btnNext.attachPop(btnNextPopCallback, &btnNext); //callback para o evento de release do botão btnNext btnBack.attachPop(btnBackPopCallback, &btnBack); //callback para o evento de release do botão btnBack slider.attachPop(sliderPopCallback); //callback para o evento de release do slider btnLight.attachPop(btnLightPopCallback, &btnLight); //callback para o evento de release do botão de dois estados (btnLight) } void loop() { //essa função trabalha como um listener para os eventos de press e release dos objetos utilizados no NEXTION nexLoop(nex_listen_list); //verifica se a página atual é a ZERO(inicial) //caso seja, verifica se o tempo passado entra a última passagem e a atual, foi de 1 segundo //e então chama a atualização do gráfico de temperatura e umidade if(isPage0) { if(millis() - previousMillis >= maxTime) { previousMillis = millis(); updateDHTInfo(); //pega os valores do DHT22 e então manda para o NEXTION } } }
This function retrieves the temperature and humidity values of the DHT22 and, through the objects in the Nextion, the information.
//função que recupera os valores de temperatura e umidade do DHT22
//e através dos objetos do NEXTION seta as informações void updateDHTInfo() { int status = dht22.read2(pinDHT22, &temperature, &humidity, NULL);//faz a leitura dos dados do DHT22 //se conseguiu ler os dados corretamente if (status == SimpleDHTErrSuccess) { progTemp.setValue(temperature); //progress bar da temperatura memset(buffer, 0, sizeof(buffer)); itoa(temperature, buffer, 10); txtTemp.setText(buffer); //texto que indica a temperatura progHumid.setValue(humidity); //progress bar da umidade memset(buffer, 0, sizeof(buffer)); itoa(humidity, buffer, 10); txtHumid.setText(buffer); //texto que indica a umidade waveform.addValue(0, temperature); //envia o valor da temperatura para o gráfico waveform.addValue(1, humidity); //envia o valor da umidade para o gráfico } }
SLIDER callback: When the release event happens, this function is called.
//callback do SLIDER, quando o evento de release acontecer essa função é chamada
void sliderPopCallback(void *ptr) { //se o LED está ligado, busca o valor da variável que guarda o valor do slider e então seta o PWM do LED if(isLedOn) { uint32_t number = 0; valueSlider.getValue(&number); //pega o valor atual da variável nextion int value = map(number, 0,100,0,255); analogWrite(pinLED, value); memset(buffer, 0, sizeof(buffer)); itoa(value, buffer, 10); statusPWM.setText(buffer); } } //callback do botão btnNext void btnNextPopCallback(void *ptr) { page1.show(); isPage0 = false; sliderPopCallback(ptr); //chama o callback do slider para reconfigura-lo } //callback do botão btnBack void btnBackPopCallback(void *ptr) { page0.show(); isPage0 = true; }
Already here, we have the Callback of the two state button.
/* Callback do botão de dois estados */
void btnLightPopCallback(void *ptr) { uint32_t dual_state; /* recupera o valor do estado de botão de dois estados */ btnLight.getValue(&dual_state); if(dual_state) { isLedOn = true; sliderPopCallback(ptr); } else { statusPWM.setText("DESLIGADO"); digitalWrite(pinLED, LOW); isLedOn = false; } }