Nextion editor инструкция на русском

Руководство к редактору Nextion Editor

В этом разделе рассматриваются возможности и функции редактора Nextion Editor версии 1.61.2 и более ранних выпусков. Редактор Nextion Editor — это программный инструмент ускоренного и упрощенного способа создания графических интерфейсов для всех устройств Nextion HMI. С помощью редактора Nextion Editor, время, затрачиваемое на создание графического интерфейса, может значительно сократиться до нескольких часов вместо недель, или до нескольких дней вместо нескольких месяцев. В этом руководстве не разъясняются самые простые и привычные действиях наподобие «как открыть или сохранить файл». В тоже время руководство даёт возможность почерпнуть новые знания и умения, или помогает освежить в памяти что-то забытое.

С появлением новой серии дисплейных модулей Nextion Intelligent, редактор Nextion Editor претерпел обширные изменения и получил некоторые нововведения (по аналогии с версией редактора 0.33 и выходом серии Enhanced). В первую очередь это означает, что обновлённый редактор не будет в точности соответствовать предыдущим версиям и повторять их функционал.

Владельцам устаревших устройств Nextion с прошивкой до v0.38 необходимо выполнить промежуточное обновление до v0.42, которое позволяет начать работать в версиях редактора Nextion Editor TLS Edition или Nextion Editor v0.53 с использованием всех новых функций. Подробная информация о способе обновления и файлах TFTv0.42 размещена в разделе «Часто задаваемые вопросы». Если в текущей версии редактора возникают проблемы полной совместимости кода, следует обратиться к версии Nextion Editor TLS Edition (основанный на ядре версии Nextion Editor v0.53). Редактор LTS Edition более не поддерживается командой разработчиков, добавление новых функции в эту версию в будущем не предусматривается.

Руководство освещает исключительно версию редактора Nextion Editor 1.61.2, не касаясь редакции Nextion Editor TLS Edition. Некоторые части руководства относятся только к определённым сериям дисплейных модулей Nextion, и отмечены в тексте соответствующими обозначениями: базовая серия Nextion Basic , расширенная серия Nextion Enhanced , и интеллектуальная серия Nextion Intelligent .

Требования к персональному компьютеру

  • Операционная система Windows (XP или новее).
    Пользователи должны свободно владеть основными навыками работы в ОС. Любые возникающие вопросы, связанные с работой в ОС Windows, не входят в рамки настоящего руководства.
    Программа Nextion Editor может быть установлена и запущена на ПК с другой ОС, однако работоспособность редактора на другой ОС официально не поддерживается командой Nextion.
  • Установленная платформа Microsoft .NET Framework 3.5
    Загрузить .NET Framework 3.5 с официального веб-сайта Microsoft можно по этой ссылке.
  • Установленный пакет Microsoft Visual C++ Redistributable.
    Своевременное обновление пакета может быть источником решения проблем для многих пользователей. Загрузить Visual C++ Redistributable с официального веб-сайта Microsoft можно по этой ссылке.
  • Разумно подобранный размер монитора с графическим разрешением, превышающим графическое разрешение выбранного устройства Nextion HMI.
    Если разработка ведётся для разрешения 320х240 или 240х320, стандартного размера монитора вполне достаточно. Напротив, если разработка проводится для разрешения 1024х600 или 600х1024, то монитор с разрешением 800х600 графических точек определённо станет не лучшим решением. Целесообразнее всего выбрать сразу большой монитор с высоким разрешением, чтобы на его экране полноценно умещались окно редактора (дизайнерский холст, меню, панели инструментов и событий), или окно симуляции HMI-проекта.

Требования к знаниям пользователя

  • Базовые навыки программирования обязательны. Внутренние инструкции Nextion — это набор из входящих текстовых (ASCII) команд и возвращаемых бинарных данных с первым значимым байтом. Отправка идентификаторов компонентов (Send Сomponent ID) для событий «Касание сенсорной панели» может применяться с целью передачи программной задачи в пользовательский микроконтроллер исполняемого устройства.
  • Более 68 тысяч микроконтроллеров (любой микроконтроллер с интегрированным модулем UART и двумя цифровыми контактами для передачи данных по последовательной шине), запрограммированных на более чем 130 языках, может использоваться вместе с Nextion. Понимание языка программирования и знание выбранного на стороне исполнительной части микроконтроллера — обязанность разработчика HMI-проекта.
  • Обновление прошивки устройств Nextion с завершённым HMI-проектом осуществляется с помощью карты microSD или через последовательный порт UART. Знание о установке, настройке и работе подключаемых к дисплейным модулям NEXTION устройств связи по шине UART (программаторов, адаптеров USB-TTL UART и т.д.) возлагается на разработчика HMI-проекта.

Загрузка редактора Nextion Editor

Новейшая версия редактора Nextion Editor доступна для загрузки по этой ссылке. Скачиваемый дистрибутив Nextion Editor существует в двух вариантах:

  1. Однофайловый дистрибутив .EXE, с автоматическим режимом установки через инсталлятор Windows MSI. Одновременно на одном ПК устанавливается и регистрируется в его ОС только одна версия EXE. Запуск обновления кнопкой «Автоматическое обновление (Auto Update)» из Nextion Editor загружает версию EXE.
  2. Однофайловый дистрибутив в ZIP-архиве, который пользователь может самостоятельно распаковать в выбранную папку. ZIP-версия удобна для единовременной работы с несколькими копиями или версиями Nextion Editor. Запуск обновления кнопкой «Ручное обновление (Manual Update)» из Nextion Editor открывает в веб-браузере страницу для загрузки ZIP-версии.

Используйте дисплейные модули Nextion для отображения текста, изображений, анимаций, кнопок, переключателей, стрелочных индикаторов, прогресс баров и графиков. Дисплеи с лёгкостью позволяют организовывать меню с выпадающими списками и даже интерактивные игры!

Всё это становится возможным благодаря мощному 32-х разрядному процессору и визуальной среде разработки Nextion Editor. С внешним миром дисплей взаимодействует с помощью резистивного сенсора касаний с собственным контроллером и интерфейса UART. Панель подключается всего по четырём проводам (два из которых — питание). Для обновления прошивки дисплея, помимо UART, предусмотрен разъем для microSD карты.

В зависимости от версии дисплеи оснащаются большим объемом памяти, часами реального времени и даже собственными пинами GPIO, что позволяет использовать дисплей для непосредственного управления устройствами, используя реле и т.п. приборы.

Видеообзор

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

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

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

    • Земля (G) — чёрный провод. Соедините с землёй внешнего микроконтроллера.

    • Сигнальный (RX) — жёлтый провод, цифровой вход дисплейного модуля. Используется для приёма данных из внешнего контроллера. Подключите к пину TX внешнего микроконтроллера.

    • Сигнальный (TX) — синий провод, цифровой выход дисплейного модуля. Используется для передачи данных во внешний контроллер. Подключите к пину RX внешнего микроконтроллера.

    • Питание (V) — красный провод. Соедините с питанием внешнего микроконтроллера.

  • Адаптер питания «USB to 2 Pin» — используется для подключения напряжения к дисплею, другими словами включает экран.

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

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

  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. В итоге, включится дисплей с тестовой прошивкой, которая покажет базовые возможности экрана.

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

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

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

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

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

Установка среды Nextion Editor

Для работы с дисплеем необходимо установить и настроить среду разработки «Nextion Editor»

Для этого перейдите на официальный сайт дисплейных модулей «Nextion». Скачайте и установите последнюю версию среды.

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

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

  2. Создайте новый проект:, напишите название будущего проекта и нажмите кнопку Сохранить.

    Откроется окно Setting, с двумя вкладками: Device и Display.

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

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

  4. После всех манипуляций нажимайте кнопку OK.

    Перед вами откроется графическое окно разработки. Рассмотрим его элементы.

  • 1 — Главное меню.

  • 2 — Меню управления выравниванием и порядком элементов.

  • 3 — Библиотека элементов.

  • 4 — Область отображения.

  • 5 — Список страниц проекта

  • 6 — Библиотека изображений /Библиотека шрифтов.

  • 7 — Окно вывода результатов компиляции.

  • 8 — Окно для ввода кода, выполняемого при возникновении события.

  • 9 — Зона редактирования атрибутов выбранного элемента.

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

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

  2. Выберите интересующее вас изображение на ПК и нажмите кнопку Открыть.

    В окне «библиотека изображений» появиться загруженное изображение.

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

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

  5. В поле pic выберите интересующую вас картинку из «библиотеки изображений» и нажмите кнопку OK

    Если вы всё сделали правильно, в окне «область отображение дисплея» вы увидите вашу картинку.

Это значит всё получилось и можно смело переходить к прошивки дисплея.

Прошивка дисплейных модулей

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

Перед прошивкой проект необходимо проверить не наличие ошибок — скомпилировать. Для этого нажмите кнопку Compile. В окне «вывода результатов компиляции» вы должны увидеть сообщение об успешной компиляции.

Дисплейные модули Nextion поддерживают два вида прошивки:

  • Через последовательный порт UART

  • С помощью карты microSD.

Рассмотрим их подробнее.

Прошивка через UART

Для прошивки дисплея через UART понадобится USB-Serial адаптер.

  1. Подключите дисплей к адаптеру USB-Serial следующим образом:

    1. Питание дисплея +5V — к питанию USB-Serial-адаптера.

    2. Земля дисплея GND — к питанию USB-Serial-адаптера.

    3. TX дисплея — в RX USB-Serial-адаптера.

    4. RX дисплея — в TX USB-Serial-адаптера.

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

    После этого загруженный проект будет выполняться и отображаться на дисплейном модуле.

Прошивка через microSD

Прошивка через UART занимает достаточно долгое время и требует дополнительного UART-преобразователя. В связи с этим существует альтернативный способ прошивки дисплеев Nextion с помощью microSD-карты.

  1. Откройте папку с компилированными проектами:

  2. Скопируйте файл с именем вашего проекта на microSD-карту.

  3. Извлеките microSD-карту из вашего ПК и вставьте её в дисплей.

  4. Подключите питание на дисплей.

  5. Дождитесь окончания прошивки.

  6. Извлеките microSD-карту.

После всех действий загруженный проект будет выполняться и отображаться на дисплейном модуле.

Примеры работы

Линейка Nextion Enhanced

Линейка Nextion Intelligent

Ресурсы

Для
моего недавнего

проекта
была поставлена задача управление
с
дисплея. И достаточно
красивая графика. Выбор
пал
на дисплей
линейки Nextion.

Это обусловлено
тем, что у
данного дисплея есть
ряд преимуществ:

1.
Собственный
редактор прошивки
Nextion
Editor.

В котором достаточно просто сделать
интерфейс, при этом не нужно много писать
кода.

2.
Сенсорный экран. Все активные элементы
привязываются
автоматически
и нет требуется
калибровка.
Все дисплеи идут откалиброванные
с завода.

3.
Не расходует мощности
нашей
Arduino.
Так как дисплей
оснащен
своим микроконтроллером.

Минусы
на мой взгляд:

1.
Резистивный сенсор. Срабатывает
только при нажатии. Что достаточно не
привычно. Но при этом срабатывает
достаточно
быстро и точно.

2.
Ограничения разработки возможностью
редактора nextion
editor
. Некоторые
задачи не возможно реализовать. Или
приходиться делать костыли.

3.
Nextion
Editor
достаточно
коряво выводит русские буквы и нет
переноса по словам. Только буквенный
перенос на новую строчку для любого
шрифта.

4.
Не поддерживаются картинки с прозрачным
фоном
. Заливает
их
черным фоном.

Но
это не так критично.
Сделать можно очень красивые и сложные
панели управления.

Купить
дисплей
Nextion
можно
тут
.

Скачать
редактор Nextion
Editor

можно тут.

Также
можно установить
Nextion
Editor
на
OS Linux
. Я установил
на
Ubuntu. Для этого устанавливаем
PlayOnLinux.
Ищем
наше приложения.

Нажимаем
установить
и программа PlayOnLinux автоматически все
установит.

<span id=»selection-marker-1″ class=»redactor-selection-marker» data-verified=»redactor»></span>

После
установки запускаем программу. Создаем
новый проект для
этого в пункте меню выбираем
New,
вводим название проекта
lesson-one
и сохраняем.
Наш проект будет сохранен
в файл lesson-one.
hmi.
В окне Setting во вкладке Device выберем модель
дисплея.

Во
вкладке
Display выбираем ориентацию дисплея
и кодировку
iso-8859-5, для
поддержки
русского языка.
Во вкладке project можно установить
пароль для
доступ к проекту.

После
создания проекта откроется рабочее
поле

1.
Главное меню.

2.
Меню управления выравниванием и порядком
элементов.

3.
Библиотека элементов.

4.
Область отображения.

5.
Список страниц проекта.

6.
Библиотека изображений /Библиотека
шрифтов.

7.
Окно вывода результатов компиляции.

8.
Окно для ввода кода, выполняемого при
возникновении события.

9.
Зона редактирования атрибутов выбранного
элемента.

Давайте
добавим картинку в наш проект на Arduino для этого
воспользуемся вкладкой загрузки
изображений в проект. Загружать
нужно картинки соответственного
размер. Если разрешение вашего экрана
480х320. Картинка должна быть такого же
размера.
Программа не умеет подгонять размеры
картинок. Это касается
и других элементов.

