Андрей Смирнов
Время чтения: ~19 мин.
Просмотров: 80

Цветной сенсорный дисплей nextion intelligent 7” / 800×480 / ёмкостный / в корпусе

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.

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

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

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

Специалист по государственным закупкам 44 фз

Исходный код

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

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

Характеристики

  • Модель: Nextion Intelligent NX8048P070-011C-Y
  • Диагональ: 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% яркости: до 530 мА
  • Потребляемый ток в спящем режиме: до 170 мА
  • Питание встроенных часов: батарейка CR1220
  • Размер экрана: 154×86 мм
  • Размер платы: 218×150×22 мм
  • Вес модуля: 470 г

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

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.

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.

Демонстрационный режим

Дисплейные модули работают прямо из коробки с демонстрационной прошивкой. Для её старта достаточно подать питание на дисплей:

  1. Соедините дисплей с переходной платой «USB to 2 pin» c помощью четырёхпроводного щлейфа.
    1. Разъём JST PH-4 подключите к дисплею.
    2. Питание (+5V) — красный провод, подключите к контакту платы «USB to 2 pin» с пометкой «+».
    3. Земля (GND) — чёрный провод, подключите к контакту платы «USB to 2 pin» с пометкой «−».
    4. Сигнальные пины (TX) и (RX) используется для обмена данных с микроконтроллером. В демонстациооном режиме не нужны, т.е. оставьте свободными.
  2. Подключите к полученной конструкции питание через порт micro-USB. Для этого отлично подойдёт зарядник на 5В с кабелем micro USB.
  3. В итоге, включится дисплей с тестовой прошивкой, которая покажет базовые возможности экрана.

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.

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.

Adding text labels, sliders and buttons

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.

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.

Описание товара

Подробности

Enhanced Support Tickets Contents Recommend reasons
2 Pack Valid for 1 month $125.00/ticket value Ideal if you have a small project but have some issues to finalize itthen perhaps 2 tickets may be enough to reach your goal.We can help you to finalize your work on a budget in time
5 Pack Valid for 1 month $100.00/ticket over regular $125/ticket price Savings of 20.00% Ideal if your project is a bit more advanced You have more questions Your idea is a bit more complex 5 technical tickets may better serve your needs.
25 Pack Valid for 3 months$80.00/ticket over regular $125/ticket priceSavings of 36.00% Ideal for larger commercial based project that desire to outsourcePerhaps you need more time than one monthPerhaps you don’t have the right development resources in-houseOur midrange offer may best fit your needsWe can help you realize your idea – on time and in budget
75 Pack Valid for 6 months$66.67/ticket over regular$125/ticket priceSavings of 46.67% Ideal for Resellers with VIP customersHelp your VIP customers out with transferable enhanced ticketsIdeal for Customers who want extra support on a contractual basis.Our guaranteed long-term support may be the right fit for you.Let our Experience by yours, on budget, whenever you need.
Project Units Units for custom Project Work Project Units are used to pay customized work as per your agreement for your customized Enhanced Support Request.  

Terms and Conditions

Itead warrants that Enhanced Support services will be provided in a professional manner consistent with industry standards

Enhanced Support is given according to purchased Enhanced Support package

A first general feedback within normal business directives is guaranteed

Itead does not guarantee that Enhanced Support will fix possible customer issues

Customer must provide specific details regarding work being requested to define scope

  • Itead must first agree to accept task as requested and defined by customer
  • Customer commits to not withdraw once work on their task has been started
  • After any knowledge-transfer has happened, support purchased is non-refundable.
  • Itead ensures confidentiality about any customer belongings in general
  • Abuse in any case will result in immediate cancel of support agreements

Enhanced Support in general does not INCLUDE

  • project development
  • total software development (HMI, INO, …)
  • hardware development (electronic work, PCB design …)
  • hardware and software customizations (Display and Editor)
  • any project attempting to reverse engineer Itead Intellectual Property

Enhanced Support in general can INCLUDE

  • assistance in debugging user code
  • assistance in enhancing routines
  • assistance in Nextion techniques and approaches
  • exploration/recommendations of what is possible with Nextion
  • assistance in technical understandings of Nextion and HMI
  • assistance with some MCU Nextion related routines

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

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

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

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

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

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

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

— установка среды 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. В поле выберите интересующую вас картинку из «библиотеки изображений» и нажмите кнопку Если вы всё сделали правильно, в окне «область отображение дисплея» вы увидите вашу картинку.

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

Рейтинг автора
5
Материал подготовил
Максим Иванов
Наш эксперт
Написано статей
129
Ссылка на основную публикацию
Похожие публикации