Nextion display with arduino

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.

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:

  1. Click here to download the Nextion library for Arduino – ITEADLIB_Arduino_Nextion. You should have a .zip folder in your Downloads folder.
  2. Unzip the .zip folder and you should get ITEADLIB-Arduino-Nextion-master folder.
  3. Rename your folder from ITEADLIB_Arduino_Nextion-master to ITEADLIB_Arduino_Nextion.
  4. Move the ITEADLIB_Arduino_Nextion folder to your Arduino IDE installation libraries folder.
  5. 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.

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.

Nextion Editor General Overview

Here’s a quick overview of the different sections of the Nextion Editor.

  1. Main Menu
  2. Canvas – this is where you add your components to build the User Interface.
  3. 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.
  4. Picture/Fonts list – this shows the fonts and pictures imported to your projects. Here you can also add new fonts and pictures.
  5. Page area – you can manage your pages here, like add more pages, copy and delete pages.
  6. Attributes area – this part shows your component’s attributes. You can edit the component’s attributes here.
  7. Compiler output window – this will show any errors occurred during compiling.
  8. Event window – here you can add code to be run when an event is met.

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).

Creating and Navigating to a New Page

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.

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.

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.

Штатный режим

Состоит из этапов:

— установка среды Nextion Editor (однократно);

— создание проекта для дисплейного модуля;

— прошивка дисплейного модуля.

Создание нового проекта в Nextion Editor

  1. Запустите среду «Nextion Editor»

  2. Создайте новый проект:
    File
    NEW
    , напишите название будущего проекта и нажмите кнопку . Откроется окно , с двумя вкладками: и .

  3. Во вкладке . В качестве примера выберем дисплей из линейки модели

  4. Во вкладке выберите ориентацию дисплея и кодировку.

    Для поддержки кириллицы выбирайте кодировку

  5. После всех манипуляций нажимайте кнопку . Перед вами откроется графическое окно разработки. Рассмотрим его элементы.

  • 1 — Главное меню.
  • 2 — Меню управления выравниванием и порядком элементов.
  • 3 — Библиотека элементов.
  • 4 — Область отображения.
  • 5 — Список страниц проекта
  • 6 — Библиотека изображений /Библиотека шрифтов.
  • 7 — Окно вывода результатов компиляции.
  • 8 — Окно для ввода кода, выполняемого при возникновении события.
  • 9 — Зона редактирования атрибутов выбранного элемента.

Добавление изображений

  1. Нажмите в окне «библиотека изображений» на иконку

  2. Выберите интересующее вас изображение на ПК и нажмите кнопку .В окне «библиотека изображений» появиться загруженное изображение.

  3. Выделите область отображение дисплея.

  4. В окне «зона редактирование атрибутов» в пункте измените поле на .

  5. В поле выберите интересующую вас картинку из «библиотеки изображений» и нажмите кнопку Если вы всё сделали правильно, в окне «область отображение дисплея» вы увидите вашу картинку.

Это значит всё получилось и можно смело

Элементы платы

Экран с тачскрином

За отображение информации отвечает ЖК-матрица 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.

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.

Исходный код

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);
  }
}

После успешной прошивки модуля, можете наслаждаться игрой.

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 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;
}
}

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.

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
}
}
}

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
}
}

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.

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:

NextionWiring to
GNDGND
RXArduino pin 1 (TX)
TXArduino pin 0 (RX)
VCC5V

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.

Комплектация

Каждый дисплей Nextion дополнен комплектующими, которые помогут соединиться с экраном:

  • Четырёхпроводной шлейф служит для подключения дисплея к питанию и управляющим пинам внешнего контроллера: например Arduino, Espruino или Raspberry Pi. С одной стороны шлейфа расположен разъём JST PH-4 (мама), а с другой — четыре свободных провода с коннекторами «мама» на концах:

    • Земля (G) — чёрный провод. Соедините с землёй внешнего микроконтроллера.
    • Сигнальный (RX) — жёлтый провод, цифровой вход дисплейного модуля. Используется для приёма данных из внешнего контроллера. Подключите к пину TX внешнего микроконтроллера.
    • Сигнальный (TX) — синий провод, цифровой выход дисплейного модуля. Используется для передачи данных во внешний контроллер. Подключите к пину RX внешнего микроконтроллера.
    • Питание (V) — красный провод. Соедините с питанием внешнего микроконтроллера.
  • Адаптер питания «USB to 2 Pin» — используется для подключения напряжения к дисплею, другими словами включает экран.

How to interface Nextion HMI with Arduino Mega2560 and learn how to use Nextion editor and program tags in Arduino

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 :

Nextion Editor Example Code

The .HMI file is included in the firmware folder.
Relevant data to note when looking at the .hmi example file.

  1. 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«.
  2. There is only one page and it is referenced as 0. Its background has been set to Picture 0.
  3. There are four components created:
    1. m0 (ID:1) is a touch area. The only parameter changed is in the Touch Press Event — Send key value is selected.
    2. 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.
    3. 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.
    4. 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.

Оцените статью:
Оставить комментарий
Adblock
detector