Также
не поддерживается
прозрачный фон, он его заливает черным
цветом.

Основные
элементы


Добавить
изображение. При нажатии этой кнопки
откроется стандартное окно выбора файла
изображения на диске.


Удалить
выделенное изображение.


Заменить
выделенное изображение.


Вставить
новое изображение перед выделенным.


Поднять
изображение в списке вверх. Индексы
изображений будут пересчитаны для
обеспечения последовательности сверху
вниз.


Опустить
изображение в списке вниз.


удалить
все изображения.

Сейчас мы можем использовать наше
изображение в проект.

Давайте сделаем его фоном нашей первой
страницы.

Поменяем свойства страницы pages0, sta на
image
и выберем нашу картинку.

Наш первый проект готов.

Нажимаем кнопку Debug в панели меню. В
новом окне откроется пример, как это
будет отображаться на
дисплее Nextion.

Давайте
переименуем страницу с нашим логотипом
на
Logo. В следующем уроке расскажу для
чего я это сделал.

И еще один небольшой нюанс использования
программы
Nextion
Editor
.
Пока вы не нажмете кнопку Debug
или
Compile. Бинарный файл для прошивке не
обновиться. Можно сделать много изменения,
загрузить на дисплей, а изменений нет.
Возможно
это в моей версии программы или в
Linux
она
себя так ведет. Но у меня такая ситуация
была.

Прошить
дисплей Nextion
можно двумя способами:

1.
С помощью
UART программатора.
Для прошивки воспользуйтесь пунктом
меню Upload. Это достаточно долгий процесс.
И в Linux нужно заморочиться с портами.
Поэтому я пользуюсь вторым способом.

 С помощью UART программатора

2.
П
рошивка
с Sd карты
. Для этого в пункте меню file
выбираем open builed folder.

Выбираем файл
lesson-one.tft и копируем его на карту памяти.
Карту предварительно нужно отформатировать
в формате FAT32. Карта
памяти

должна быть 10 класса.

Прошивка
дисплея
Nextion.

Отключаем
дисплей. Ставим флешку. Подаем
питание на дисплей. Если у вас дисплей
задумался и после вывел демонстрационную
информацию. Ваша флешка не подходит.
Если загрузил экран на котором показывает
скорость 9600 и больше ни чего не происходит
значит у вас на флешке есть постороннии
файлы.

При
прошивке у вас побегут проценты загрузки
прошивки. При завершении прошивка.
Отключите дисплей. Достаем флешку. И
можно пользоваться дисплее.

В
нашем случае мы вывели логотип. В
следующем уроке научим дисплей общаться
с Arduino.

Если
вам интересна данная тема пишите в
комментарии.

Не забывайте подписываться на канал Youtube и вступайте в группы в Вконтакте и Facebook.

Всем Пока-Пока. И до встречи в следующем уроке.

Понравилась статья? Поделитесь ею с друзьями:

Файлы для скачивания

Исходники к уроку 12.1 Nextion Editor .zip 219 Kb 1225 Скачать

Время на прочтение17 мин

Количество просмотров102K

Добрый день.
Хочу рассказать об одном очень интересном проекте компании ITEAD STUDIO — цветной ЖК дисплей + резистивный сенсор касаний с собственным контроллером, управляемые по UART “Nextion HMI”. Данный проект появился на краудфандинговой платформе Indiegogo и при заявленных 20000 долларах проект собрал более 45000 долларов.
Один из пользователей программы FLProg прислал мне образец такой панели для ознакомления. Начав работать с ней, я был восхищён её возможностями, при очень демократичной цене. По возможностям она очень близко подходит к промышленным HMI панелям, а её редактор представляет собой практически полноценную SCADA систему. Поэтому я интегрировал управление этой панелью в проект FLProg.
В этой серии уроков я расскажу, как работать с этой панелью, и управлять ею из программы FLProg. Первый урок будет посвящён программе Nextion Editor и созданию проекта визуализации в ней.

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

NX3224T024_011R NX3224T028_011R
Размер 2.4″ 2.4″
Разрешение 320*240 320*240
Touch Panel RTP RTP
Количество цветов 65536 65536
Flash(MB) 4 4
RAM(Byte) 2048 2048
Описание wiki.iteadstudio.com/NX3224T024 wiki.iteadstudio.com/NX3224T028
NX4024T032_011R NX4827T043_011R
Размер 3.2″ 4.3″
Разрешение 400*240 480*272
Touch Panel RTP RTP
Количество цветов 65536 65536
Flash(MB) 4 16
RAM(Byte) 2048 2048
Описание wiki.iteadstudio.com/NX4024T032 wiki.iteadstudio.com/NX4827T043
NX8048T050_011R NX8048T070_011R
Размер 5.0″ 7.0″
Разрешение 800*480 800*480
Touch Panel RTP RTP
Количество цветов 65536 65536
Flash(MB) 16 16
RAM(Byte) 2048 2048
Описание wiki.iteadstudio.com/NX8048T050 wiki.iteadstudio.com/NX8048T070

Скачать программу Nextion Editor на сайте производителя.
Основное окно программы.

При создании нового проекта (“File” -> “New”) в первую очередь необходимо выбрать место хранения и имя нового проекта. После этого будет предложено выбрать используемую модель панели, ориентацию экрана, и необходимую кодировку.

Для поддержки русских символов необходимо использовать кодировку iso-8859-5.
Рассмотрим окно программы с открытым проектом.

Зоны окна:

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

Сразу после создания проекта в нём будет создана первая страниц с индексом 0 именем по умолчанию “page0”. Данное имя можно сменить, сделав двойной клик на нём и введя новое имя. Имя страницы должно быть уникальным в пределах проекта. После ввода нового имени страницы необходимо нажать “Enter”.
Рассмотрим меню списка страниц (5).

— Добавить страницу.

— Удалить страницу. Индексы страниц будут пересчитаны для устранения пустот.

— Вставить страницу перед выделенной. Индексы страниц будут пересчитаны для обеспечения последовательности сверху вниз.

— Поднять страницу в списке вверх. Индексы страниц будут пересчитаны для обеспечения последовательности сверху вниз.

— Опустить страницу в списке вниз. Индексы страниц будут пересчитаны для обеспечения последовательности сверху вниз.

— Скопировать выделенную страницу. Копия выделенной страницы будет добавлена в низ списка.

— Удалить все станицы.

При выборе страницы в списке, в зоне редактирования атрибутов (6) будет возможно изменить параметры странницы.

При выборе определённого атрибута в нижней части данной зоны будет показана дополнительная информация по атрибуту.
Я до конца не освоил или не понял необходимость всех атрибутов имеющихся в редакторе, поэтому буду рассказывать только о тех, с которыми разобрался.

Атрибуты страницы.

  • vscope – Видимость. Возможные значения:
    • local – видимость в пределах данной страницы
    • global – видимость на всех страницах. Мне непонятно назначение данного атрибута в контексте страницы.
  • sta – Режим заливки фона. Возможные значения:
    • no background – нет заливки. При отображении страницы в таком режиме в качестве фона окажется ранее отрисованная страница
    • solid color – сплошная заливка цветом, заданным с помощью атрибута “bco”
    • image – использование в качестве фона картинки. В качестве картинки используется изображение с индексом заданным в атрибуте “pic”. Соответственно данное изображение предварительно должно быть загружено в библиотеку изображений(3). Изображение по размеру должно соответствовать разрешению экрана панели. В случае превышения изображением размера панели будет выдана ошибка, и изображение не будет наложено, в случае размера изображения меньшего, чем панель на незакрытых им областях экрана будет видна отрисованная ранее страница

Следующий атрибут зависит от режима заливки фона.
В режиме “no background” этот атрибут отсутствует.
В режиме “solid color” это атрибут “bco”. Он определяет каким цветом будет заливаться фон страницы. В поле значения данного атрибута отображается код цвета в формате Hight Color. При двойном клике на этом поле открывается окно выбора цвета.

Данное окно используется при задании значений всех атрибутов связанных с цветом.
В режиме “image” это атрибут “pic”. Он определяет, какое изображение используется для заднего фона страницы. При двойном клике на поле значения данного атрибута открывается окно выбора изображения.

Данное окно так же используется в программе для задания значений всех атрибутов связанных с изображением.
Остальные атрибуты показывают размеры страницы, и доступны для редактирования, но я не советую их трогать, поскольку поведение страницы в этом случае не предсказуемо.
Теперь рассмотрим библиотеку изображений и библиотеку шрифтов. Они находятся в зоне 3 на вкладках “Picture” и “Fonts” соответственно.

Вкладка “Picture”.

На вкладке показываются загруженные в проект изображения, а так же отображены их индекс и размеры.

Меню вкладки.

— Добавить изображение. При нажатии этой кнопки откроется стандартное окно выбора файла изображения на диске. Возможен множественный выбор.

— Удалить выделенное изображение. Индексы изображений будут пересчитаны для устранения пустот.

— Заменить выделенное изображение. При нажатии на эту кнопку откроется стандартное окно выбора файла изображения на диске. Выбранное изображение заменит выделенное, при этом не только в библиотеке, но и в тех местах, где оно используется.

— Вставить новое изображение перед выделенным. При нажатии на эту кнопку откроется стандартное окно выбора файла изображения на диске. Выбранное изображение вставится перед выделенным. Индексы изображений будут пересчитаны для обеспечения последовательности сверху вниз.

— Поднять изображение в списке вверх. Индексы изображений будут пересчитаны для обеспечения последовательности сверху вниз.

— Опустить изображение в списке вниз. Индексы изображений будут пересчитаны для обеспечения последовательности сверху вниз.

— удалить все изображения.

Вкладка “Fonts”.

На этой вкладке отображаются шрифты, используемые в проекте. Для того что бы добавить шрифт в проект, необходимо сначала сгенерировать файл шрифта с помощью инструмента “Font Generator”. Данный инструмент вызывается из главного меню программы “Tools” -> “Font Generator”.

В окне этого инструмента надо выбрать размер шрифта, выбрать исходный шрифт из системы, схему (я, честно говоря, не понял что это такое) и ввести имя шрифта которое будет отображаться в списке шрифтов. Затем нажимаем кнопку “Generate font”. При этом будет запрошено место сохранения шрифта и имя файла. Файл шрифта сохраняется с расширением “.zi”. При закрытии окна “Font Generator” будет предложено сразу добавить сгенерированный шрифт в библиотеку шрифтов проекта.

Меню вкладки.

— Добавить шрифт. При нажатии этой кнопки откроется стандартное окно выбора файла шрифта на диске. Возможен множественный выбор.

— Удалить выделенный шрифт. Индексы шрифтов будут пересчитаны для устранения пустот.

— Заменить выделенный шрифт. При нажатии на эту кнопку откроется стандартное окно выбора файла шрифта на диске. Выбранный шрифт заменит выделенный, при этом не только в библиотеке, но и в тех местах, где он используется.

— Вставить новый шрифт перед выделенным. При нажатии на эту кнопку откроется стандартное окно выбора файла шрифта на диске. Выбранный шрифт вставится перед выделенным. Индексы шрифтов будут пересчитаны для обеспечения последовательности сверху вниз.

— Поднять шрифт в списке вверх. Индексы шрифтов будут пересчитаны для обеспечения последовательности сверху вниз.

— Опустить шрифт в списке вниз. Индексы шрифтов будут пересчитаны для обеспечения последовательности сверху вниз.

— Пред просмотр выделенного шрифта.

— удалить все шрифты.

Теперь рассмотрим библиотеку элементов (2).

Элементы в проект добавляются кликом по нему. Графические элементы добавляются в позицию 0@0, таймер и переменная в строку под зоной экрана.
Практически все графические элементы имеют атрибуты “objname”, “vscope” и “sta”. Коротко я уже рассказал о последних двух в контексте страницы. Немного расширю рассказ.

  • “objname” – имя элемента. Используется при написании кода и при запросах к атрибутам через UART.

Атрибут “vscope” определяет доступность элемента для изменения его атрибутов и может иметь два значения:

  • “local” – прочитать и изменить атрибуты элемента можно, только если активна страница, на которой он расположен. Это касается как кода исполняемого на самой панели, так и при запросах через UART.
  • “global” — прочитать и изменить атрибуты элемента можно в любой момент времени. Это касается как кода исполняемого на самой панели, так и при запросах через UART. При использовании этого значения атрибута необходимо следить за уникальностью имени в пределах всего проекта.

Атрибут “sta” определяет режим заливки фона элемента и может иметь следующие значения:

  • “solid color” – заливка фона сплошным цветом.
  • “image” – использование картинки в качестве фона. Размер элемента подгоняется под размер картинки.
  • “crop image” – дословный перевод «вырезанное изображение». По смыслу наиболее близко как ни странно к прозрачному фону. Идеология такая. В качестве фона берётся картинка, но она накладывается в нулевые координаты страницы. В качестве фона элемента используется участок изображения, который совпадает с проекцией элемента на область страницу. Но это легче попробовать, чем объяснить.

