Nextion display with arduino
Содержание:
- Wiring Nextion Display to the Arduino
- Compiling and Uploading code to the Nextion Display
- Creating and Navigating to a New Page
- Step 27: CALLBACKS
- Step 24: Code for the Microcontroller
- Элементы платы
- Adding Fonts
- Downloading Nextion Libraries
- Step 16: Upload
- Step 25: Setup and Loop
- Introducing the Nextion Display
- Project Overview
- Adding text labels, sliders and buttons
- Демонстрационный режим
- Штатный режим
- Project Resources
- How to interface Nextion HMI with Arduino Mega2560 and learn how to use Nextion editor and program tags in Arduino
- Wrapping up
- Getting a Nextion Display
- Receiving a Message and detecting a Button
- Nextion Editor Example Code
- Nextion Editor General Overview
- Adding a Background Image
- Step 26: UpdateDHTInfo
- Исходный код
- Introduction: Display Nextion With Arduino Uno
- Характеристики
Wiring Nextion Display to the Arduino
Connecting the Nextion display to the Arduino is very straightforward. You just need to make four connections: GND, RX, TX, and +5V. These pins are labeled at the back of your display, as shown in the figure below.
Nextion display pinout
Here’s how you should wire the Nextion display:
Nextion | Wiring to |
GND | GND |
RX | Arduino pin 1 (TX) |
TX | Arduino pin 0 (RX) |
VCC | 5V |
You can power up the Nextion display directly from the Arduino 5V pin, but it is not recommended. Working with insufficient power supply may damage the display. So, you should use an external power source. You should use a 5V/1A power adaptor with a micro USB cable. Along with your Nextion display, you’ll also receive a USB to 2 pin connector, useful to connect the power adaptor to the display.
Here’s the schematic you need to follow to wire the display to the Arduino.
Compiling and Uploading code to the Nextion Display
To upload your project to the Next display, follow the next steps:
1. Click the Compile button in the main menu;
2. Insert the microSD card on your computer;
3. Go to File > Open Build Folder;
4. Copy the .TFT file corresponding to the file you’re currently working;
5. Paste that file in the microSD card (note: the microSD card should have been previously formatted as FAT32);
6. Insert the microSD card on the Nextion display and plug power.
7. You should see a message on the display saying the code is being uploaded.
8. When it is ready, it should display the following message:
9. Remove the power from the Nextion display, and unplug the microSD card.
10. Apply power again, and you should see the interface you’ve built in the Nextion Editor on your Nextion display.
Adding more pages to your GUI is really simple. On the top right corner, in the Page area, select the Add button to add a new page. A new page will be created. In this case, page1.
To navigate to one page to another, we’ve added a button in each page, at the bottom right corner – in this case it is called bNext.
To make this button redirect to page1, you need to add the following to the Event window, in the user code section (as highlighted in red below).
If you want to redirect to another page, you just have to modify the User Code with the number of the page.
Our second page will display data from the DHT11 temperature and humidity sensor. We have several labels to hold the temperature in Celsius, the temperature in Fahrenheit, and the humidity. We also added a progress bar to display the humidity and an UPDATE button to refresh the readings. The bBack button redirects to page0.
Notice that we have labels to hold the units like “ºC”, “ºF” and “%”, and empty labels that will be filled with the readings when we have our Arduino code running.
Step 27: CALLBACKS
SLIDER callback: When the release event happens, this function is called.
//callback do SLIDER, quando o evento de release acontecer essa função é chamadavoid 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;
}
}
Step 24: Code for the Microcontroller
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 = {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: */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
};
Элементы платы
Экран с тачскрином
За отображение информации отвечает ЖК-матрица TFT IPS диагональю 7 дюймов и разрешением 800×480 пикселей с глубиной 65536 цветов. В дисплей встроена LED-подсветка, яркость которой регулируется от 0 до 300 кд/м2 с шагом 1%.
Контроллер дисплея AI HMI
Сердцем дисплея является контроллер AI HMI с тактовой частотой до 200 МГц, который является посредником между ЖК-матрицей экрана и управляющей платой. Контролер обладает блоками памяти EEPROM на 1 КБ для хранения пользовательских данных при отключенном питании и SRAM на 512 КБ для хранения переменных во время исполнения программы.
Flash-память W29N01HVXINA
За хранение прошивки, пользовательских картинок, аудио и видео данных отвечает внешняя Flash-память W29N01HVSINA на 128 МБ.
Чип RTC AT8563
Микросхема AT8563 — это часы реального времени, которые подскажут текущее время и дату. А при отключённом питании, чип продолжит отчитывать время и поможет зафиксировать важные события.
Для работы часов реального времени при отключённом питании, установите элемент питания формфактора CR1220 / CR1225 в батарейный отсек на плате дисплея.
Слот для батарейки
На плате модуля расположен батарейный отсек BH500 для элемента питания CR1220 / CR1225, которая обеспечивает питание .
Преобразователь логических уровней SN74HC86
Преобразователь логических уровней на микросхеме 74HC86 необходим для сопряжения экрана с разными напряжениями цифровых сигналов от 3,3 до 5 вольт. Другими словами дисплейный модуль совместим как с 3,3 вольтовыми платами, например Espruino, так и с 5 вольтовыми — например Arduino Uno.
Разъём питания и данных
Дисплей подключается к управляющей электронике через разъём JST XH-3 Male (папа). Для коммуникации используйте кабель с разъёмом JST XH-3 Female с четырьмя проводниками на конце:
- Земля (G) — чёрный провод. Соедините с землёй микроконтроллера.
- Сигнальный (RX) — жёлтый провод, цифровой вход дисплейного модуля. Используется для приёма данных из микроконтроллера. Подключите к пину TX микроконтроллера.
- Сигнальный (TX) — синий провод, цифровой выход дисплейного модуля. Используется для передачи данных в микроконтроллер. Подключите к пину RX микроконтроллера.
- Питание (V) — красный провод. Соедините с питанием микроконтроллера.
Слот microSD карты
Дисплейный модуль поддерживает прошивку через SD-карту. Скопируйте файл проекта из программы Nextion Editor в корень microSD-шки, вставьте её в картридер и включите дисплей — прошивка начнётся автоматически. Подробности читайте в нашей документации на «Nextion Editor».
Разъём внешних GPIO
Дисплей является самодостаточным устройством и обладает собственными GPIO-пинами. К контактам можно подключать простые модули и датчики: например кнопки, светодиоды или реле.
№ Вывода | Имя сигнала | Описание |
---|---|---|
1 | GND | Земля |
2 | IO_0 | Цифровой пин GPIO0 |
3 | IO_1 | Цифровой пин GPIO1 |
4 | IO_2 | Цифровой пин GPIO2 |
5 | IO_3 | Цифровой пин GPIO3 |
6 | IO_4 | Цифровой пин GPIO4 |
7 | IO_5 | Цифровой пин GPIO5 |
8 | IO_6 | Цифровой пин GPIO6 с поддержкой ШИМ |
9 | IO_7 | Цифровой пин GPIO7 с поддержкой ШИМ |
10 | +5V | Питание дисплея |
Для коммуникации используйте дополнительные модули от Nextion.
Аудиовыход
Дисплей позволяет выводить аудиозвук: для этого предусмотрен разъём JST SH-2 Male (папа) для подключения наушников или внешней акустики. Мощность выходного сигнала 0,5 Вт. В качестве ответной части подойдёт коннектор JST SH-2 Female (мама) совместно с динамиком HSP3040A.
Adding Fonts
To write text on the display, you need to generate a font in the Nextion Editor. Go to Tools > Font Generator. A new window should open.
Here you can select the font height, type, spacing and if you want it to be bold or not. Give it a name and click the Generate font button. After that, save the .zi file and add the generator font by clicking yes.
The font will be added to the Fonts library at the left bottom corner and it will be given an index. As this is your first font, it will have the index 0.
Note: At the time of writing this instructions there is an issue with font types. Whatever font type you chose, it will always look the same. Still, you can edit the font size and if it is bold or not.
Downloading Nextion Libraries
Before getting started, you also need to install the Nextion libraries for Arduino IDE. Follow the next steps to install the library:
- Click here to download the Nextion library for Arduino – ITEADLIB_Arduino_Nextion. You should have a .zip folder in your Downloads folder.
- Unzip the .zip folder and you should get ITEADLIB-Arduino-Nextion-master folder.
- Rename your folder from
ITEADLIB_Arduino_Nextion-masterto ITEADLIB_Arduino_Nextion. - Move the ITEADLIB_Arduino_Nextion folder to your Arduino IDE installation libraries folder.
- Finally, re-open your Arduino IDE.
Configure Library for Arduino UNO
This library is configured for Arduino MEGA2560 by default. To make it work for Arduino Uno, you need to do the following:
1. Open the ITEADLIB_Arduino_Nextion folder
2. There should be a NexConfig.h file – open that file.
3. Comment line 27, so that it stays as follows:
//#define DEBUG_SERIAL_ENABLE
4. Comment line 32:
//#define dbSerial Serial
5. Change line 37, so that you have the following:
#define nexSerial Serial
6. Save the NexConfig.h file.
7. Here’s the final result:
Now, you are ready to start experimenting with the Nextion display with Arduino UNO.
Step 16: Upload
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.
Step 25: Setup and Loop
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
}
}
}
Introducing the Nextion Display
Nextion is a Human Machine Interface (HMI) solution. Nextion displays are resistive touchscreens that makes it easy to build a Graphical User Interface (GUI). It is a great solution to monitor and control processes, being mainly applied to IoT applications.
There are several Nextion display modules, with sizes ranging from 2.4” to 7”.
The Nextion has a built-in ARM microcontroller that controls the display, for example it takes care of generating the buttons, creating text, store images or change the background. The Nextion communicates with any microcontroller using serial communication at a 9600 baud rate.
So, it works with any board that has serial capabilities like Arduino, Raspberry Pi, ESP8266, ESP32, and so on.
To design the GUI, you use the Nextion Editor, in which you can add buttons, gauges, progress bars, text labels, and more to the user interface in an easy way. We have the 2.8” Nextion display basic model, that is shown in the following figure.
Project Overview
The best way to get familiar with a new software and a new device is to make a project example. Here we’re going to create a user interface in the Nextion display to control the Arduino pins, and display data.
Here’s the features of the application we’re going to build:
- The user interface has two pages: one controls two LEDs connected to the Arduino pins, and the other shows data gathered from the DHT11 temperature and humidity sensor;
- The first page has one button to turn an LED on, another button to turn an LED off, a label showing the LED current state;
- This first page also has a slider to control the brightness of another LED;
- The second page shows the current temperature in a text label, and the current humidity in a progress bar;
- This page has an update button to update to the readings.
At this moment, you can start adding components to the display area. For our project, drag three buttons, two labels and one slider, as shown in the figure below. Edit their looks as you like.
All components have an attribute called objname. This is the name of the component. Give good names to your components because you’ll need them later for the Arduino code. Also note that each component has one id number that is unique to that component in that page. The figure below shows the objname and id for the slider.
You can edit the components the way you want, but make sure to edit the slider maxval to 255, so that it works with the Arduino code we’ll be using.
Демонстрационный режим
Дисплейные модули работают прямо из коробки с демонстрационной прошивкой. Для её старта достаточно подать питание на дисплей:
-
Соедините дисплей с переходной платой «USB to 2 pin» c помощью четырёхпроводного щлейфа.
- Разъём JST PH-4 подключите к дисплею.
- Питание (+5V) — красный провод, подключите к контакту платы «USB to 2 pin» с пометкой «+».
- Земля (GND) — чёрный провод, подключите к контакту платы «USB to 2 pin» с пометкой «−».
- Сигнальные пины (TX) и (RX) используется для обмена данных с микроконтроллером. В демонстациооном режиме не нужны, т.е. оставьте свободными.
- Подключите к полученной конструкции питание через порт micro-USB. Для этого отлично подойдёт зарядник на 5В с кабелем micro USB.
- В итоге, включится дисплей с тестовой прошивкой, которая покажет базовые возможности экрана.
Штатный режим
Состоит из этапов:
— установка среды Nextion Editor (однократно);
— создание проекта для дисплейного модуля;
— прошивка дисплейного модуля.
Создание нового проекта в Nextion Editor
-
Запустите среду «Nextion Editor»
-
Создайте новый проект:
File
NEW
, напишите название будущего проекта и нажмите кнопку . Откроется окно , с двумя вкладками: и . -
Во вкладке . В качестве примера выберем дисплей из линейки модели
-
Во вкладке выберите ориентацию дисплея и кодировку.
Для поддержки кириллицы выбирайте кодировку
- После всех манипуляций нажимайте кнопку . Перед вами откроется графическое окно разработки. Рассмотрим его элементы.
- 1 — Главное меню.
- 2 — Меню управления выравниванием и порядком элементов.
- 3 — Библиотека элементов.
- 4 — Область отображения.
- 5 — Список страниц проекта
- 6 — Библиотека изображений /Библиотека шрифтов.
- 7 — Окно вывода результатов компиляции.
- 8 — Окно для ввода кода, выполняемого при возникновении события.
- 9 — Зона редактирования атрибутов выбранного элемента.
Добавление изображений
-
Нажмите в окне «библиотека изображений» на иконку
-
Выберите интересующее вас изображение на ПК и нажмите кнопку .В окне «библиотека изображений» появиться загруженное изображение.
-
Выделите область отображение дисплея.
-
В окне «зона редактирование атрибутов» в пункте измените поле на .
-
В поле выберите интересующую вас картинку из «библиотеки изображений» и нажмите кнопку Если вы всё сделали правильно, в окне «область отображение дисплея» вы увидите вашу картинку.
Это значит всё получилось и можно смело
Project Resources
We won’t cover step-by-step how to build the GUI in the Nextion display. But we’ll show you how to build the most important parts, so that you can learn how to actually build the user interface. After following the instructions, you should be able to complete the user interface yourself.
Additionally, we provide all the resources you need to complete this project. Here’s all the resources you need (be aware that you may need to change some settings on the user interface to match your display size):
- .HMI file (this file can be imported into the Nextion Editor to edit the GUI);
- background image used in the user interface should also be in the project folder;
- .TFT file (this file should be uploaded to the Nextion display, this is the file that the display runs);
- .ino file (this is the file you should upload to your Arduino board).
psadminetechpath
February 14, 2018
About:
Nextion is a smart hardware HMI (Human Machine Interface) solution published by ITEAD that provides visualization and control interface between human and machine. Nextion HMI comes with simple serial interface and can be easily communicate with Arduino, raspberry pi and other serial Interface compatible hardware’s.
In this post, I will explain how to draw basic HMI screens, setting tag names and reading tags using Arduino.Circuit Diagram:
Circuit Diagram
Prototype
Nextion HMI Designing:
Watch bellow video for complete tutorial on how to operate Nextion HMI graphic designing software.
Arduino Code:Note: I am using common anode RGB LED for output testing purpose. So I have written this code to operate common anode LED as output. If you want to drive relays instead of LED, you will need to change the code a bit.
/*************************************************************************************************************** * Nextion HMI Basic Example : Three Buttons * Version 1.0 * Created By: Pranay Sawarkar * Email: admin@etechpath.com * All Rights Reserved 2018 www.etechpath.com * * Download necessary libraries from the links mentioned in download section in the post, * Post Link: http://www.etechpath.com/how-to-interface-nextion-hmi-with-arduino-mega2560-and-learn-how-to-use-nextion-editor-and-program-tags-in-arduino * *************************************************************************************************************************/ #include "Nextion.h" int S1 = 2, S2 = 3, S3 = 4; NexDSButton bt0 = NexDSButton(0, 2, "bt0"); NexDSButton bt1 = NexDSButton(0, 3, "bt1"); NexDSButton bt2 = NexDSButton(0, 4, "bt2"); char buffer = {0}; NexTouch *nex_listen_list[] = { &bt0, &bt1, &bt2, NULL }; void setup(void) { pinMode(2,OUTPUT); pinMode(3,OUTPUT); pinMode(4,OUTPUT); digitalWrite(S1, HIGH); digitalWrite(S2, HIGH); digitalWrite(S3, HIGH); nexInit(); bt0.attachPop(bt0PopCallback, &bt0); bt1.attachPop(bt1PopCallback, &bt1); bt2.attachPop(bt2PopCallback, &bt2); dbSerialPrintln("setup done"); } void loop(void) { nexLoop(nex_listen_list); } void bt0PopCallback(void *ptr) { uint32_t dual_state; NexDSButton *btn = (NexDSButton *)ptr; dbSerialPrintln("Callback"); dbSerialPrint("ptr="); dbSerialPrintln((uint32_t)ptr); memset(buffer, 0, sizeof(buffer)); bt0.getValue(&dual_state); if(dual_state){digitalWrite(S1, LOW);}else{digitalWrite(S1, HIGH);} } void bt1PopCallback(void *ptr) { uint32_t dual_state; NexDSButton *btn = (NexDSButton *)ptr; dbSerialPrintln("Callback"); dbSerialPrint("ptr="); dbSerialPrintln((uint32_t)ptr); memset(buffer, 0, sizeof(buffer)); bt1.getValue(&dual_state); if(dual_state){digitalWrite(S2, LOW);}else{digitalWrite(S2, HIGH);} } void bt2PopCallback(void *ptr) { uint32_t dual_state; NexSButton *btn = (NexDSButton *)ptr; dbSerialPrintln("Callback"); dbSerialPrint("ptr="); dbSerialPrintln((uint32_t)ptr); memset(buffer, 0, sizeof(buffer)); bt2.getValue(&dual_state); if(dual_state){digitalWrite(S3, LOW);}else{digitalWrite(S3, HIGH);} }
HMI with Arduino working video:
Downloads :
Wrapping up
In this post we’ve introduced you to the Nextion display. We’ve also created a simple application user interface in the Nextion display to control the Arduino pins. The application built is just an example for you to understand how to interface different components with the Arduino – we hope you’ve found the instructions as well as the example provided useful.
In our opinion, Nextion is a great display that makes the process of creating user interfaces simple and easy. Although the Nextion Editor has some issues and limitations it is a great choice for building interfaces for your electronics projects. We have a project on how to create a Node-RED physical interface with the Nextion display and an ESP8266 to control outputs. Feel free to take a look.
What projects would you like to see using the Nextion display? Write a comment down below.
Getting a Nextion Display
You can grab a Nextion basic model, or a Nextion enhanced model. The Nextion enhanced has new features when compared with the basic model:
- has a built-in RTC
- supports saving data to flash
- supports GPIOs
- has larger flash capacity and larger CPU clock
The best model for you, will depend on your needs. If you’re just getting started with Nextion, we recommend getting the 3.2” size which is the one used in the Nextion Editor examples (the examples also work with other sizes, but you need to make some changes). Additionally, this is the most used size, which means more open-source examples and resources for this size.
You can check Maker Advisor website to get your Nextion display at the best price – just click the links below:
- Nextion 2.8” basic model
- Nextion 3.2” basic model
Receiving a Message and detecting a Button
Upload the «ReceiveMessages.ino» sketch from nextion/examples and open the Serial Monitor. Try pressing and releasing the two checkboxes. The responses should appear in the monitor. Note that the messages only appear after releasing the buttons. The exact behaviour is configured in the relevant Touch Event tab in the editor.
Button press (release) messages
Using the listen() function any message coming from the Nextion is stored in a String.
We can modify the loop() to detect when a button is pressed (or in this case — released). Update the loop() with the following code:
The «65 0 2 0 ffff ffff ffff» was copy/pasted from the Serial Monitor. What does the message mean? Here is the official Nextion Instruction Set and a breakdown of the message:
- 65: This message is a touch event
- 0: The page ID is 0
- 2: Component ID (the number of the first button in the Editor)
- 0: Type of event. A «0» means a Release event, A «1» is a Press event
- FFFF FFFF FFFF: The end of message pattern
This can be read as: «Button 1 on Page 0 was released». But it’s easy to just copy the message and compare was done in the code above.
Making the button turn on
The next step is to update the icon when the button is pressed. In the code below instead of printing to the serial monitor we are sending two commands:
- «b0.picc=2» sets the default picture to ID:2
- «ref b0» refreshes the button image
We send these commands to the Nextion using the sendCommand() function:
Nextion Editor Example Code
The .HMI file is included in the firmware folder.
Relevant data to note when looking at the .hmi example file.
- There are only three full screen graphics loaded and they are referenced as Pictures 0, 1 and 2. See the section «The Graphics and Image Cropping«.
- There is only one page and it is referenced as 0. Its background has been set to Picture 0.
- There are four components created:
- m0 (ID:1) is a touch area. The only parameter changed is in the Touch Press Event — Send key value is selected.
- b0 (ID:2) is an image crop button. The default image «picc» is 0. The Pressed image «picc2» is 1. In the Touch Release Event tab the Send key value is selected.
- b1 (ID:3) is an image crop button. The default image «picc» is 0. The Pressed image «picc2» is 1. In the Touch Release Event tab the Send key value is selected.
- t0 (ID:4) is a text area with a solid white background, right aligned.
The Pressed image configured to 1 is why the check boxes show the round grey circle when they are being pressed even though we haven’t configured anything in the Arduino yet.
Nextion Editor General Overview
Here’s a quick overview of the different sections of the Nextion Editor.
- Main Menu
- Canvas – this is where you add your components to build the User Interface.
- Toolbox – this is where you have a wide variety of components you can add to the user interface, like pictures, progress bar, buttons, sliders, and much more.
- Picture/Fonts list – this shows the fonts and pictures imported to your projects. Here you can also add new fonts and pictures.
- Page area – you can manage your pages here, like add more pages, copy and delete pages.
- Attributes area – this part shows your component’s attributes. You can edit the component’s attributes here.
- Compiler output window – this will show any errors occurred during compiling.
- Event window – here you can add code to be run when an event is met.
Adding a Background Image
We’ll start by adding a background image. To use an image as a background, it should have the exact same dimensions as your Nextion display. We’re using the 2.8” display, so the background image needs to be 240×320 pixels. Check your display dimensions and edit your background image accordingly. As an example, we’re using the following image:
After having your background image with the right dimensions, follow the next instructions:
1. In the bottom left corner of the Nextion display, there’s a window for fonts and pictures. Select the Picture tab.
2. Click the (+) button and select your background image. The image will be added to the pictures list and it will be given an id. In this case it is 0.
3. Go to the toolbox, and click on the Picture component. It will be automatically added to your display area.
4. Having that component selected, you should see its attribute in the attribute area. You can double click on the attributes to edit them. Double-click on the pic attribute to select the picture you want. You must write “0” which is the index of the picture you want, or select the image on the new window that pops up. After writing “0”, you actually need to hit ENTER to save the changes.
Step 26: UpdateDHTInfo
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
}
}
Исходный код
- mini-game.ino
-
// библиотека для эмуляции Serial порта #include <SoftwareSerial.h> // создаём объект mySerial и передаём номера управляющих пинов RX и TX // RX - цифровой вывод 8, необходимо соединить с выводом TX дисплея // TX - цифровой вывод 9, необходимо соединить с выводом RX дисплея SoftwareSerial mySerial(8, 9); // переменная для хранения посылки данных String data; void setup() { // открываем последовательный порт mySerial.begin(9600); } void loop() { // ждём данные от дисплея while (mySerial.available() > ) { data += char(mySerial.read()); delay(2); } // если пришёл символ 'g' if (data == "g") { int c = 99; // обнуляем счётчик попаданий mySerial.print("n0.val=0"); // дописываем в посылку служебные символы конца команды comandEnd(); // цикл счётчика таймера for (int i = ; i < 100; i++) { for (int j = ; j < 15; j++) { mySerial.print("tsw p"); mySerial.print(j); mySerial.print(",0"); comandEnd(); mySerial.print("p"); mySerial.print(j); // все слоты дисплея закрашиваем матрёшками mySerial.print(".pic=5"); comandEnd(); } // функция для генерации случайных чисел randomSeed(analogRead(A0)); // генерируем случайное число // одна из 15 области экрана на дисплее int b = random(, 15); mySerial.print("tsw p"); mySerial.print(b); mySerial.print(",1"); comandEnd(); mySerial.print("p"); mySerial.print(b); // появление картинки, на которую надо быстро нажать mySerial.print(".pic=3"); comandEnd(); // уменьшаем таймер на единицу и отправляем в дисплей c--; mySerial.print("j0.val="); mySerial.print(c); comandEnd(); data = ""; delay(500); } data = ""; mySerial.print("t0.txt=\"reset\""); comandEnd(); mySerial.print("tsw t0,1"); comandEnd(); mySerial.print("tsw m0,1"); comandEnd(); delay(2); } data = ""; } // функция отправки конца команды // команда поступающая в дисплей должна кончаться символами «0xFF0xFF0xFF» void comandEnd() { for (int i = ; i < 3; i++) { mySerial.write(0xff); } }
После успешной прошивки модуля, можете наслаждаться игрой.
Introduction: Display Nextion With Arduino Uno
By Fernando KoyanagiVisit my Site!Follow
More by the author:
About: Do you like technology? Follow my channel on Youtube and my Blog. In them I put videos every week of microcontrollers, arduinos, networks, among other subjects.
More About Fernando Koyanagi »
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.
Характеристики
- Модель: Nextion Intelligent NX8048P070-011C
- Диагональ: 7 дюймов
- Разрешение: 800×480
- Тип матрицы: TFT IPS
- Количество цветов: 65536 (16 бит, RGB: 5R-6G-5B)
- Подсветка: светодиодная (LED)
- Максимальная яркость: 300 кд/м2
- Ресурс подсветки: не менее 30000 часов
- Тип тачскрина: ёмкостный
- Контроллер дисплея: Ai HMI
- Тактовая частота: 200 МГц
- SRAM-память: 512 КБ
- EEPROM-память: 1 КБ
- Внешняя Flash-память: 128 МБ
- Интерфейс обмена данными: UART
- Пины GPIO: 8
- Поддержка microSD: до 32 ГБ (FAT32)
- Аудиовыход: 0,5 Вт / 16 Ом
- Напряжение питания: 5 В
- Напряжение логических уровней: 3,3–5 В
- Потребляемый ток при 100% яркости: до 430 мА
- Потребляемый ток в спящем режиме: до 170 мА
- Питание встроенных часов: батарейка CR1220
- Размер экрана: 154×86 мм
- Размер дисплея: 165×100 мм
- Размер платы: 181×108×9 мм
- Вес модуля: 310 г