В списке атрибутов (6) часть из них показана зелёным цветом. Эти атрибуты доступны для чтения и записи как с помощью кода исполняемого на самой панели, так и с помощью команд через UART. Атрибуты, показанные чёрным цветом, изменяются только через редактор на этапе разработки проекта.
Рассмотрим доступные элементы.

— Поле с текстом.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “sta”
  • “bco” – цвет заливки фона. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “pic” – индекс картинки для фона. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “picс” – индекс вырезанной картинки для фона. Этот атрибут появляется при выборе значения “crop image” в атрибуте “sta”
  • “pco” – цвет надписи. Значение атрибута – код цвета в формате Hight Color, которым будет написан текст
  • “font” – индекс шрифта, которым будет написан текст.
  • “xcen” – Горизонтальное выравнивание. Возможные значения:
    • 0 – по левому краю
    • 1 – по центру
    • 2 — по правому краю
  • “ycen” – вертикальное выравнивание. Возможные значения:
    • 0 – по верху
    • 1 – по центру
    • 2 – по низу
  • “txt” – отображаемый текст
  • “txt-maxl” – максимальная длинна текста. Если передать в атрибут “txt”значение длинной больше чем значение этого атрибута, лишние символы в конце отрежутся.
  • “x” и “y” – координаты вставки текста
  • “w” и “h” – ширина и высота прямоугольника, в который вписывается текст.

— Поле с числовым значением.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “sta”
  • “bco” – цвет заливки фона. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “pic” – индекс картинки для фона. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “picс” – индекс вырезанной картинки для фона. Этот атрибут появляется при выборе значения “crop image” в атрибуте “sta”
  • “pco” – цвет надписи. Значение атрибута – код цвета в формате Hight Color которым будет написано число.
  • “font” – индекс шрифта, которым будет написано число.
  • “xcen” – Горизонтальное выравнивание. Возможные значения:
    • 0 – по левому краю
    • 1 – по центру
    • 2 — по правому краю
  • “ycen” – вертикальное выравнивание. Возможные значения:
    • 0 – по верху
    • 1 – по центру
    • 2 – по низу
  • “val” – отображаемое значение. Может отображать числа от 0 до 4294967295. Не умеет отображать отрицательные значения.
  • “lenth” –длинна числа как строки. Возможные значения от 0 до 10. При нуле – длинна числа определяется автоматически, в остальных случаях, если длинна числа переданного в как значение атрибута “val” больше значения “ lenth ” спереди числа дописываются недостающие нули, а если длинна числа переданного в как значение атрибута “val” меньше значения “ lenth ” спереди числа отрезаются лишние символы.
  • “x” и “y” – координаты вставки элемента
  • “w” и “h” – ширина и высота прямоугольника, в который вписывается число.

— Кнопка без фиксации.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “sta”
  • “bco” – цвет кнопки в не нажатом положении. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “bco2” – цвет кнопки в нажатом положении. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “pic” – индекс картинки кнопки в не нажатом положении. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “pic2” – индекс картинки кнопки в нажатом положении. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “picс” – индекс вырезанной картинки кнопки в не нажатом положении. Этот атрибут появляется при выборе значения “crop image” в атрибуте “sta”
  • “picс2” – индекс вырезанной картинки кнопки в нажатом положении. Этот атрибут появляется при выборе значения “crop image” в атрибуте “sta”
  • “pco” – цвет надписи на кнопке в не нажатом положении. Значение атрибута – код цвета в формате Hight Color.
  • “pco2” – цвет надписи на кнопке в нажатом положении. Значение атрибута – код цвета в формате Hight Color.
  • “font” – индекс шрифта, которым будет написана надпись на кнопке.
  • “xcen” – Горизонтальное выравнивание. Возможные значения:
    • 0 – по левому краю
    • 1 – по центру
    • 2 — по правому краю
  • “ycen” – вертикальное выравнивание. Возможные значения:
    • 0 – по верху
    • 1 – по центру
    • 2 – по низу
  • “txt” – текст надписи на кнопке.
  • “txt-maxl” – максимальная длинна надписи на кнопке. Если передать в атрибут “txt”значение длинной больше чем значение этого атрибута, лишние символы в конце отрежутся.
  • “x” и “y” – координаты вставки кнопки
  • “w” и “h” – ширина и высота кнопки.

— Прогресс бар. Отображает заполненную на заданное значение процентов линейку. Очень интересное решение реализовано при применении изображений. Есть два изображения. Например, термометра. На одном он пустой (0%), на другом он же полный(100%).

После привязки его к элементу прогресс бар в зависимости от заданного значения показывает часть первого изображения и часть второго.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “sta” – возможные значения: “solid color” и “image”
  • “dez” – направление. Возможные значения:
    • “horizontal” – по горизонтали
    • “vertical” – по вертикали
  • “bco” – цвет при при заполнении 0%. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “рco” – цвет при при заполнении 100%. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “bpic” – индекс картинки кнопки при заполнении в 0%. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “ppic” – индекс картинки при заполнении в 100%. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “val” – наполнение. Возможные значения: от 0 до 100.
  • “x” и “y” – координаты вставки прогресс бара
  • “w” и “h” – ширина и высота прогресс бара.

-Картинка

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “pic” – индекс картинки.
  • “x” и “y” – координаты вставки картинки
  • “w” и “h” – ширина и высота картинки.

— Вырезанное изображение.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “picс” – индекс картинки.
  • “x” и “y” – координаты вставки картинки
  • “w” и “h” – ширина и высота картинки

— Невидимая кнопка.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “x” и “y” – координаты вставки картинки
  • “w” и “h” – ширина и высота картинки

— Стрелочный индикатор. Отображает стрелку, повёрнутую на заданный угол.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “sta” Возможные значения: “solid color” и “crop image”
  • “bco” – цвет фона. Значение атрибута – код цвета в формате Hight Color. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “picс” – индекс вырезанной картинки на фоне. Этот атрибут появляется при выборе значения “crop image” в атрибуте “sta”
  • “val” – значение угла поворота стрелки от 0 до 360.
  • “wid” – толщина стрелки. Значение от 0 до 5.
  • “pco” – цвет стрелки. Значение атрибута – код цвета в формате Hight Color.
  • “x” и “y” – координаты вставки элемента
  • “w” и “h” – ширина и высота элемента.

— График. Элемент строит график по точкам, передаваемым ему кодом, исполняемым на панели или через UART. Поддерживает до четырёх графиков отображаемых одновременно. С моей точки зрения элемент ещё пока не доделанный. Причину такого мнения опишу ниже.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “dir” – направление построения. Возможные значения:
    • “left to right” – слева направо
    • “right ti left” – справа налево
  • “sta”
  • “ch” – количество отображаемых каналов. Возможные значения от 1 до 4.
  • “bco” – цвет фона. Значение атрибута – код цвета в формате Hight Color. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “pic” – индекс картинки фона. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “picс” – индекс вырезанной картинки на фоне. Этот атрибут появляется при выборе значения “crop image” в атрибуте “sta”
  • “рco0” – цвет графика канала 1.
  • “рco1” – цвет графика канала 2. Этот атрибут появляется при значении атрибута “ch” более 1.
  • “рco2” – цвет графика канала 3. Этот атрибут появляется при значении атрибута “ch” более 2.
  • “рco3” – цвет графика канала 4. Этот атрибут появляется при значении атрибута “ch” более 3.
  • “x” и “y” – координаты вставки графика
  • “w” и “h” – ширина и высота графика.

— Слайлер

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “mode” – направление слайдера. Возможные значения:
    • “horizontal” – по горизонтали
    • “Vertical” – по вертикали
  • “sta”
  • “psta” – режим рисования курсора слайдера. Возможные значения:
    • “solid” – прямоугольник залитый сплошным цветом.
    • “image” – в качестве курсора используется изображение.
  • “bco” – цвет фона. Значение атрибута – код цвета в формате Hight Color. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “pic” – индекс картинки фона. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “picс” – индекс вырезанной картинки на фоне. Этот атрибут появляется при выборе значения “crop image” в атрибуте “sta”
  • “рco” – цвет курсора. Этот атрибут появляется при выборе значения “solid” в атрибуте “psta”
  • “рic2” – индекс картинки курсора. Этот атрибут появляется при выборе значения “image” в атрибуте “psta ”
  • “wid” – ширина курсора.
  • “hig” – высота курсора.
  • “val” – значение соответствующее положению слайдера.
  • “maxval” – максимальное величина значения слайдера.
  • “minval” – минимальная величина значения слайдера
  • “x” и “y” – координаты вставки графика
  • “w” и “h” – ширина и высота графика.

-Переключатель с двумя фиксированными положениями.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “sta”
  • “bco0” – цвет переключателя в положении 0. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “bco1” – цвет переключателя в положении 1. Этот атрибут появляется при выборе значения “solid color” в атрибуте “sta”
  • “pic0” – индекс картинки переключателя в положении 0. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “pic1” – индекс картинки переключателя в положении 1. Этот атрибут появляется при выборе значения “image” в атрибуте “sta”
  • “picс0” – индекс вырезанной картинки переключателя в положении 0. Этот атрибут появляется при выборе значения “crop image” в атрибуте “sta”
  • “picс1” – индекс вырезанной переключателя в положении 1. Этот атрибут появляется при выборе значения “crop image” в атрибуте “sta”
  • “val” – положение переключателя. Возможные значения 0 и 1
  • “x” и “y” – координаты вставки кнопки
  • “w” и “h” – ширина и высота кнопки.

Теперь рассмотрим не отображаемые элементы. При добавлении на страницу они не добавляются на экран, а располагаются на специальной панели редактора.

— Переменная. Служит для использования хранения данных при расчетах, выполняемых в коде непосредственно на панели. В зависимости от типа хранит либо числовое значение, либо строковое

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “sta” — тип переменной. Возможные значения:
    • “Number” – переменная хранит числовое значение
    • “String” – переменная хранит строковое значение
  • “val” – числовое значение переменной. Этот атрибут появляется при выборе значения “Number” в атрибуте “sta”
  • “txt” – строковое значение переменной. Этот атрибут появляется при выборе значения “String” в атрибуте “sta”
  • “txt-maxl” –максимальная длинна строкового значения переменной. Этот атрибут появляется при выборе значения “String” в атрибуте “sta”

-Таймер. Вызывает вызов события “Timer Event” периодически через заданное время.

Атрибуты элемента:

  • “objname”
  • “vscope”
  • “tim” – период срабатывания таймера в миллисекундах. Возможные значения от 50 ms. до 65535 ms.
  • “en” – работа таймера. При значении 0 – отсчёт времени остановлен, при значении – 1 работает.

Поведение глобальных и локальных элементов.

Локальные элементы при отрисовке страницы, к которому они привязаны, всегда инициализируются значениями, присвоенными в момент разработки проекта. Во время отображения страницы эти значения можно менять с помощью кода исполняемого на панели или через UART, но при переходе на другую страницу все измененные значения атрибутов сбрасываются на установленные при разработке. Значения атрибутов глобальных элементов при переходе со страницы на страницу не изменяются.
Элемент “Waveform” (График) не работает в глобальном режиме и в любом случае ведёт себя как локальный. При переходе на станицу, к которой он привязан, он всегда отрисовавается пустым, и с настройками, установленными при разработке. Скорее всего, поскольку проект Nextion HMI достаточно молодой, этот элемент просто не закончен.

Написание кода исполняемого на панели.

Код, исполняемый на панели, и имеет событийную основу. То есть непосредственно код пишется в обработчиках событий элементов и исполняется при возникновении соответствующих событий.
Для начала рассмотрим события, происходящие на панели.

События страницы:

  • Preinitialize Event – событие происходит перед отрисовкой страницы.
  • Postinitialize Event – событие происходит сразу после отрисовки страницы.
  • Touch Press Event – событие происходит при нажатии на экран в месте свободном от других элементов. При нажатии на элемент событие вызывается у него.
  • Touch Release Event – событие происходит после отпускания предварительно нажатой области станицы свободной от других элементов.

Все элементы, кроме не отображаемых, имеют два обработчика события – нажатия и отпускания.

  • Touch Press Event – событие происходит при нажатии на элемент
  • Touch Release Event – событие происходит после отпускания предварительно нажатого элемента.

У элемента Slider (слайдер) есть событие “Touch Move” которое происходит при каждом перемещении курсора на оду позицию.

У элемента Timer (таймер) есть единственный обработчик события срабатывания таймера – «Timer Event.»

Команды операции и условные операторы, поддерживаемые панелью

Переход на страницу

page аргумент – перейти на страницу. В качестве аргумента может выступать либо имя, либо индекс страницы.
Пример – при нажатии на кнопку происходит переход на страницу page1 c индексом 1. Команда написана в обработчике события Touch PressEven:

page  page1

или

page 1

Запись или чтение значения атрибута

Чтение значения аргумента
имя элемента.аргумент
или
имя страницы. имя элемента.аргумент

Запись значения в аргумент
имя элемента.аргумент=значение
или
имя страницы. имя элемента.аргумент=значение

Пример: По нажатию кнопки значение аргумента “val” из поля с числовым значением с именем “n0” перепишется в аргумент “val” поля с числовым значением с именем “n1”. Так же из аргумента “txt” текстового поля с именем “t0” строка перепишется в аргумент “txt” текстового поля с именем “t1”. Все элементы находятся на странице с именем “page0”.

Преобразование типов
cov значение1, значение2, длинна где:

  • значение1 — атрибут источника например n0.val
  • значение2 – атрибут приёмника например t0.txt
  • длинна — длинна строки. При значении 0 – автоматическое определение. Если идёт преобразование из числа в строку — это длинна целевого атрибута, если строка преобразуется в число, это длина атрибута-источника.

Если типы атрибута источника и атрибута приёмника одинаковы будет выдана ошибка компиляции

Примеры.

  1. Значение атрибута “txt” (строка) текстового поля “t0” при нажатии кнопки преобразуется в число и записывается в аргумент “val” (число) поля с числовым значением “n0”
  2. Значение атрибута “val” (число) поля с числовым значением “n0” при нажатии кнопки преобразуется в число и записывается в аргумент “txt” (строка) текстового поля “t0”

Математические операции.

Поддерживаются операции сложения (+), вычитания (-), умножения(*) и деления (/).Необходимо учитывать что панель умеет работать только с целыми положительными числами.

Пример.

При нажатии кнопки начинает работать таймер и добавляет единицу к значению числового поля “n0”. При отпускании кнопки счёт заканчивается.

Настройки таймера “tm0”

Аргумент “tim” – 1000 ms. При работе таймера событие “Timer Event” вызывается 1 раз в 1000 миллисекунд.
Аргумент “en” – 0. По умолчанию таймер выключен.

Код в событии “Touch Press Event” копки.

При нажатии кнопки в значение аргумента “en” таймера “tm0” заносится 1. То есть таймер включается.

Код в событии “Touch Release Event” копки.

При отпускании кнопки в значение аргумента “en” таймера “tm0” заносится 0. То есть таймер отключается.

Код в событии “Timer Event” таймера “tm0”

При каждом срабатывании таймера к значению аргумента “val” цифрового поля “n0” добавляется единица и записывается в этот же аргумент.

Условные операторы.

Примеры записи:

if(t0.txt==”123456”)
{    
рage 1
}

Если значения атрибута “txt” текстового поля “t0” равно «123456» то переходим на страницу с индексом 1.

if(b0.txt==”start”)
{    
  b0.txt==”stop”  
} else
{ 
  b0.txt==”start”  
}

Если значения атрибута “txt” кнопки “t0” равно «start» то записываем в этот атрибут значение «stop» иначе записываем в этот атрибут значение «stop».

if(b0.txt==”1”)
{    
  b0.txt==”2”  
} else if (b0.txt==”2” )
{ 
  b0.txt==”3”  
}else
{ 
  b0.txt==”1”
}

Если значения атрибута “txt” кнопки “t0” равно «1» то записываем в этот атрибут значение «2» иначе: ( eсли значения атрибута “txt” кнопки “t0” равно «2» записываем в этот атрибут значение «3» иначе записываем в этот атрибут значение «1»).

Возможные операторы сравнения:

  • Для числовых значений
    • > больше
    • < меньше
    • == равно
    • != не равно
    • >= больше или равно
    • <= меньше или равно
  • Для строковых значений
    • == равно
    • != не равно

Вложенные “()” и операторы связи не допускается, например нельзя использовать такую конструкцию: if(j0.val + 1> 0). Для решения таких задач необходимо использовать переменные.

Поддерживаются вложенные “if” и “else if”.

Отладка проекта.

В состав Nextion Editor входит симулятор проекта. Для его запуска надо нажать кнопку “Debug” ()главного меню. При этом проект откомпилируется и откроется в симуляторе где можно будет проверить работу проекта.

Загрузка проекта в панель.

Для загрузки проекта в панель существует два метода.
Первый метод – через UART. Для этого необходим переходник USB -> UART. Подключаем его в соответствии с таблицой.

Nextion HMI USB -> UART
+5V +5V
RX TX
TX RX
GND GND

В редакторе нажимаем кнопку “Upload” ()главного меню. При этом проект компилируется и открывается окно загрузки.

Можно сразу установит порт, под которым в системе установился переходник, можно оставить автопоиск. Нажимаем “GO” и начинается загрузка проекта в панель.

В случае больших проектов, особенно с большими ресурсами в виде картинок и шрифтов время загрузки может достигать несколько минут. После окончания загрузки панель перезагрузится и перейдёт в рабочий режим.
Я пользовался только этим методом загрузки, но есть ещё один способ, с применением карты Miro SD.

Расскажу теорию. Карта должна быть отформатирована в формате FAT32. В редакторе нажимаем кнопку “Compile” (). В случае удачной компиляции в окне вывода результатов компиляции (7) не должно быть красных строк.

После этого в Главном меню открываем пункт “File” и выбираем “Open build folder”

Откроется папка со скомпилированными файлами проекта. Выбираем файл с именем нашего проекта и расширением “.tft” в головную директорию SD карты. Фай с таким расширением на карте должен быть один. Затем вставляем карту в отключенную от питания панель и подаём на неё питание. При подаче питания панель обнаружит у себя карту, и ели найдет на ней файл с расширением “.tft” начнёт загрузку проекта с неё. Процесс загрузки будет отображаться на экране. После окончания загрузки надо отключить питание от панели и извлечь SD карту.

Я, конечно, рассказал не все возможности панели Nextion HMI а только те с которыми сам столкнулся в процессе интеграции поддержки панели в программу FLProg. Более подробно о панели можно почитать на сайте wiki.iteadstudio.com/Nextion_HMI_Solution.

В следующих уроках я расскажу, как организовать взаимодействие панели Nеxtion HMI и Arduino используя программу FLProg.

Спасибо за внимание

Если эта публикация вас вдохновила и вы хотите поддержать автора — не стесняйтесь нажать на кнопку

Skip to content

The Nextion Editor GuidePatrick2022-12-24T04:04:41+08:00

Nextion Editor GuideNextion Editor ico

Introduction

This document goes through various features of the current Nextion Editor. The Nextion Editor is used to rapidly create Human Machine Interface GUIs for Nextion HMI devices. As such the GUI can be created within Hours instead of Weeks, and Days instead of Months. So while we won’t be covering basics such as opening a file, we will point out somethings that might prove helpful to know, or reminders need be made.

Note: Nextion Editor has indeed evolved since its early beginnings, so I would like to take a moment for a quick review. As time has passed, many additional features and bug fixes were incorporated. The Nextion Editor is not expected to retain every previous behaviours between versions exactly. With the new, then there are indeed new behaviours and new possibilities.

The pandemic had created global supply shortages and to meet these challenges while keeping with Nextion quality then second source components/ICs were indeed needed. This said, while elder devices only require firmware level code to communicate with primary sources ICs, the newer devices with secondary source ICs (visually identified with QR codes on the microSD slot) indeed require more recent versions of the Nextion Editor (v1.63.3 and later recommended) for the firmware to communicate with the secondary source ICs. As such, newer devices with secondary source ICs can not make use of elder versions of the Nextion Editor (such as v0.38, or LTS) before such firmware level code was incorporated into the Nextion Editor version firmware.

Since 2020, the newer Nextion devices may give a Data Error when trying to attempt loading a *.TFT file that was created with an Editor version prior to version 1.63.3 that does not have the ability to communicate with second source ICs. One would need to compile their project with a version 1.63.3 or later and use that *.TFT file to upload their project to the newer Nextion device.

Now mostly Historical, those original Nextion devices from 2015/2016 with the Itead logo on the PCB may require an intermediary upgrade only if all the Legacy conditions are met (see the Legacy FAQ, v0.42 intermediary TFTs are supplied in FAQ), otherwise when every condition is not met then such an intermediary is not required. Devices that were upgraded to a version of the Nextion Editor v0.29 and later can not return to an earlier version (v0.28 and before). Devices that were upgraded to a version of the Nextion Editor v0.38 and later can not return to an earlier version (v0.37 and before). Enhanced Series models require v0.33 or later, when Enhanced models were introduced. Intelligent Series models require v0.58 or later, when Intelligent models were introduced. Discovery Series models require v1.62.2 and later, when Discovery models were introduced. The Nextion Editor LTS Edition (Long Term Support) can only be used with elder Basic and Enhanced devices without second sources ICs. And of course, any newer devices with the QR code on the microSD card slot requires v1.63.3 or later.

This Editor Guide will refer exclusively to the new and current Nextion Editor. Where an item within the guide may be specific to a particular Nextion series, the following icons will be used to represent the series: For the Basic T Series , for the Discovery F Series , for the Enhanced K Series and for the Intelligent P Series

Requirements

  • * Windows Operating System (XP or higher). Users must know and be able to use their Windows OS. Windows OS support is beyond the scope of Nextion, so while Microsoft discontinues there support of earlier OSes, the current Nextion Editor does run on XP with the x86 .NET 3.5 and x86 2015 VC++ Redistributable. Users are expected to know their own development environment. Note: Installations on VMware and other Operating Systems may have been accomplished successfully, but is not officially supported and beyond the scope of any manual.
  • * As stated in the Note above, use of Nextion Editor v1.63.3 or later is required for newer Nextion devices with second source ICs, or a Data Error may occur when the *.tft file firmware can not communicate with the second source ICs
  • * .NET 3.5 Assemblies installed. When needed, download and install the x86 .NET 3.5 Assembles from the Microsoft Website [here].
  • * Ensuring the specific x86 Microsoft Visual C++ x86 Redistributables are installed and up-to-date resolved a rare issue for a couple users [here].
  • * A reasonable sized monitor for the model’s resolution you are designing for is only good sense. When designing for a 320×240 or 240×320 model then a standard monitor size is probably sufficient. However, if one is designing for 1024×600 or 600×1024 resolutions, then it would stand to good reason not to expect best ease from using an 800×600 monitor resolution. For comfort, then it is senseful to use a large enough monitor resolution so that your design canvas, tool panes, menus, and event panes fit for your designing comfort. And in the reverse, a large enough screen for for your development comfort when designing for the smallest of Nextion devices. It is not appropriate to blame the Editor software for your too small monitor when you really know you need more screen real estate.
  • * Basic programming skills are prerequisite. The Nextion Instruction Set is made up of ASCII text based commands inbound, and significant first byte binary Return Data. A component’s Touch Event “Send Component ID” can be used to defer programming tasks to the user’s MCU.
  • * As such, quickly creating an HMI GUI for Nextion does not demand extreme skills – but basic programming skill are expected. When programming logic Nextion side, then users should have a foundation in programming.
  • * Over 68,000 MCUs (any MCU with an internal UART module or two digital pins to bit-bang a Software Serial) can be used with Nextion in over 130 programing languages. MCU side programming is beyond the scope of Nextion and remains within the user’s domain and duty to know and understand their chosen MCU and chosen MCU side programming languages.
  • * Uploading your completed Nextion HMI project can be accomplished either by microSD card or over TTL Serial. As there are dozens of manufactures for each of these, it is the user’s domain and duty to know their device installation, configuration and operation.

Downloading the Nextion Editor

The latest version of the Nextion Editor can be downloaded from [here]. Earlier versions of the Nextion Editor can be downloaded from the Nextion Editors and Change Logs thread in the Announcement Forum (Register for the forum, confirm and then Login to use).

There are typically two versions of the nextion-setup available for download.

  1. 1) The EXE version is installed through the Windows MSI for a more automated installation. Only one version of the Nextion Editor may be registered at a time via the EXE version. When updating within the Nextion Editor, Auto Update will install the EXE version
  2. 2) The ZIP version can be unzipped into a user chosen folder and run directly from that folder. For maintaining multiple versions of the Nextion Editor, the ZIP version is recommended. When updating within the Nextion Editor, Manual Update will launch your web browser to the download page so you may download the ZIP version

Parts to this document

  1. 1) Theme Styles, Panes and Other Settings … <goto>
  2. 2) Nextion Editor Main Interface … <goto>
  3. 3) Debug Simulator Overview … <goto>
  4. 4) Uploading your Project your Device … <goto>
  5. 5) External Tools … <goto>

1. Theme Styles, Panes and Other Settings

1.1 Styles

The Nextion Editor can be set to a Blue or Black themed style (Style is found in the upper right corner).

1.2 Panes

Many of the panes can be adjusted on both size and their location. To resize, drag the splitter between panes and move to resize the panes. To move a pane to a more convenient location, drag the title of the pane and release on your preferred drop point. Panes can also be pinned to retain a fixed position or unpinned to collapse to an edge when not in focus. When needed, you can reset these and any Pane settings by selecting the Reset layout under the Setting menu.

1.3 Other Editor Settings

Other settings in the Nextion Editor can be configured in Configuration under the Settings menu. The default font of the Nextion Editor can now be changed to suit your taste. The default timeout of 100ms for the Debug Simulator can be adjusted from 20ms to 5000ms. Code hints, highlighting, description, tooltips and auto-complete can be set individually for the Editor and the Debug Simulator. Default path for eeprom and sd files can be customized to suit your taste. When needed, you can reset these settings by selecting the Reset layout under the Settings menu.

In the Display Tab of the Nextion Editor on starting the Editor, there is a section for listing the most Recent Projects. The number of recent projects tracked is by default 10, and can be increased. Right-clicking a project allows you to select from the following:

  • * Open the file: if the project file exists, then opens in the Editor
  • * Open the folder: if the folder exists, then opens the folder in Explorer
  • * Delete the current records: clears the highlighted recent projects from the list
  • * Delete the invalid records: clears non existent projects from the list
  • * Delete all the records: clears the recent projects list
  • * The number of recent project setting: allows you to adjust the number of projects tracked

2. Nextion Editor Main Interface

  1. 1) Title Bar … <goto>
  2. 2) Main Menu … <goto>
  3. 3) Toolbars … <goto>
  4. 4) Page Pane … <goto>
  5. 5) Toolbox Pane … <goto>
  6. 6) Attributes Pane … <goto>
  7. 7) Picture Resource Pane … <goto>
  8. 8) Font Resource Pane … <goto>
  9. 9) Audio Resource Pane … <goto>
  10. 10) Gmov Resource Pane … <goto>
  11. 11) Video Resource Pane … <goto>
  12. 12) Design Canvas (Visual Components) … <goto>
  13. 13) Non Visual Components … <goto>
  14. 14) User Event Code … <goto>
  15. 15) Output … <goto>
  16. 16) Display/Program.s … <goto>
  17. 17) Status Bar … <goto>

2.1 Title Bar

The Title Bar contains the path and filename of the HMI project file when an HMI project is loaded. When an HMI project is not currently loaded, you can:

  • * Open an existing HMI file using the Open toolbar button.
  • * Create a new HMI file using the New toolbar button.
  • * Load a TFT file into the Debug Simulator by pressing Debug.
  • * Upload an existing TFT file to your Nextion by pressing Upload.

2.2 Main Menu

File Menu

Here, Users can create a New project, Open an existing project, Save the current project, Save as to rename and save the currently loaded project, Close Project to close their current project, and Exit the Nextion Editor. Import Project will append an existing project into the current project – usually with resulting naming and renumbering issues. As such, it is recommended to either: a) load your project, adjust your device settings, and Save as under your new project name, or limit importing to individual pages if importing is required.

Clear Recent Projects used to clear the Project filenames in the Recent projects pane has been removed and is now accomplished in the Recent projects pane with context click and selecting Delete all records, or by managing the recent projects with more selectiveness.

Open Build Folder has been moved into TFT File Output.

With the new TFT File Output, users can select where the TFT file should be placed (which folder, sd card drive, other). A valid HMI without compile errors is required to generate a valid TFT output file. The option to open the output folder location in Windows Explorer can be made by clicking only open the output folder link. The old folder location C:\Users\Username\AppData\Roaming\Nextion Editor\bianyi will still contain previously compiled TFTs from elder Editor versions, and only if this is used as the TFT File Output location, will the new TFT for the current project be added to that folder.

The Backup Directory has been renamed to Version backup folder only keeps a copy of an older HMI project opened with a new version of the Nextion Editor launches Windows Explorer to the C:\Users\Username\AppData\Roaming\Nextion Editor\backup folder.

The Virtual EEPROM Folder located C:\Users\Username\AppData\Roaming\Nextion Editor\eeprom contains the eeprom.bin for the Enhanced/Intelligent series models. The default folder can be customized in Settings > Configuration.

The Virtual SD Card Folder located C:\Users\Username\AppData\Roaming\Nextion Editor\sdcard0 allows users of the Intelligent series models to copy project files here that will eventually be on their Nextion microSD card, allowing users to test their project in the Debug Simulator. The default folder can be customized in Settings > Configuration.

Tools Menu

Under the Tools menu, users can access the external tools Font Generator, GmovMaker, VideoBox and PictureBox. These are covered individually in Section 5 of this Guide.

Setting Menu

The Setting menu contains two items: Configuration and Reset layout.

In the Configuration menuitem, the user can choose for the Nextion Editor and the Debug Simulator if code should be highlighted or not, if Auto-Complete should be on, if the descriptions for instruction parameters should be on or not, if the tooltips should be shown when the mouse is over the toolbar buttons.

For serial data in the Debug Simulator, the timeout can be adjusted from its 100ms default value to a user selected value within the range from 20ms to 5 seconds.

For the new Intelligent Series, the user can choose if there should be a 3 second delay at screen edge before allowing the component position to escape to the outside of the canvas area. This is useful to be on, especially in the Basic, Discovery and Enhanced models as out of bounds positioning is not permitted and will cause the project to not compile.

For the eeprom/sd folder, the user can choose to use the default path, or can set their own custom path that is more suited to their system and workflow.

Transparent color replacement value defaults to the 565 color 0 (BLACK), and is useful when importing images into the Picture Pane to convert the transparent pixels to a desired color when transparency is not supported (ie: Basic, Enhanced and Discovery Series models).

Image format for the Intelligent Series defaults to the YUV422 standard, but can be set to the YUV420 standard when desired.

Finally, the default Font used for the Nextion Editor can be changed to suit the users taste. Currently, this default font effects both Editor wide as well as the Event code font. Resetting the font to the default Microsoft Sans Serif will return the Editor to its normal traditionally used font.

Reset layout will reset the Nextion Editor default panes back to their original positions. This is a useful starting point if you have somehow misplaced your pane or positioned it in some obscure unreachable position.

Help Menu

The Nextion Instruction Set is no longer available as a Tab in the Nextion Editor.
Selecting Instruction Set menuitem will launch the Nextion Instruction Set in your default web browser.
Selecting Editor Guide menuitem will launch the Editor Guide in your default web browser.

About Menu

Selecting About Nextion Editor menuitem in the About menu will show the about box with the version of the Nextion Editor. Clicking the link will take you to the Nextion website where you can access the forums and other documentation.
Selecting Check for new version menuitem in the About Menu will show the Update dialog when a new version is available (see Downloading the Nextion Editor at the beginning of this Guide), or a dialog informing that you have the most recent version.

2.3 Toolbars

Open, New and Save

These will Open an existing project, create a New project, or Save the currently opened project.

Compile

Use Compile to check for errors in the currently loaded project. Any Warnings or Error Messages will be placed in Output Pane.

Pay attention to any warnings as these will mean your project may not run as you expect. Pay attention to any error messages as they will need to be corrected before continuing. Error messages are descriptive, and if it is a code error then the user can click to jump directly to the coding error location.

Compile is more of a building and assembly process. This is only stated so that users do not make the wrong expectations of native machine code when making feature requests and/or Bug Reports. Nextion remains closed source.

A TFT file is no longer built and placed in the bianyi folder on Compile. To generate a TFT file, one has to use the TFT file output menuitem located under the File menu

Debug

The Nextion Editor contains a built-in Simulator that can be accessed via the toolbar Debug. To be clear this is not a precision emulator and is intended to be sufficient to assist in debugging a users project. It in no way is meant to replicate the Nextion device exactly. (Any Windows OS is already sufficient to make such precision unattainable). The Debug Simulator will be covered in more detail in Section 3 of this Guide.

If a project is not currently loaded in the Nextion Editor, Debug will open a dialog to open a compiled *.TFT file directly. This is handy for loading demos or sharing ideas without surrendering your original source code. Although the Debug Simulator can run a *.TFT file from any Nextion Series or model supported by the version of the Nextion Editor, it is important that the same version of Nextion Editor and *.TFT file is used to successfully simulate. (ie: an older v0.36 project TFT file can not be used with the current version of the Nextion Editor.)

Upload

Selecting Upload will launch an Open dialog to select a *.TFT file before the Upload to Nextion Device dialog. Ensure the Nextion is connected via serial (typically via USB to TTL adapter) before upload or the Port may not be available to select. Auto search feature will look for your Nextion’s reply to the connect instruction, but realize that data is being sent on all serial ports that are searched (and may interfere with the other connected serial devices). A better choice is to select the correct Port and Baud Rate. Proper configuration of Serial adapters, Windows drivers, device conflicts, etc is beyond the scope of Nextion support and remains the domain of user responsibility to know their used Operating System and devices.

Once Nextion has responded to the connect instruction, the upload process will begin. Do not interrupt this process until completed. If the process has been interrupted, resetting the serial port may be required. When a partial *.TFT file has been uploaded and uploading over serial is no longer an option, then the user will need to upload via the microSD method. Refer to Section 4 of this guide.

Copy, Cut, Paste and Delete

Users can select components or multiple components and then Copy, Cut, Paste or Delete as required. Paste contains a drop down option to in place paste which will copy without any vertical or horizontal offsets.

Lock and Unlock

Users can select components or multiple components and then Lock or Unlock as required. Locking prevents a component from being repositioned with the mouse until unlocked. A lock icon appears in the upper right corner of the visual components when locked that can interfere with visual inspection of your HMI design.

Undo and Redo

Use Undo and Redo to Undo the last operation, or to Redo the last operation undone.

The Component Layout Toolbar

For Renumbering components: Bring Top (Arrow Up) will take the selected component(s) and renumber to the highest .id on the page. Bring Bottom (Arrow Down) will take the selected component(s) and renumber to the lowest .id starting at 1 (page component is always 0) on the page.

For Aligning components: Align Left, Align Right, Align Top and Align Bottom will take a group of selected components (green ID labels) and bring the alignment to match the component with the blue ID label.

For Resizing components: Same Width, Same Height and Same Size will take a group of selected components (green ID labels) and set the size (width, height or both) to match the component with the blue ID label.

For Spacing components: Make horizontal spacing equal, Increase horizontal spacing, and Decrease horizontal spacing will take a group of selected components (green ID labels) and adjust the horizontal spacing between components using the component with the blue ID label as the baseline component. Likewise: Make vertical spacing equal, Increase vertical spacing, and Decrease vertical spacing will take a group of selected components (green ID labels) and adjust the vertical spacing between components using the component with the blue ID label as the baseline component.

Device

The steps to configure your HMI project for your Nextion Series and Model are usually done at the time of creating a New project. When you need to make changes, Device will launch the following window with the Device tab selected. First select the Nextion Series: T for the Basic models, K for the Enhanced models, and P for the Intelligent models. Then select your Nextion Model. For example: the Multi-touch Capacitive Nextion NX8048K070_011C, Select K for the Enhanced series and then the select the NX8048K070_011 Nextion Model.

Selecting the DISPLAY tab, the user can select the orientation and the Character Encoding. 0° is the native viewing angle for the selected model. Users can choose alternative orientations (90°, 180° or 270°) but this will not be the native viewing angle.

Character Encoding is default iso-8859-1. Select from the character encodings that make sense for your HMI project to best display your local character sets. There are a selection of single byte and double byte character sets available.

Currently supported Character encodings include:
ASCII, ISO-8859-X (1,2,3,4,5,6,7,8,9,11,13,15), UTF8,
GB2312, BIG5, KS_C_5601-1987, Shift-JIS, koi8-r,
Windows 874, 1255, 1256, 1257, and 1258

Note: An encoding is a character mapping of value to character. Computer systems and MCUs use numeric values and not characters. A byte numeric value 0x41 in single byte ASCII encoding will reference the character A. Your MCU will not send A, it sends byte 0x41 (which in many cases maybe mapped to the letter A), but does not explicitly mean 0x41 renders A in every encoding. A Byte value of 0xC4 can map to different characters in different encodings, or even be undefined (mapping to no character). While modern computers can do translations between many encodings, your MCU will likely not. It is useful to research the character encodings you are planning to use.

Note: While the Nextion Editor HMI project can only have one base character encoding. This does not prevent the inclusion of different encoded fonts within your HMI project. Building on the above explanation, when your MCU sends a byte 0xFF to the Nextion device, the component .font attribute is responsible for which Font resource the byte 0xFF is rendered in (provided the chosen font resource has a glyph to render and is not undefined).

If you desire to password protect your entire HMI project, selecting the project tab will bring up the Open Password Setting button. If an existing password exists, it will need be entered before a new password can be set. When a Password is lost, it is not retrievable. Fair warning is given: DO NOT LOSE YOUR PASSWORD. There is no recovery! A project with a lost password would need to be rebuilt! So, do not lose – or – do not use.

One-time update option will rename the *.tft file on your microSD card to a different extension after successful upload.  You can now also now choose to ignore your pictures (image resources) and fonts (library resources) at compile time.  While this is a small time saving step, it is recommended to turn these off when you are ready to create your final project compiled TFT.

For the Intelligent series, Memory file storage size for external picture resources is specified in Bytes.

ID

Selecting ID to will toggle if the component .objnames are displayed in the upper left region of the component space. Yellow labelled components have a .vscope local, while black labelled components have a .vscope of global. (Hint: Event code is never global). When selecting multiple components, green labelled components indicate multiple components have been selected, while the one blue labelled component will be used as the baseline component. To change the baseline component while the group is still active selected, simply click on the already selected component you want to become the baseline component.

Canvas Zoom

New to the Nextion Editor is the ability to Zoom the design canvas both in and out. Users can zoom from 20% to 600% using the slider, or increment steps using the + and – buttons on the ends of the slider. The value of the zoom is shown in percentage to the right of the Canvas Zoom. Clicking on the percentage zoomed allows you to reset the zoom back to an unzoomed 100% state. Note: Component dragging-by-edge (indicated by double ended arrow pointer) to move or resize components whether intended or accidental can cause an undesired snap-to effect in size and/or position where zoom is not at 100%. Calculation for the placement of component or edge must be to whole numbers and as such drag ending on partial-pixels can indeed effect component size, position or both.  In the event of undesired results, use the Undo (ctrl+z) to revert back to your previous unaltered state. Version v1.65.0 maintains edge-dragging to resize, a drag movement will not resize the component.

Project Startup Code

Selecting the C on the toolbar will open the Program.s tab in the Design Canvas area.  To return to the Design Canvas, click the Display Tab.  The Project Start Up code section is a newly introduced concept allowing for users to define and initialize additional int globals (such as sys0=0).  At the moment only int 32 bit signed integers are supported.  Additionally project start up code can be added in this section to be run before the HMI runs using Nextion Instructions.

Note: Nextion Preamble 0x00 0x00 0x00 0xFF 0xFF 0xFF NIS 7.19 and Nextion Ready 0x88 0xFF 0xFF 0xFF NIS 7.29 have been moved from firmware start notifications into Program.s as a printh instruction. Users can now choose to keep these notifications or discard by removing this printh line. Default values for dim, baud and recmod also prepopulate in Program.s as this is the recommended location for setting these variables (historically was recommended in Page Preinitialize Event before Program.s existed). Also important to note that once a page instruction or system variable dp assignment has been given the HMI will change to the desired page and will not return to Program.s to run instructions beyond the page change instruction.

Remark Line On / Remark Line Off

When in the Project Startup Code, using the Comment or Uncomment on the tool bar will comment the selected line(s) or uncomment the selected line(s) in the same manner as the Event Pane does with user code.

2.4 Page Pane

Every HMI project needs to have at least one Page. Pages can be created and imported into your HMI project through the Page Pane. A Page is created with Add, deleted with Delete, and copied with Copy. Insert will create a new page before the highlighted page. Use the Move Up and Move Down to renumber the page number within the Page Pane. Using Delete all (Trash) will delete all pages within the project.

Pages can be renamed to a maximum of 14 characters and the page names are case sensitive (avoid using space and other characters that can be code ambiguous as this could cause code parsing issues: Since the Intelligent Series, the Editor compile becomes more strict). To rename your page highlight the page, right click. and select Rename. Then enter your new name (it is recommended to press Enter to ensure the change takes place). Double clicking a Highlighted page name will also trigger the page renaming function.

The page Lock and Unlock functions are only accessed by right clicking the highlighted page name and selecting Lock or Unlock. If the page has been locked with a password, the password must be entered to access the components and event code. There is no password recovery should the password becomes lost, so don’t use or don’t use. As an example, the keyboard pages are imported as locked, but do not use passwords (the keyboard pages are also a good coding example to review). When keyboard pages are imported by the Nextion Editor component .key attribute, reset system page option is included in the context menu, which is used to reload the keyboard page and proper orientation in the cases where the keyboard page may have been edited or display orientation options may have changed.

Pages can be exported from one project to another project with Export page. This is the preferred way to share components and partial projects. Page files *.page can not be compiled on their own. If you want to export a page as locked or locked with a password, this must done before exporting.

To import a page, use Import page. Imported pages can be used independent if they are locked with a password, locked without a password, or unlocked. Locking is to protect the code. So as long as proper documentation about the page variables and functions accompanies the *.page file, an end user can use even a locked page. When a page is imported with naming conflicts, the affected conflicting names will be renamed. It is therefore relevant to perhaps select meaningful names. To import a copy of one of the keyboard pages, one can either import the *.page file directly or use the .key attribute of a Text, Scrolling Text, xFloat or Number component.

In an HMI project a page is a localized unit. When changing pages, the existing page is removed from memory and the requested page is then loaded into memory. As such components with a variable scope of local are only accessible while the page they are in is currently loaded. Components within a page that have a variable scope of global are accessible by prefixing the page name to the global component .objname.

As an Example: A global Number component n0 on page1 is accessed by page1.n0. A local Number component n0 on page1 can be accessed by page1.n0 or n0, but there is little sense to try access a local component if the page is not loaded. Only the component attributes of a global component are kept in memory. Event code is never global in nature.

A Page always contains a page component, and this page component will always have an .id of 0. Making the page component global, does not make the components within a Page global – just the few page attributes of the page component. The page component .id used with the b[.id] component array is not the page index number used with the p[index] page array.

A Page component can have a background of either : Solid color, image background, or no background. An image background should use a fill screen image to avoid calling non-existent data. No background will show the current page components over top the last unloaded page, this must be used with caution. No background on a no background, on a no background soon causes unwanted side effects. There is a hard limit of 250 components allowed per page, and theoretically up to 254 pages per project (likely resources will be depleted before any page254 is reached).

Built-in-Keyboard Pages

Nextion Editor now has four different built-in-keyboards that can be added to a project.  This allows for Text, Scrolling Text, Xfloat and Number component .txt and .val to be changed using a built in keyboard by the device user at runtime.  In order to add a built-in-keyboard to your project, the component must first be set to .vscope global, second the .key attribute needs to select your desired keyboard.  Selecting one of the keyboards will add the keyboard page to your project.  Choices are full qwerty style (keybdA), numeric keyboard (keybdB), speed dial style (keybdC), and Chinese Input (Pinyin) style (keybdAP).  The associated keyboard will load an appropriate font if not already included in the project and the keyboard page for the model size and orientation.   Should you choose to change model size or orientation, use the context-menu (right click) for the keyboard page and select Reset System Page to reload.

Keyboard pages are first loaded locked.  You can unlock the keyboard page by using the context-menu (right click) the keyboard page and select unlock.  Do so with care.  You can then review the code within the keyboard page and choose to modify it when you have reviewed and have understanding what they keyboard page is doing.  Caution:  Selecting to Reset System Page will abandon all your modification changes made to your customized keyboard.

For the Chinese Input (Pinyin) keyboard, the HMI project should be encoded using gb2312, this is currently the only supported encoding.

2.5 Toolbox Pane

The Page component not listed above is always created when the new Page is added to the Page pane. The page component will always have an .id of 0 and is always the bottommost layer. New page effects and swipe-to-change-page capabilities are added for the Intelligent series. There is a hard limit of 250 components allowed per page.

Many components have multiple .sta choices of
– crop image (pulls background from .x and .y location of a user chosen picture resource)
– solid color (sets background to be a user chosen 565 color)
– image (text if any will be drawn over the user chosen image)
– transparency (pulls background from underlying layers for transparent pixels)

Many components have multiple .style choices of
– flat (no lines will be added around edges)
– border (lines will be drawn around edges)
– 3D_Down (lines will be drawn to yield impression of lowered)
– 3D_Up (lines will be drawn to yield impression of raised)
– 3D_Auto (lines will be drawn Up/Down according to state)

Many components have multiple text alignment and placement options
– .xcen of Left, Center or Right
– .ycen of Top, Center or Bottom
– .spax will add extra blank pixel spacing to right of each character
– .spay will add extra blank pixel spacing to bottom of each character
– .isbr for multi-lined (set to true) or single line (set to false)
– .pw for masking (Character is off, Password will mask with an asterisk)

For the Intelligent Series, most components have new capabilities

  • repositionable by assigning .x and .y values, or by move instruction
  • user draggable at runtime by setting .drag
  • alpha channel blending (fading effect) by setting .aph attribute
  • additional attributes not available for the Basic, Discovery or Enhanced component
  • and other effects found in the .effect attribute
  • NOTE: with many more customizable attributes for the Intelligent Series components, it is wise to click the attribute in the Attribute Pane (see Section 2.6) for a full attribute description. ie: Intelligent Series Gauge .vvs2 attribute now controls the foot length of the gauge needle (attribute not available for the Basic, Discovery or Enhanced Series).

The Text component is a highly customizable component. The Text component has the .pw attribute for masking (Character is off, Password will mask with asterisk) and the .key attribute for integrating one of the included example keyboards (must be set to .vscope global before use).

The Scrolling text component combines an integrated timer component with a text component. The .pw option is not available with this component. The .key attribute allows for integrating one of the included example keyboards (must be set to .vscope global before use). There is a hard limit of 12 timer components per page within your project.

The Number component is used for signed 32-bit integer values. The .lenth (as spelled) sets the number of digits shown (useful for leading zeros). The .format attribute allows for a choice of integer, currency (comma separated every three digits, not float values), or hexadecimal. Input should be in integer or hexadecimal. The .key attribute allows for integrating one of the included example keyboards (must be set to .vscope global before use).

The Xfloat component is used for signed 32-bit integer values. The .vvs0 sets the number of digits shown to the left of the decimal (useful for leading zeros). The .vvs1 sets the number of digits shown to the right of the decimal. The .key attribute allows for integrating one of the included example keyboards (must be set to .vscope global before use).

The Button component is again highly customizable and integrates text in a momentary manner. Use text, images and event code to suit tastes.

The Progress bar component is for progress, thus a valid range of 0 to 100 to represent the percentage of progress. (Please no more requests to extend the range, even if many may give 110% effort). Best effects for progress are attained using images.

The Picture component will allow any picture resource to display in the Picture component. Example p0.pic=3. It is important that the picture resource matches the user defined size in .w and .h or the picture resource will over draw the picture component boundaries, or incorrectly insert adjoining data. The Picture component is useful to represent multi-states and animation sequences. Note: when you want a background picture to a Page, do not create a full screen sized Picture component over top the .sta solid color page: This will likely result in flickering on redrawing. Rather, set the page to .sta image and set the now exposed .pic attribute to the desired Picture Resource image. In this manner you achieve a page background image without the background being the cause of flicker.

The Crop component will replace its boundaries with the same location and boundaries from the picture resource pointed to with .picc. It is highly recommended that the picture resource being used is a full screen image to avoid errors (must be fullscreen image). The Crop component is useful to represent states.

The Hotspot component is a user defined touch spot to its overlaying region. At a 2 pixel by 2 pixel region, it makes for a useful code holder to be later called by the click instruction – thereby creating a user defined function. As a Hotspot, it turns any image area beneath into a button, such as in creating a customized keyboard.

The TouchCap component is a non-visual component that stores in its .val attribute the .id value of the last component touched (pressed or released). Even though the TouchCap is a non-visual component it has both Touch Pressed and Touch Released events that are triggered on the internal setting of the .val value, this is useful to trigger code in the TouchCap events on a touch event (pressed or released) as would be the case in any other visual component. Only one TouchCap component will be useful on a page – if there are two or more TouchCap components on a page, the TouchCap component with the highest .id value will supercede any TouchCap component with a lower .id value. Note: A TouchCap Send Component ID checkbox will always reset to the unchecked state as it is never this component that triggered the physical touch. Rather, use the individual component’s Send Component ID checkboxes or mimic a touch event using print statements. Touch Event format is listed in NIS 7.21
(ie: printh 65 prints dp,1 prints tc0.val,1 printh 00 or print 01 and printh FF FF FF).

It is also note worthy to mention as a reminder: Nextion Resistive devices have only process a single touch – meaning first component pressed will be registered and no other component can register until the first component pressed is released. Nextion Capacitive devices are multi-touch devices registering up to 5 different touch components and they are registered in the order of pressed and released as they happen in sequence they occur up until when the 6th component is pressed and the sixth component will not register. This complexity is simply the nature of multi-touch and requires a higher degree of workflow planning for precision execution – Nextion still remains consecutive processing of events and a “next-event” will not be processed until the current event has completed.

The Gauge component is a full circular component with value in degrees. This means a range of 0 to 360. In Basic, Discovery and Enhanced series: Gauge components are not useful for stacking (example: a three handed clock), as the redrawn gauge will overwrite any lower gauge. The gauge component is always a square in nature. Semi-circular gauges at the screen’s edge are not achieved with the gauge component. In the Intelligent series: a stackable gauge with highly customizable needles and out of bounds positioning can achieve many effects not possible in the other series.

The Waveform component is used to plot y axis data points on up to 4 channels. Waveforms are never global: in that adding datapoints with add/addt can only be done when waveform is on the active current page. Waveform .vscope of global allows plotted data to be maintained between page changes. Waveform .vscope of local, the data points are not retained, changing pages away and back will revert the waveform to an emptied state. Up to 4 waveforms can be used on a single page. The Waveform component is limited to a y axis data range of 0 to 255 or 0 to waveform height -1. As a data point is added, it will consume one column, with the next data point using the next column. Recent changes now allow a variable to be used in the add command. Example add 1,0,h0.val. The addt command becomes useful to refill the waveforms on page load (such coding remains within the user domain).

The Slider component can be horizontal or vertical. The slider has the added event code for Touch Move, useful for providing updates to the sliders current position. Best results are attained with images. Slider length includes the size of the thumb as well as the range (often overlooked in calculations). Snapping a slider to its value position can be achieved with h0.val=h0.val where slider .objname is h0.

The Timer component is not expected to be a high precision interrupt driven component. It is however useful for queueing reoccurring event code after elapsed .tim has expired. As code is sequentially processed, it is very easy for the time to process the requested user event code to exceed the .tim intervals and therefore not interrupt driven (to avoid such stack overflows) and not high precision. There is a hard limit on the maximum number of timers running in a single page, this limit is 12. Beware that the scrolling text component integrates 1 timer. Timer attributes can have a variable scope of global, event code is never global. As such timer code can only be triggered within the current page they are designed in. As the timer is a non visual component, they are added below the Design Canvas.

The Variable component is a non visual component and also added below the Design Canvas. Variables are either 32 bit signed numeric or string content can be selected with the .sta attribute at design time.

The Dual-state button component is an expanded Button maintaining its toggling state between press/releases.

The Checkbox component is another example of a lightweight dual-state component with less customization and lower memory usage.

The Radio component is yet another example of a lightweight dual-state component with little customization and lower memory usage. Obtaining grouping is achieved via user code (remains in the user domain).

The QRcode component is used to generate a 2D scanable QR. It is limited to a byte maximum for the .txt_maxl attribute of 84 (of up to a max 154 bytes) on Basic T models and 192 bytes on the Enhanced K and Intelligent P models. The QR component will consume some user HMI SRAM when included in an HMI project to facilitate the QR rendering.

New components for the Intelligent series

The Switch component is an expanded dual-state combining text and graphics.

The ComboBox component is used to present an expandable/collapsible selectable list with the .path attribute holding options one per line.  The number of selected item held in .val and .txt holding the text of the selected item.

The TextSelect component is used to present a cyclic spinner with .path attribute holding options one per line. The selected item number in .val and .txt holding the read-only text of the selected item.

The SLText component is used to present a scrollable textbox with .txt holding multiline data. The position of the list in pixels can be set through the .val_y attribute.

The DataRecord component is used to present a dataset in a scrollable table.  DataRecord supports up to 12 fields per record.   DataRecord incorporates 4 methods .insert(), .delete(), .up() and .clear().  Configuring DataRecord attributes for your application requirements will need be thoughtful at your HMI design time.

The FileBrowser component is used to present a folder and file structure tiled in a filter capable browser.  The .dir attribute holds the folder path, and the .txt attribute holds the selected filename.  FileBrowser incorporates an .up() method to return to previous folder. Be sure to ensure an appropriate font has been included to your project for filenames to be displayed.

The FileStream component is a non visual component for working with a file, it incorporates 5 methods .open(), .close(), .read(), .write() and .find().  A file is of finite size when user creates the file, appending beyond the file end is not supported.

The Gmov component is used to present an animation, with up to 16 Gmov components on an HMI page.  Use the GMovMaker Tool to create an animation in the Nextion *.gmov format using supported *.jpg, *.bmp, *.png and *.gif source files.  The Gmov component contains an additional Play completed Event to trigger user code at the end of each iteration of the animation.

The Video component is used to present a movie, with up to 6 Video components on an HMI page.  Use the VideoBox Tool to convert a movie into the Nextion *.video format. The Video component contains an additional Play completed Event to trigger user code at the end of each iteration of the Video. Use the .from attribute as external file and .path attribute to use *.video files stored in ram or on Nextion’s microSD card.

The Audio component is used to present wav files that are stored in ram or microSD card.  Use the VideoBox Tool Audio tab to create audio resources in the Nextion *.wav format. The Audio component contains an additional Play completed Event to trigger user code at the end of each iteration of the Audio. Use the .from attribute as external file and .path attribute to use *.wav files stored in ram or on Nextion’s microSD card. Note: Nextion Audio capabilities is 2 Channel with 10 band equalizer with output to a mono speaker. See Instruction Set play instruction, and system variables volume, audio0/audio1, eql/eqm/eqh, and eq0..eq9 in NIS Section 6.

The ExPicture component is used to present pictures that are stored either in ram or on microSD card.  Use the PictureBox Tool to create picture resources in the Nextion *.xi format that can be stored in ram or on Nextion’s microSD card. ExPicture can display images that are in the same selected orientation as the HMI and either Nextion’s *.xi format or JPEG Baseline DCT only.

To add any of the above components to the currently design page, simply click on the component and it will be added with its .id set to the number of components on the page. All components within a page are listed in .id ascending order in the Component Drop down in the Attributes Pane. Then continue with placement and adjustment of .attributes as desired.

2.6 Attribute Pane

The Attribute Pane contains the list of components included within the current design page in the Component drop down. Clicking on a component, or selecting it from the drop down will display the component’s available attributes. The left side contains the attribute name, the right side contains the attributes current value. Clicking on an attribute will display the attributes meaning and valid range/options at the bottom of the Attribute Pane. Double clicking a field with bring up resource editor for the attribute if attribute has such (ie: .pco opens color picker, .pic opens picture chooser).

Any attribute in black is read only at runtime (with the exception of .objname which remains inaccessible). Any attribute in green can be both read and changed by user code at runtime. Empty unassigned attributes values or invalid attribute values will need to be resolved before a successful compile can be achieved. When renaming a Components .objname: avoid using space and other characters that can be code ambiguous as this could cause code parsing issues.

Page name prefixing is suggested to access a global component’s attributes on another page.
– example: page0.va0.val
Page name prefixing is not required to access a local component’s attribute on the current page
– example: va0.val

Attributes that have ranges are evaluated in full during Nextion’s parsing of a complex expression and as such care is required. Nextion is stated as simplex expression, although these rules are often bent. Use care.
– example: gauge z0 with a .val range of 0 to 360.
z0.val=va0.val+step.val%360
Should va0.val+step.val exceed 360 the assignment fails before arriving at modulo 360.
– this is the nature of simplex expressions (think assembly language), and bending the rules has side effects.

The various combinations of attribute choices provides a wide range of expected behaviours with too many combinations to cover in any manual(s). This combined with the Nextion Instruction Set creates the opportunity for very powerful HMIs.

There is an HMI hard limit for a combined tally of attributes and user code of 65534.

2.7 Picture Resource Pane

Pictures are imported into your HMI project through the Picture Resource Pane. A picture is added with Add, deleted with Delete, and swapped with Replace. Insert will add the imported pictures before the highlighted picture. Use the Arrow Up and Arrow Down to renumber the picture resource number within the Picture Resource Pane. Using Trash will delete all pictures within the pane. Note that Delete will not delete a picture resource if it is being used with a component.

The accepted picture types to import are *.jpg, *.png, non animated *.gif and *.bmp files. When importing a picture, the picture is converted into the 565 16 bit color format used by Nextion. In Basic and Enhanced models: Nextion is not a graphics card, as such transparency and in picture animation is not supported. In native 16-bit color, picture resources consume 16 bits per pixel, or width x height x 2 bytes.  In Discovery models: some image compression is achieved breaking the traditional 2 byte per pixel formula and allowing more pictures in the same amount of flash compared to Basic and Enhanced models.  In Intelligent models: Nextion now supports transparency and configurable image compression allowing more picture resources for the same space, the 2 bytes per pixel formula does not apply.

Exporting a picture resource is accessed by highlighting a the picture resource, right clicking and selecting Export. The available picture formats for export are *.jpg, *.png and *.bmp as per the resource being exported. Note that *.jpg may save space but is a lossy format: once the data is lost, it is lost. Note that exporting pictures is with the naming convention picture resource #.format. Exporting will no longer overwrite a pre-existing file as it once did, but will now append a _# format to the filename portion where the higher appended number is the latest exported.

When using cropping, a full screen image is strongly recommended for the background. This avoids pulling data from non-existent space – which will resemble randomized colors (data from other locations). Cropping can consume more cycles than using a picture, using a picture will consume more cycles than solid colors. When cycle time becomes to high to render, tearing and flickering will be the sign. Nextion is an HMI device and not designed for HD multi-media and streaming. That said, amazing effects can still be achieved with purposeful programming.

A picture resource has the following limitations:
1) longest edge can not exceed 4080 pixels
2) width x height can not exceed 614400 pixels

Assignment of the picture by code at runtime would look like:
p0.pic=1ÿÿÿ over serial, or as p0.pic=1 inside an event as code.

2.8 Font Resource Pane

The ZI Font Resource is very important! If any visual component used in the user’s project contains a .txt or .val attribute, then at least one font must exist in the project. If a user wants to use various size of styled fonts in their HMI project, they will need to generate a ZI Font file for each style and size they will use. For most users this will mean starting with a ZI Font generated with the built-in Font Creator (covered in the Menu section above).

These *.zi font files will need to be added into the ZI Font Resource Pane. Each ZI Font Resource will show the font resource number, it’s given name user gave at creation time, it’s size in pixels Width X Height, it’s character encoding, number of characters in the set and the size in bytes the font contributes to the HMI project’s overall filesize. The appropriate *.zi font can then be selected by its number and assigned in a visual components .font attribute. Note that the design size of the visual component is set at design time and can not be changed at runtime.

Assignment of the font by code at runtime would look like:
t0.font=1ÿÿÿ over serial, or as t0.font=1 inside an event as code.

Properly formed monospaced ZI font resources from v0.53 (and prior) will have a width that is either equal to the height or a width that is half the height. Height will always be a multiple of 8 from 16 to 192. ZI fonts are monobit (pixel is either on or off) and Fixed Width. Hint: Generating a proportional font like Arial where W and @ are 24×24 and squeezing into a 12×24 space is like pouring 2 litres into a one litre bottle and expecting all 2 litres have been saved. Fonts that do not conform to the ZI size formula just stated can indeed have issues when it is rendered on the Nextion device.

With the introduction of the Intelligent Series, an anti-aliased non-fixed width font can now be generated. Be mindful that the max visual space required for characters of an anti-aliased proportional font is not width x qty as it was with the elder ZI fixed width font. Proportional fonts such as Arial contain characters of varying width (W is indeed wider than l).

A ZI font resource can be viewed by selecting the font and double clicking the selected font. Subset ZI fonts can be redefined and regenerated with Change Font button at the bottom of the Font Preview window. Trash will Delete all loaded ZI Font Resources. Multiple *.zi fonts can be imported with Add. A font must not be associated to a component to remove with Delete. A font can be swapped out with a different font using Replace. Insert will import the font before the highlighted font. Use the Arrow Up and Arrow Down to renumber the font resource number within the ZI Font Resource Pane.

Exporting a font resource is accessed by highlighting a the font resource, right clicking and selecting Export. Note that exporting multiple fonts is with the naming convention font resource #.zi. Exporting will overwrite a pre-existing file.

2.9 Audio Resource Pane

Audio resources are imported into your HMI project through the Audio Resource Pane. An audio resource is added with Add, deleted with Delete, and swapped with Replace. Insert will add the imported audio resource before the currently highlighted audio resource. Use the Arrow Up and Arrow Down to renumber the audio resource number within the Audio Resource Pane. Double clicking on a selected Audio resource will preview/play the audio file in the Nextion Editor. Using Trash will delete all audio resources within the pane. Note that Delete will not delete a picture resource if it is being used with a component.

Use the VideoBox tool in the Tool menu to assist with converting your audio resource to ensure a usable resource.

2.10 Gmov Resource Pane

Gmov resources are imported into your HMI project through the Gmov Resource Pane. A Gmov animation is added with Add, deleted with Delete, and swapped with Replace. Insert will add the imported Gmov resource before the currently highlighted Gmov. Use the Arrow Up and Arrow Down to renumber the Gmov resource number within the Gmov Resource Pane. Using Trash will delete all Gmov resources within the project. Note that Delete will not delete a Gmov resource if it is being used with a component. Double clicking on a selected Gmov resource will preview/play the Gmov resource.

Use the GmovMaker tool in the Tool menu to assist with creating your Gmov resource and ensure a usable resource.

2.11 Video Resource Pane

Videos are imported into your HMI project through the Video Resource Pane. A picture is added with Add, deleted with Delete, and swapped with Replace. Insert will add the imported pictures before the highlighted picture. Use the Arrow Up and Arrow Down to renumber the picture resource number within the Picture Resource Pane. Using Trash will delete all videos within the pane. Note that Delete will not delete a picture resource if it is being used with a component.

Use the VideoBox tool in the Tool menu to assist with converting your video resource.

2.12 Design Canvas

This is the main design space for the visual/touch components for the current Page. The Page’s page component is always .id 0 and always the most back layer. The mouse coordinates are displayed on the Status Bar aiding in precision placement. Selected components can be moved in one pixel offsets using the keyboard arrow keys. For best precision, use the component’s .x and .y attributes. Components selected with the left mouse click can be moved by dragging. Right clicking for context menu has the traditional cut, copy, paste, in place paste, delete, lock and unlock as well as grouping functions Create Group and Delete Group. Grouping will allow for multiple components to be reposition as if one component, another useful feature. Resizing a component can be achieved via edge dragging on any edge. There is a limit of 250 components (visual and non visual) allowed per page.

2.13 Non Visual Components

A Page’s non visual components (Variable, TouchCap, Timer, Audio and FileStream) will be listed in the area under the Design Canvas. This area is not displayed if no non-visual components are used in the page. There is a limit of 250 components (visual and non visual) allowed per page.

2.14 User Event Code

User Event Code can contain any valid Nextion Instruction. This section will not teach programming, but will quickly give an overview of the various types of Events where inserting user code is available. Event code is always local to page and never global.

Almost every component has the Touch Press and Touch Release events.
– The Touch Press Event includes a Send Component ID checkbox that when checked sends the 0x65 Return Data over serial on physical press. User code is run on either physical press or via the click command.
– The Touch Release Event includes a Send Component ID checkbox that when checked sends the 0x65 Return Data over serial on physical release. User code is run on either physical release or via the click command.
– The Send Component ID 0x65 Return Data over serial action can not be triggered by the click command. This is reserved for an end-user physical action received through the touch sensor. The click command will only trigger running the user event code.
– The Nextion Instruction printh command can simulate 0x65 Return Data (Actual or spoofed)

The Page component contains both Touch Press and Touch Release as well as
– The Preinitialize Event user code is run before the loading of the HMI designed page.
– The Postinitalize Event user code is run after the loading of the HMI designed page.
– The Page Exit Event user code is run as last event before a Page change
Note: .sta global values will persist, while .sta local values return to their designed state.
Note: Page component Pre and Post initialize Events are not triggered on exiting sleep, rather the components are visually refreshed to render the visual screen space to its wake state. Pre and Post Initialize events are triggered when entering a page. If page initialize events are required when exiting sleep, consider using the purposefully designed wup system variable.

The Slider component contains Touch Press and Touch Release as well as Touch Move.
– The Touch Move Event user code is run during drag of thumb when slider changes values.
– The Touch Move Event does not have a Send Component ID to avoid serial overflow.

The Timer component only contains the Timer Event for user code.
– Refer to the Timer component in the Component Pane section for more details

The Gmov, Audio and Video components contain the additional Play Completed Event.
– the Play Completed Event is run after each iteration of the sequence completes

Nextion Return Data is returned after the end of command execution
– it would otherwise not be wise to predict an outcome before the end.

There is an HMI hard limit for a combined tally of attributes and user code of 65534.

2.15 Output

The Output Pane contains details on the build process when Compile/Debug/Upload is selected. Compile needing to occur first, the user HMI is assembled into a usable TFT file for the selected Nextion Model. The first four lines of the output will list the total amount of Available Memory, Global SRAM Memory consumed by the HMI project, and then statistics for the total amount of Flash space the picture resources consumes, followed by the total amount of Flash space the ZI Font resources consumes. For the Intelligent series: a line will be displayed for each Gmov, Video and Audio with the total amount of Flash space each resource group consumes.

The build process then goes through the project sequentially page by page. At the end of a successful page build, the page Memory stats are listed Global+Local=Total. Should a page not build successfully, the offending page is the last listed+1.
Warnings listed in blue (such as when using the not recommended layering techniques, it will compile, but warn of potential unexpected behaviours), Errors listed in red (this will not compile, and the build process halts). Note: Do not upload a zero byte *.tft file.

File Size must be small enough to fit in your Model’s Flash size. See the Status Bar or your Datasheet for your model’s Flash size. All pages’ Total Memory usage must be small enough to fit your model’s HMI allotted SRAM. See the Status Bar or your Datasheet for your model’s HMI allotted SRAM.

Due to the nature of flash, it is possible that a compiled filesize may be under the MB size (ie: 1677216 bytes) and still be shy of the available and usable Flash on the Nextion Device. Nextion may report on upload the File is too big – this is not a hardware error but the working nature of Flash. Some allowance for wear-leveling and unusable flash pages have to be made, and even more so over time.

2.16 Display / Program.s Tabs

Use the Display Tab to show the Design Canvas
Use the Program.s Tab to set project global variables and project start up code. Variable declarations are made first, followed by code, and finally the power on start page. Code after a page change to the start page can never be executed as the start page will never return back to the start to complete the section after page change line. As of v1.65.0, the Nextion Preamble (NIS 7.19 and NIS 7.29) have been moved from firmware to the Program.s tab as a printh statement allowing the user to have choice if this startup notification is given or perhaps user customized. It is recommended to set baud, dim and recmod in Program.s rather than in Page Preinitialize events.

2.17 Status Bar

The Status Bar at the bottom contains three segments. The character encoding, the quick details of the Nextion Model selected, and the Design Canvas mouse coordinates. Clicking on Encoding will launch the DISPLAY tab of Device Settings. The Nextion Model details provide quick design specifications – limits of Project SRAM and Flash is useful to be mindful of.

3. Debug / Simulator Overview

  1. 1) Simulated Nextion … <goto>
  2. 2) Operations Menu … <goto>
  3. 3) Command Redirection … <goto>
  4. 4) Input Encoding … <goto>
  5. 5) Instruction Input … <goto>
  6. 6) Simulator Return … <goto>
  7. 7) User MCU Return … <goto>
  8. 8) Input Selection … <goto>
  9. 9) Connected Nextion Identification … <goto>
  10. 10) Waveform Generator … <goto>
  11. 11) Waveform Generator Options … <goto>
  12. 12) Nextion Address … <goto>
  13. 13) Simulator Backlight and Sleep … <goto>
  14. 14) Saved Nextion Input … <goto>

3.1 Simulated Nextion

  • This is a simulation – this is not an emulation.
  • Purpose of the simulation is to aid in debugging commands
  • Timers will not be precision under any Windows OS
  • RTC is simulated, GPIO is not simulated
  • EEPROM is simulated with eeprom.bin in Virtual EEPROM Folder
  • microSD card is simulated with files in Virtual SD Card Folder
  • Note: EEPROM generally adheres to 4 byte boundaries when writing
    Users may write to any address, but should care for data until boundary.

3.2 Operations Menu

  • Synchronize RTC time and Reboot (for each Simulator and Device).

3.3 Command Redirection

  • Simulator only, Nextion device only, or both.
  • Only one (Nextion device or User MCU) can be connected at a time
    When one is selected, the other is not available.

3.4 Input Encoding

  • Character Encoding to use for input

3.5 Instruction Input

  • Text command input of any non-block Instructions (excludes if, for and while)
  • Use the CRC checkbox to send the CRC (mode 1) with instructions
  • Toggle hex mode to ensure byte precision in input.
    (Answers the question of how to input less frequently used characters)

3.6 Simulator Return

  • Any Return Data or print commands from Simulator will display here
  • Expected to be sufficient to aid in the debugging process
  • Not expected to be full trace logs (Simulator – not emulator)
  • View in Hex or String format
    View Line by Line (ÿÿÿ terminations), or by Total bytes in Hex
    Context Menu (right click) to: Copy HEX, Copy STR, Copy HEX+STR

3.7 User MCU Return

  • Any Return Data or print commands from Nextion/MCU will display here
  • Expected to be sufficient to aid in the debugging process
  • Not expected to be full trace logs (Simulator – not emulator)
  • View in Hex or String format
    View Line by Line (ÿÿÿ terminations), or by Total bytes in Hex
    Context Menu (right click) to: Copy HEX, Copy STR, Copy HEX+STR

3.8 Input Selection

  • Keyboard input is the default simulator input method.
  • Cut, Copy, Paste and Delete added to right click context menu.
  • Toggle to User MCU input to have user MCU interact with Simulator
  • Select Com Port of user MCU, MCU operating baud rate and then Start
  • Only one (Nextion device or User MCU) can be connected at a time
  • When one is selected, the other is not available.

3.9 Connected Nextion Identification

  • When Nextion is connected to Simulator, portions of connect string is shown here.

3.10 Waveform Generator

  • Click here to show the Waveform Generator

3.11 Waveform Generator Options

  • Sinewave or random waveform input at selected intervals.
  • Expected to be sufficient to aid in the debugging process
  • Not expected to be an oscilloscope (Simulator – not emulator)

3.12 Nextion Address

  • Default is 0 – Nextion normal mode, 256 to 2815 in address mode.
  • Address will only apply to specialized advanced applications.

3.13 Simulator Backlight and Sleep

  • The current backlight value (dim command) while debugging
  • The current sleep state indicated by Yes (sleep) or No (wake).

3.14 Saved Nextion Input

  • The Debug Simulator now has 4 storage points for saving Input
  • Clicking the S box will allow you to choose where to store
  • Clicking a numbered box will recall the Input stored in the chosen slot

4. Uploading your Project your Device

Once you have completed designing your HMI project in the Nextion Editor and tested it with the Debug Simulator, it is now time to test it on your actual Nextion device. Note: With previous versions of the Nextion Editor, the Compile and Debug toolbar buttons created the project TFT file in the bianyi folder, note this has changed in favour of outputing your *.tft file directly to microSD card (or folder of your choice).

4.1 Uploading using a microSD card

To upload via microSD card, first use the TFT file output under the File menu to generate your TFT file to your microSD card. You need to ensure that your microSD card is Windows formatted as FAT32, that there is only 1 *.tft file on the microSD card in the root folder, that the microSD card is less than 32GB in size (32GB microSD cards generally are), that the power to Nextion device is off when inserting and removing the microSD card, and that you allow time for any firmware updates to occur after powering your Nextion device back on. Note: not all microSD cards are designed for embedded use. example: Ultra High Speed microSD cards for use with high speed digital cameras. Not all manufacturers adhere to the same standards. It is a matter of finding microSD cards that work for you in a reliable manner. As an example, We have had good successes with Kingston 32GB class 10 HC microSD cards … there are many many others that work well.

4.2 Uploading over Serial

Uploading over TTL Serial can be accomplished using the Upload toolbar button and selecting your configured COM port and baud rate. Keep in mind that Nextion devices are 5.0V devices (refer to your Nextion model’s Datasheet). As there are many many manufactures of USB to TTL Serial adapters, it remains within the User’s domain to understand their chosen TTL Serial Adapter to install, properly configure, and operate.

4.3 Nextion Upload Protocol

The Nextion Upload Protocol v1.1 has been published in the Nextion blog section. This allows users to upload their *.tft files over Serial without the Nextion Editor. As this is an advanced topic, it will not be covered in depth here. Please refer to the published Nextion Upload Protocol v1.1

5. External Tools

5.1 Font Creator

The Nextion Editor ZI Font Creator has undergone an overhaul to introduce proportional fonts with anti-aliasing. Height must be between 16 and 254 and Custom can be chosen to set a height not listed in the dropdown (between 16 and 254). Choosing Anti-aliasing of fonts option will generate an anti-aliased font. Leaving anti-aliased not selected will generate a mono-bit font. Previous embedded 1:2 ratio with width=1/2height has been replaced in favour of proportional fonts. Fixed width fonts can still be generated from a fixed width font source (such as Consolas). Fonts created in the new Font Creator are not compatible with v0.53/LTS. Any installed font on your system can be used as a source for generating your ZI font.  ZI Fonts can now be limited to a specified range of characters, useful for subsetting your fonts to what is project required and reduce font resource space usage.  (56 pixel height UTF-8 could be a very large ZI file at 23,168,377 bytes)

Using the UTF-8 font has requirements that event code is UTF-8 and project Encoding is UTF-8, but for those that are preferring to use UTF-8 over single byte or double byte encodings, The Font Generator can generate a ZI Font using user selected combinations of 142 UTF-8 subsets.  Select Encoding as UTF-8 in the Font Creator and click on the languages(qty) link near the bottom to launch the subset selections.  Once your Language Choice selections are selected, click confirm and Generate Font.  (ensure Height, Encoding, Font, Antialiasing and Bold choices, and Font Name are done as usual)

5.2 Gmov Maker

GMovMaker is a new tool for assisting in creating animations. Ensure that your resources are of uniform size. GmovMaker will create the sequence of images (frames) in the order you create and render your frames with the timing set for each frame (default of 100ms). Frame timing can be set between 30ms and 65000ms. The generated .gmov resource can then be added to your Nextion project as a single resource making your animations easy. GmovMaker will accept *.bmp, *.gif, *.jpg and *.png source files.

5.3 VideoBox

VideoBox is a new tool for the Intelligent Series used to create Audio Resource *.wav files from your audio sources, and Video Resource *.video files from your video sources.

VideoBox will accept *.mkv, *.mp4, *.mov, *.avi, *.mpeg, *.mpg, *.rm, *.wmv, *.rmvb, *.3gp, *.mp3 and *.wav audio source files.
Audio can be run from the microSD card for the Intelligent Series, use the .from attribute of the Audio Component for external file.

VideoBox will accept *.mkv, *.mp4, *.mov, *.avi, *.mpeg, *.mpg, *.rm, *.wmv, *.rmvb and *.3gp video source files. Resolution is limited to area w*h<=622592 where longest_edge<=4080 pixels.

Video can be run from the microSD card for the Intelligent Series, use the .from attribute of the Video Component for external file.

5.4 PictureBox

PictureBox is a new tool for the Intelligent Series used to create resources for the ExPicture components. Picture resources are then stored in ram or in the microSD card folder. Ensure to set the resource orientation the same as the proper orientation for your project. The tool will output your picture resource as an *.xi file. PictureBox will accept *.bmp, *.jpg, *.jpeg, and *.png source files.

Page load link

We Value Your Privacy

By clicking «Accept», you agree to our use of cookies to improve your experience, analyze site usage, and deliver personalized contents.

Go to Top

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Snr ups onrm 1500 s36 инструкция
  • Нейромидин инструкция по применению таблетки детям
  • Лозеваль инструкция по применению для птиц бройлеров
  • Parol 120mg 5ml инструкция по применению на русском
  • Сканер штрих кодов mertech 2210 p2d инструкция