Easy Nextion Library

Hello everyone,

I have been a member of this forum for almost two years. I have the obligation to admit that through this forum and the Arduino community I have learnt so much and got helped even more!
I have learnt how to write code. This doesn't mean that I do not have more to learn, as coding keeps on growing. I have learnt to make projects, small or a little bigger.

One of the things I noticed these past two years, is that everyone helps anyone who is stuck with something or confused.
The last year I noticed that, there were not libraries for Nextion that are beginner-friendly, and after the Tutorial I have written, I saw that a lot of people need something very simple to just run their projects easily.

So today, I am glad to announce you that I have published the first release of the EasyNextionLibrary.

I want to thank again the Arduino community for everything that it has offered to our society and to the open-source coding and gave us the opportunity to occupy ourselves with electronics and coding, by simplifying them.

You can find the library through the Library Manager of the Arduino IDE, by searching: Easy Nextion Library

And of course, at this gitHub repository: GitHub - Seithan/EasyNextionLibrary: A simple library for Nextion display that uses only four functions. You can easily benefit from Nextion's wide range of features and advantages in just a few easy steps. The library uses a custom protocol that can prove to be a powerful tool for advanced users as it can be easily modified to meet one’s needs.

--Athanasios Seitanis

** **Easy Nextion Library** **

** **Description** **

A simple library that uses only four functions. You can easily benefit from Nextion’s wide range of features and advantages in just a few easy steps.
The library uses a custom protocol that can prove to be a powerful tool for advanced users as it can be easily modified to meet one’s needs.
This is an attempt to give a very simple method to use Nextion monitors for beginners at programming and at the same time to be a strong and reliable method that can be capable of satisfying the needs of the advance programming.
The handling of Nextion should be as simple and at the same time as professional as a display of this kind deserves.

** **Installation** **

First Method

  1. In the Arduino IDE, navigate to Sketch > Include Library > Manage Libraries
  2. Then the Library Manager will open and you will find a list of libraries that are already installed or ready for installation.
  3. Then search for EasyNextionLibrary using the search bar.
  4. Click on the text area and then select the latest version and install it.

Second Method

  1. Download the latest release of EasyNextionLibrary.
    https://github.com/Seithan/EasyNextionLibrary

  2. Extract the .zip file

  3. Copy the EasyNextionLibrary folder, to: …\Arduino\libraries\

NOTE: .HMI files for Nextion Editor are also included in every example’s folder.
All .HMIs are set for 2.8" Basic screens, so as to be easier to modify it for bigger screens.

** **The main functions** **

- begin();
- writeNum();
- writeStr();
- readNumber();
- trigger();

** **And the public variables:** **

* currentPageId (Data Type: Integer )
* lastCurrentPageId (Data Type: Integer )

Details, examples and explanation of custom protocol, can be found on my website at:

Easy Nextion Library Custom Protocol Explained

Easy Nextion Library Documentation

Easy Nextion Library Examples

MPU6050 accelerometer and gyro sensor with Easy Nextion library

** **4-step Example** **

  1. Include EasyNextionLibrary and create an object of EasyNex class
#include "EasyNextionLibrary.h"  // Include EasyNextionLibrary

EasyNex myNex(Serial); // Create an object of EasyNex class with the name < myNex > 
                       // Set as parameter the Serial you are going to use
  1. Begin the object and give the desired baud rate as a parameter. Also, initialize the built-in LED as output
void setup(){
  myNex.begin(9600); // Begin the object with a baud rate of 9600
                     // If no parameter was given in the begin(), the default baud rate of 9600 will be used 
  pinMode(LED_BUILTIN, OUTPUT); // The built-in LED is initialized as an output                     
}
  1. Place the NextionListen() function in the loop.
void loop(){
  myNex.NextionListen(); // This function must be called repeatedly to response touch events
                         // from Nextion touch panel. Actually, you should place it in your loop function.
}
  1. Select one of the 50 predefined trigger() functions and use it as a simple void function (nothing returned).
    Declare the void function by simply writing:
void trigger1(){
[ put your code here !!!!]
}

Write the code you want to run in there.
The trigger1() function will run every time the following sequence of bytes (in HEX format) 23 02 54 01 comes to Arduino’s Serial.
To do that, write in the Touch Release Event of the button b0, this command: printh 23 02 54 01

void trigger1(){

  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); 
  if(digitalRead(LED_BUILTIN) == HIGH){
    myNex.writeNum("b0.bco", 2016); // Set button b0 background color to GREEN (color code: 2016)
    myNex.writeStr("b0.txt", "ON"); // Set button b0 text to "ON"
    
  }else if(digitalRead(LED_BUILTIN) == LOW){
    myNex.writeNum("b0.bco", 63488); // Set button b0 background color to RED (color code: 63488)
    myNex.writeStr("b0.txt", "OFF"); // Set button b0 text to "ON"
  }
}

Enjoy the Easy Nextion Library!! Please do not forget the LED on :slight_smile:

Full Example Code

/*
 * FourStepExample.ino - Simple example code
 * Copyright (c) 2020 Athanasios Seitanis < seithagta@gmail.com >. 
 * All rights reserved. EasyNextionLibrary is licensed under the MIT License
 * https://opensource.org/licenses/MIT
 */
#include "EasyNextionLibrary.h"  // Include EasyNextionLibrary

EasyNex myNex(Serial); // Create an object of EasyNex class with the name < myNex > 
                       // Set as parameter the Serial you are going to use

void setup(){
  myNex.begin(9600); // Begin the object with a baud rate of 9600
                     // If no parameter was given in the begin(), the default baud rate of 9600 will be used 
                     
  pinMode(LED_BUILTIN, OUTPUT); // The built-in LED is initialized as an output                     
}

void loop(){
  myNex.NextionListen(); // This function must be called repeatedly to response touch events
                         // from Nextion touch panel. Actually, you should place it in your loop function.
}

void trigger1(){
  /* Create a button on Nextion
   * Write in the Touch Release Event of the button
   * this command:    printh 23 02 54 01
   * Every time the button is pressed, the trigger1() function will run
   * and the code inside will be executed once
   */
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); //If LED_BUILTIN is ON, turn it OFF, or the opposite
  if(digitalRead(LED_BUILTIN) == HIGH){
    myNex.writeNum("b0.bco", 2016); // Set button b0 background color to GREEN (color code: 2016)
    myNex.writeStr("b0.txt", "ON"); // Set button b0 text to "ON"
    
  }else if(digitalRead(LED_BUILTIN) == LOW){
    myNex.writeNum("b0.bco", 63488); // Set button b0 background color to RED (color code: 63488)
    myNex.writeStr("b0.txt", "OFF"); // Set button b0 text to "ON"
  }
}
[b]Function documentation[/b]

The various combinations of attribute choices provide a wide range of expected behaviors with many combinations.
This combined with the Nextion Instruction Set creates the opportunity for very powerful HMIs.

Function trigger();

Associated Library's Code Example: Trigger and FourStepExample

Description:
This is the most important function of the library.
And this is because, it gives you the ability to use the predefined functions and run your code from there.
These predefined functions are named trigger1(), trigger2(), trigger3()... up to trigger50().
You can use them as a simple void function out of the loop, in which you will have written a block of code to run every time it is called.
You can call those trigger() functions and run the code they contain anytime by simply writing in a Nextion Event the command: printh 23 02 54 XX , where XX the id for the triggerXX() in HEX.
For example in a button's Touch Release Event, write:

Command Function
printh 23 02 54 01 trigger1()
printh 23 02 54 02 trigger2()
------------- -------------
printh 23 02 54 0A trigger10()
up to up to
printh 23 02 54 32 trigger50()

In Arduino code, declare a void trigger() function with the predefined name you want to use and put your code there.
Declare the void by simply writing:

void trigger1(){
[ put your code here !!!!]
}

Example:

#include "EasyNextionLibrary.h"

EasyNex myObject(Serial);
void setup(){
  myObject.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}
void loop(){
  myObject.NextionListen();
}
void trigger1(){
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}

1st NOTE: To change the predefined names of the trigger() functions, there are details inside the trigger.cpp file and you can add up to 255 functions of this kind.
2nd NOTE: You can send the same printh command, to call the same function, from more than one component from any page, depending on your needs

See Appendix at the end of the document for numbers in HEX table

** Function begin();**

Parameters:
begin(unsigned long)
unsigned long: unsigned long baud = 9600 (default) if nothing is written in the begin() function

Description:
The begin() method of the class in which we pass the initialization data to the objects.

Syntax:

myObject.begin(115200); // for baud rate 115200

Function writeNum();

Associated Library’s Code Example: ReadAndWriteNumber

Parameters:
writeNum(String, uint32_t)
String = objectname.numericAttribute (example: ‚Äún0.val‚ÄĚ or ‚Äún0.bco‚Ä̂Ķetc)
uint32_t = value (example: 84)(number from 0 to 4,294,967,295)

Description:
For writing numbers in numeric attributes in components of any kind (variables, textboxes, etc.).

  • We can change the shown value of a number box
  • We can change the value of a numeric attribute of the design editing commands. Those commands are used to change the attribute of the components (button, text box, timer, numeric etc.) while Nextion is running.
Command Result on n0 comp.
Syntax
n0.val=30 Sets n0 component‚Äôs shown value to 30 myObject.writeNum(‚Äún0.val‚ÄĚ, 30);
n0.bco=63488 Sets background color to red myObject.writeNum(‚Äún0.bco‚ÄĚ, 63488);
n0.font=0 Sets font to font style with Id = 0 myObject.writeNum(‚Äún0.font‚ÄĚ, 0);
n0.pco=1055 Sets font color to blue myObject.writeNum(‚Äún0.pco‚ÄĚ, 1055);
n0.format=0 Sets value format to decimal myObject.writeNum(‚Äún0.format‚ÄĚ, 0);

With the same way you can change the xcen, ycen, length and isbr

TIP: In a timer component, at the attribute < en >, you can start or stop the timer by writing 0 or 1
Also, at the attribute < tim >, you can set the time the timer is going to repeat the commands written in timer’s User-code event.

myObject.writeNum("tm0.en", 0);     // 0 = stop, 1 = start
myObject.writeNum("tm0.tim", 1000); // repeat code every 1000ms

Syntax:

myObject.writeNum("n0.val", 30);    // Set the value of numeric n0 to 30
myObject.writeNum("n0.bco", 63488); // Set background color of n0 to 63488(red)
myObject.writeNum("n0.font", 0);    // Set font to font style with ID 0
myObject.writeNum("n0.pco", 1055);  // Set font color to blue
myObject.writeNum("n0.format", 0);  // Set value format to decimal

NOTE: Only attributes shown in green in the Editor can be both read and changed by user code at runtime.

Send floating-point numbers, a number that has a decimal point.

Description:
Nextion DOES NOT SUPPORT float numbers. Instead, it uses integer math and does not have real or floating support.
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.

You can send Floating-point numbers with these two ways:

*** On a Xfloat component after you convert the float to int and multiply it by 10, the Xfloat component will put a comma , (decimal point) automatically after the last digit if attribute vvs1 is set to 1.

Example:

int tempInt = temperature*10;      // Convert the float to int. Multiply it x10                       
myNex.writeNum("x0.val", tempInt); // Write it to x0 Xfloat component on Nextion

it is obvious that if you want 2 decimal places, you will set the attribute vvs1 to 2 and you will multiply by 100

*** On a Textbox component after you convert the float value to String

Example:

String tempString = String(temperature, 1); // Convert the float value to String, with 1 decimal place
myNex.writeStr("t0.txt", tempString);       // Write the String value to t0 Textbox component

Function writeStr();

Associated Library’s Code Example: WriteTextAndCommands

Parameters:
writeStr(String, String). To change the .txt attribute in components
String No1: objectname.textAttribute (example: ‚Äút0.txt‚ÄĚ or ‚Äúb0.txt‚ÄĚ)
String No2: value (example: ‚ÄúHello World‚ÄĚ)

  • writeStr(String). To send Designing and System Commands
    String: The command to send on Nextion

Description:
For writing text in Nextion. The two ways the command can be used:

First Usage of the command:
Use writeStr(String, String) to change the text in a textbox
Use both parameters to write text in textboxes.

  • In the first parameter, write the objectName.textAttribute example: t0.txt or b0.txt
  • In the second parameter, write the text you want to ‚Äúprint‚ÄĚ

1st Syntax:

myObject.writeStr("t0.txt", "Hello World"); // Change t0 text to "Hello World"

Any previous text on the textbox is deleted

Avoid using very big text Strings in the same command, as Nextion will not recognise them. Istead use a second command and in order to add to the existing text, use the **+**symbol, after the .textAttribute("t0.txt+").

myObject.writeStr("t0.txt", "You are now transferred to page2\rThank you\rfor choosing my library!!!");
myObject.writeStr("t0.txt+", "\rEnjoy the library!!!");
myObject.writeStr("t0.txt+", "\r\rAthanasios Seitanis\rseithagta@gmail.com");
 /* By writing \r, you send Nextion the change line character < r >
  * The second  is required, in order to print the  as character
  * and not as an escape character.
  */

Second Usage of the command:
Use writeStr(String) to send Designing and System Commands according to the instructions of Nextion’s Instruction Set.
Use only the first parameter to send a command to Nextion. The commands must be syntaxed according to Nextion’s Instruction Set.

2nd Syntax:
Design Commands Example:

myObject.writeStr("page page0"); // Sending this command to change the page we are on Nextion using pageName
myObject.writeStr("page 1"); // Sending this command to change the page we are on Nextion using pageId
myObject.writeStr("cir 100,100,30,RED"); // Renders a hollow Red circle with circle center at (100,100)

System Commands Example:

myObject.writeStr("dim=50"); // Set the current brightness level to 50%
myObject.writeStr("sleep=1"); // sleep=1 (Enter sleep mode) or sleep=0 (Exit sleep mode)

NOTE: When you decide to exit the sleep mode on Nextion, use a small delay of 50ms, in order to give Nextion some time to Exit sleep mode.
WARNING: DO NOT send commands that causes data return over Serial to MCU, unless you know what you are doing.
Commands that cause data return over serial:
print, prints, printh, sendme, get, rept, rdfile, twfile
TIP: Write in the debug mode the command to check if it is written correctly

[b]Function readNumber();[/b]

Associated Library's Code Example: ReadAndWriteNumber

See Example's code on Github: ReadAndWriteNumber on Github
Parameters:
readNumber(String)
String: objectname.numericAttribute (example: "n0.val", "n0.pco", "n0.bco"...etc)

Description:
We use it to read the value of every components' numeric attribute from Nextion (value, bco color, pco color...etc)
In case the function fails to read the new value, it will return the number 7777.
The chances of getting a wrong value is one in a million.
You can use this, fail return value, feature in your code, in case you handle sensitive value data, to confirm that you have the right value.
You can check it with an if() statement, in which you will ignore the value of 7777 and you can run the readNumber() again or set a safe value or use the last good known value method.

uint32_t number = 0;
uint32_t lastnumber = 0;

number = myNex.readNumber("n0.val");   // We read the value of n0 and store it to number variable
    
if(number != 7777){       // 7777 is the return value if the code fails to read the new value
  lastnumber = number;
  
} else if(number == 7777){
    number = lastNumber;
}

Syntax:

unsigned long x = myObject.readNumber("n0.val"); // Store to x the value of numeric box n0
unsigned int y = myObject.readNumber("b0.bco"); // Strore to y the color number of the background of button b0

NOTE: Only attributes shown in green in the Editor can be both read and changed by user code at runtime.

[b]Library Public Variables[/b]

Associated Library's Code Example: ChangePagesAndSentFloatValues

See Example's code on Github:ChangePagesAndSentFloatValues on Github

1st Variable:
currentPageId
A variable that stores the ID number of the current page loaded on Nextion. It is VERY important that Nextion and Arduino are synced and when you send data, the data goes to the right page.

NOTE: In order to update this variable with the current Id of the page, you must write the Preinitialize Event of every page: printh 23 02 50 XX , where XX the id of the page in HEX.
For page0: printh 23 02 50 00
for page9: printh23 02 50 09
for page10: printh 23 02 50 0A

See Appendix at the end of the document for numbers in HEX table

It can be called by writing:

int x = myObject.currentPageId; // Store to x the currentPageId

Example:

if(myObject.currentPageId == 0){
  myObject.writeStr("t0.txt", "You are on page0!");
}else if(myObject.currentPageId == 1){
  myObject.writeStr("t0.txt", "You are on page1!");
}

2nd Variable:
lastCurrentPageId
This variable stores the last value of currentPageId before currentPageId is changed. We use it to check if the page we are on has changed, in order to send refreshing screen data to the components of the page.
After that, it can be set to equal with the currentPageId, in order not to send unnecessary data for refreshing the components.

if(myObject.currentPageId != myObject.lastCurrentPageId){
  if(myObject.currentPageId == 0){
    [send the data to refresh the page0]
  }else if(myObject.currentPageId == 1){
    [send the data to refresh the page1]
  }
  myObject.lastCurrentPageId = myObject.currentPageId;
}

Find more on the Library's Example: ChangePagesAndSentFloatValues
TIP: You can read the ID of the current Loaded page at anytime, without the use of the Library's commands using the dp system command
int x = myObject.readNumber("dp"); // Store to x the ID of the current Loaded page

Compatibility

  • Arduino
  • ESP

Tested MCUs:

  1. Arduino NANO
  2. Arduino MEGA 2560
  3. Arduino UNO
  4. WeMos D1 mini ESP8266

In this example we:

  • Change page on nextion to page0, write a text on a TextBox, wait for a while (5 sec).
  • Change page on nextion to page1, write a text on a TextBox, wait for a while (5 sec).
  • Change page on nextion to page2, write a text on a TextBox, wait for a while (8 sec).
  • Send the text ‚ÄúScreen will go to sleep mode in‚ÄĚ.
  • Enter to sleep mode, wait 10 seconds‚Ķ
  • Exit sleep mode, repeat.
/*
 * WriteTextAndCommands.ino - Simple example code for EasyNextionLibrary
 * Copyright (c) 2020 Athanasios Seitanis < seithagta@gmail.com >. 
 * All rights reserved. EasyNextionLibrary is licensed under the MIT License
 * https://opensource.org/licenses/MIT
 */
 
/* I have invested time and resources providing open source codes, like this one. 
 * Please do not hesitate to support my work!
 */
 
#include "EasyNextionLibrary.h"  // Include EasyNextionLibrary
                                                // Download the latest release of EasyNextionLibrary from:.
                                                // https://github.com/Seithan/EasyNextionLibrary

EasyNex myNex(Serial); // Create an object of EasyNex class with the name < myNex >
                       // Set as parameter the Serial you are going to use

void setup(){
  myNex.begin(9600); // Begin the object with a baud rate of 9600
                       // If no parameter was given in the begin(), the default baud rate of 9600 will be used
}

void loop(){
  /* Use writeStr(String) for sending commands. 
   * Use ONLY the first parameter
   * In the first parameter, write the command according to the instructions of Nextion's Instruction Set 
   * Do NOT write ANYTHING in the second parameter. Leave it empty.
   * TIP: Write in the debug mode the command to check if it is written correctly
   * example: The command to change the page and go to page0, is:  page page0(page0 is the name of the page) 
   * or page 0(0 is the ID of the page)
   */
  myNex.writeStr("page page0"); // Sending this command to change the page we are on Nextion using pageName
  delay(50); // Some time for Nextion to execute the command
  /* Use writeStr(String, String) to change the text in a textbox  
   * Use BOTH parameters
   * In the first parameter, write the objectName.textAttribute example: t0.txt or b0.txt
   * In the second parameter, write the text you want to "print"
   * Any previous text on the textbox is deleted
   */
  myNex.writeStr("t0.txt", "You are now transferred to page0"); // The text in t0 is now this
  delay(2950);

  
  myNex.writeStr("page 1"); // Sending this command to change the page we are on Nextion using pageId
  delay(50); // Some time for Nextion to execute the command
  /* By writing \\r, you send Nextion the change line character < \r >
   * The second \ is required, in order to print the \ as character
   * and not as an escape character.
   */
  myNex.writeStr("t0.txt", "You are now transferred to page1\\r");
  // Avoid using very big text Strings in the same command, as Nextion will not recognise them.
  // Istead use a second command and in order to add to the existing text, use the + symbol, after the .textAttribute("t0.txt+").
  myNex.writeStr("t0.txt+", "This is the:\\rWriteTextAndCommands example");
  myNex.writeStr("t0.txt+", "\\rEvery 3000ms we change page");
  myNex.writeStr("t0.txt+", "\\rAnd we print a text to t0");
  delay(4950);
  
  myNex.writeStr("page page2");
  delay(50); // Some time for Nextion to execute the command
  myNex.writeStr("t0.txt", "You are now transferred to page2\\r");
  myNex.writeStr("t0.txt+", "Thank you\\rfor choosing my library!!!");
  myNex.writeStr("t0.txt+", "\\rEnjoy the library!!!");
  myNex.writeStr("t0.txt+", "\\r\\rAthanasios Seitanis");
  myNex.writeStr("t0.txt+", "\\rseithagta@gmail.com");
  delay(7950);
  
  myNex.writeStr("t0.txt", "Screen will go to sleep mode in");
  myNex.writeStr("t0.txt+", "\\r3...");
  delay(1000);
  myNex.writeStr("t0.txt+", "2...");
  delay(1000);
  myNex.writeStr("t0.txt+", "1...");
  delay(1000);
  myNex.writeStr("t0.txt", "S L E E P\\rSee you in 10 seconds!!!");
  delay(1000);
  
  myNex.writeStr("sleep=1"); // Screen goes to sleep mode
  delay(10000);
  myNex.writeStr("sleep=0"); // Screen exits sleep mode
  delay(100); // Give some time to Nextion to Exit sleep mode
  
  // As these commands are using Serial to read and write, 
  // it is more preferred not to run them in the loop() without delay(); 
  // or some other method of not running them with the frequency of the loop
  // and use them only when it is needed.
  // A delay in the loop can be noticed, especially when reading from Serial
  // And of course to avoid a Serial buffer overflow
}

Hi Seithan. I was working in my project and I was using the official Nextion library, but when my code starts to get bigger some of the commands to the Nextion stop to work, giving me a headache. So, I start a post and get an answer from Perry Bebbington, he mentions your library. I'm starting to change my code to use your library and so far everything is working perfectly, therefore, congratulations for your contribution to the community it is an awesome work. I‚Äôm reading your documentation and testing your examples, but I don‚Äôt find yet something related to the waveform component of the Nextion. I‚Äôm using one in my project so I¬īm wondering if is possible to be used with your Easy Nextion Library. Can you give me an example?

Congratulations!!

Thank you for using my library and I’m glad that my work proved useful!

I must write many examples to cover all the basic needs and I’m doing this at the time being.

You can send values to a waveform using the writeStr() function to send a command, this means that you can send this:

writeStr(‚Äúadd 1,0,30‚ÄĚ) // add value 30 to Channel 0 of Waveform with .id 1

Last time that I had to deal with a waveform, I preferred to handle it with a different way that I find it more efficient, as we must map the values to 0-255 and after to send the command ‚Äúadd‚ÄĚ.

So:

  1. Create a numeric variable on Nextion.

  2. Send the value of the sensor on Nextion’s variable, if the value is a float, multiply it by x10 and convert it to int (see the example for sending numbers and floats)

  3. Now handle the waveform from Nextion

Create a timer and write a little code where at the preferred time, read the variable, make the mapping and send it to the waveform.

Maybe this way seems complicated but in that project, I was using 4 waveforms with 2 channels and at the same time I was using the values from the variables to display 4 progress bars and also I displayed the value.

I’m going to write an example for MPU6050 but until that time you can use this:

/*
 * Waveform.ino - Simple example code for EasyNextionLibrary
 * Copyright (c) 2020 Athanasios Seitanis < seithagta@gmail.com >. 
 * All rights reserved. EasyNextionLibrary is licensed under the MIT License
 * https://opensource.org/licenses/MIT
 */

/* This project aims to show how to manage waveforms,
 * how to send different data on Nextion and how to process them
 */


#include "EasyNextionLibrary.h"  // Include EasyNextionLibrary 

EasyNex myNex(Serial); // Create an object of EasyNex class with the name < myNex >
                       // Set as parameter the Serial you are going to use
                       
#define DATA_REFRESH_RATE 500 // The time between each Data refresh of the page
                               // Depending on the needs of the project, the DATA_REFRESH_RATE can be set
                               // to 50ms or 100ms without a problem. In this example, we use 1000ms, 
                               

unsigned long pageRefreshTimer = millis(); // Timer for DATA_REFRESH_RATE

//--------------------------------------------------------------------------------
//_________ MPU6050 Accelerometer and Magnetometer sensor Configuration
//--------------------------------------------------------------------------------
#include <MPU6050_tockn.h>      // MPU6050_tockn Library
                               //  Get the library  HERE: https://github.com/tockn/MPU6050_tockn
                              //   or from Library manager on Arduino IDE <MPU6050_tockn>
 #include <Wire.h>                              
                             // Connect SCL to D21 pin    SDA to D20 for Mega
                            //  Connect SCL to A5 pin     SDA to A4 for UNO - Nano 

MPU6050 mpu6050(Wire);       // create an object of MPU6050_tockn library with the name <mpu6050> so that we can access functions related to it

float accelerationX = 0;
float accelerationY = 0;
float accelerationZ = 0;

float lastSentAccelerationX = 0;
float lastSentAccelerationY = 0;
float lastSentAccelerationZ = 0;

float angleX = 0;
float angleY = 0;
float angleZ = 0;

float lastSentAngleX = 0;
float lastSentAngleY = 0;
float lastSentAngleZ = 0;           

#define PIN_CALIBRATION_MPU6050 10  // when D10 is LOW with a switch on GND. MPU6050 NOT calibrating on start up
                                    // the INPUT_PULLUP is going to activated later
#define MPU6050_GET_DATA_EVERY 400   // request data from sensor every 400ms 
unsigned long mpu6050Timer = millis();


void setup(){

  //__________ Nextion setup    

   myNex.begin(9600); // Begin the object with a baud rate of 9600
                     // If no parameter was given in the begin(), the default baud rate of 9600 will be used 
  
  //--------------------------------------------------------------------------------
//_________ MPU6050 Accelerometer and Magnetometer sensor setup
//--------------------------------------------------------------------------------
  pinMode(PIN_CALIBRATION_MPU6050, INPUT_PULLUP);  
  Wire.begin();
  mpu6050.begin();
  
  if(digitalRead(PIN_CALIBRATION_MPU6050) == HIGH) {
    mpu6050.calcGyroOffsets(true);
  }
  
} 

void loop(){

 
 mpu6050GetData();
 refreshNextion();
}

void mpu6050GetData() {

  if((millis()-mpu6050Timer) > MPU6050_GET_DATA_EVERY){
      mpu6050.update();
      
      if((millis()-mpu6050Timer) > (MPU6050_GET_DATA_EVERY + 10)){
         accelerationX = mpu6050.getAccX();
         accelerationY = mpu6050.getAccY();
         accelerationZ = mpu6050.getAccZ();
      
         angleX = mpu6050.getAngleX();
         angleY = mpu6050.getAngleY();
         angleZ = mpu6050.getAngleZ();
         
         mpu6050Timer = millis();
      }
  }
}

void refreshNextion() {
    
    if((millis()-pageRefreshTimer) > DATA_REFRESH_RATE){
    
      if(lastSentAccelerationX != accelerationX){
        int accelerationXInt = accelerationX*10;  // multiply x10 and convert it to int
        myNex.writeNum("accelX.val", accelerationXInt); // accelX is a variable that we have create on Nextion

        lastSentAccelerationX = accelerationX;
      }

      if(lastSentAccelerationY != accelerationY){
        int accelerationYInt = accelerationY*10;
        myNex.writeNum("accelY.val", accelerationYInt); // accelY is a variable that we have create on Nextion

        lastSentAccelerationY = accelerationY;
      }      
      
      if(lastSentAccelerationZ != accelerationZ){
        int accelerationZInt = accelerationZ*10;  
        myNex.writeNum("accelZ.val", accelerationZInt); // accelZ is a variable that we have create on Nextion

        lastSentAccelerationZ = accelerationZ;
      }

      if(lastSentAngleX != angleX){
        int angleXInt = angleX*10;  
        myNex.writeNum("angleX.val", angleXInt); // angleX is a variable that we have create on Nextion        

        lastSentAngleX = angleX;
      }

      if(lastSentAngleY != angleY){
        int angleYInt = angleY*10; 
        myNex.writeNum("angleY.val", angleYInt); // angleY is a variable that we have create on Nextion 

        lastSentAngleY = angleY;
      } 

      if(lastSentAngleZ != angleZ){
        int angleZInt = angleZ*10;  
        myNex.writeNum("angleZ.val", angleZInt); // angleZ is a variable that we have create on Nextion 

        lastSentAngleZ = angleZ;
      }      
      pageRefreshTimer = millis();
    }

}

I have not tested the code, but I am sure it works. If any bugs appear, let me know.

I am attaching both the HMI and the .ino file into a .zip file.

Stay healthy!

Also, at the library I mention that you can send every command of the Instruction Set, with writeStr(String).

But it is for sure better to have examples, as they are easier to understand. :slight_smile:

EDIT:

 // Connect SCL to D21 pin    SDA to D20 for Mega
        //  Connect SCL to A5 pin     SDA to A4 for UNO - Nano

Waveform.zip (106 KB)

Wow, thanks for the quick answer. You are right I didn't notice how easy is it, I will follow your recommendation. Keep on with this excellent contribution!!

Hi Seithan

Thank you, for your library it has helped with my ESP-NOW, Nextion, Blynk multiple sensor home project.

I now have all my sensor readings displayed on my Nextion as well as being posted to Blynk, which is great and thanks to your library quite easy to implement.

Now I have come across one issue and hope you can help me.

In your examples, you have the Analogue read to progress bar, and I tested this working on my larger Nextion perfectly.

So it got me thinking that perhaps I could also monitor the battery levels of each of my temperature sensors, which are all Wemos D1mini pro`s.

I looked at you code and saw that half of the code was actually on the Nextion itself.

So I did some plying around trying to get 4 separate progress bars on my display, unfortunately I cant work out how to do it as I keep getting errors.

Can you give an example of say 2 separate progress bars for different readings, I could then work out how to add more.

Many thanks in advance.

Alan

Hello Alan,

I am glad that the library was useful and above all, it was Easy to use. :slight_smile:

I have prepared an example for two seperate progress bars and I cannot believe that you made such a big project with Blynk, you also connected Nextion, and you are stuck in an problem that is a piece of cake.

I hope it helps you and I hope that I understood correctly what you asked for.

If you have further questions, do not hesitate to ask.

Stay healthy!

AnalogRead To Two Progress Bars.zip (12 KB)

Hi Saithan

Funnily enough your code was basically what I had written to the Nextion.

I tried your 2 line progress bar, and ig worked, so I added 2 more lines, with the same structure and bang errors again.

I have no idea why as I have created the variables, everything is the same as you made, just doubled up, and I just get errors.

See attached screenshot.

Cheers Alan

1 Like

Hello @damian99, welcome to the forum.

Hello Allan
Unfortunately the system variables for Nextion are only 3 and have the names sys0, sys1, sys2.
The error on Editor is expected as there is no sys3 or sys4.
You can use the variable sys0 again and again for each addition you make and save the new value as after the re-mapping you no longer need the sys0 value.
I confused you with using sys1 instead of using sys0 again, I'm sorry about that.

you code on Nextion can be like this

n1.val=Nvoltage1.val                  // write Nvoltage1.val to n1.val
sys0=Nvoltage1.val*100/5000   //  use sys0 to make the calculations
j1.val=sys0                            //   add the value to the Progress bar
//
n2.val=Nvoltage2.val                  // write Nvoltage2.val to n2.val
sys0=Nvoltage2.val*100/5000   //  use sys0 to make the calculations
j2.val=sys0                             //   add the value to the Progress bar
//
n3.val=Nvoltage3.val                  // write Nvoltage3.val to n3.val
sys0=Nvoltage3.val*100/5000   //  use sys0 to make the calculations
j3.val=sys0                             //   add the value to the Progress bar
//
n4.val=Nvoltage4.val                  // write Nvoltage4.val to n4.val
sys0=Nvoltage4.val*100/5000   //  use sys0 to make the calculations
j4.val=sys0                             //   add the value to the Progress bar
//

The following reference is from the Nextions instruction set

sys0     Numeric       sys0=10 sys1=40 sys2=60 n0.val=sys2
sys1     System        System Variables are global in nature with no need to define or create.
sys2     Variables      They can be read or written from any page. 32-bit signed integers.
                              min value of -2147483648, max value of 2147483647
                              Suggested uses of sys variables include
 ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ‚Äď as temporary variables in complex calculations
 ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬† ‚Äď as parameters to pass to click function or pass between pages.

Man you are an absolute star! :slight_smile:

Thank you so very much, yes the code complied after I tweaked it around.

I have to flash my system but will update with my code and a couple of pictures tomorrow.

Cheers again

Thank you for a piece of art!! It is a great library andeasy to follow.

I got it working with my code on a Uno (using it exactly as in you explanations). But if I upload the code to a Nano there is no reaction from the nano on button presses ect. The same code working on Uno, but no comms with Nano.

I see Uno is using Serial. What changes must be made in the library for it to work with Nano?

Hello McLarens,

First of all, thank you for your kind words!

There is no need for any changes to be made in order to work with NANO. I am always using NANOs and all the examples are tested on NANOs.

I do not know what could possibly is happening with your NANO. Maybe try another one. Try a common ground between Nextion and Arduino and do not power the NANO from USB when using Nextion.

Also try to not have connected the Serial pins when uploading the sketch.

If you find my Library useful, you can add karma

Hello

Love the library, i’ve spent days before trying to get the standard one to work as expected. Is there a way to read a txt val ? I see you can read a numeric val but i can’t seem to work out how to get the arduino to read a txt value.

Hello jack.

I'm glad that the library is useful and easy to handle.

No, I haven't added this feature as I think that the usage is almost unnecessary as a Display is most for displaying messages and not to sent text to MCU. I tried hard to have as less functions as possible.
The profit of adding this function is small in contrast to keeping the simplicity.

Although if you need to store a text, it is more efficient to store it on Nextion using a variable (change variable's type "sta" to string) or a Textbox component.

Feel free to ask again

Ah that would be why, I was trying to pass through an ssid/password and possibly even an IP address entered on the Nextion to the ardunio.

No worries I’ll have a play around with it

Hello jack0oo,

I made a small example on how you can send text from Nextion to Arduino. You can read a small guide on how you can use Nextion
A guide for receiving and sending commands from Nextion displays

Have in mind: pay attention to the number of bytes that the textbox will have, because the print command will return 1 ASCII byte per char. That means it can send as many characters as the field has. If they are many, it can cause buffer overflow etc.

This is the other reason I chose not to add readStr() function and I leave it up to the user, in order to know what they are doing.

Despite this, I would like your opinion on whether I should add this function with a restriction to the number of bytes or leave it as it is.

I will attach the code below and the .HMI file in a .zip file

/*
 * passwordCode.ino - Simple example code for EasyNextionLibrary
 * Copyright (c) 2020 Athanasios Seitanis < seithagta@gmail.com >. 
 * https://www.seithan.com 
 * All rights reserved. EasyNextionLibrary is licensed under the MIT License
 * https://opensource.org/licenses/MIT
 */
 
 //********************************************************************************
 //  You can find more examples, tutorials and projects with Nextion on my website
 //  https://www.seithan.com 
 //********************************************************************************
 
// Compatible for Arduino

/* This example shows how to read a password from a Textbox
 * Using the trigger function of EasyNextionLibrary
 */
 
 #include "EasyNextionLibrary.h"  // Include EasyNextionLibrary
                                 // Download the latest version https://github.com/Seithan/EasyNextionLibrary
                                 // or from Arduino's IDE Library Manager

EasyNex myNex(Serial); // Create an object of EasyNex class with the name < myNex >
                       // Set as parameter the Serial you are going to use


char PASSWORD[] = "1234";                   
String passwordCheck;


void setup(){
  myNex.begin(9600); // Begin the object with a baud rate of 9600
                     // If no parameter was given in the begin(), the default baud rate of 9600 will be used
  
}

void loop(){
  myNex.NextionListen(); // WARNING: This function must be called repeatedly to response touch events
                         // from Nextion touch panel. Actually, you should place it in your loop function.
}

void trigger1(){
  // To call this void send from Nextion's component's Event:  printh 23 02 54 01
  // In this exmaple, we send this command from the Release Event of b0 button (see the HMI of this example)
  // You can send  the same `printh` command, to call the same function, from more than one component, depending on your needs
  
  // from the same button after printh 23 02 54 01 we send the command: print t0.txt 
  // return 1 ASCII byte per char of t0.txt without null byte ending
  // Next step is to read those bytes
 unsigned long timer = millis();
 
  while(Serial.available() < 4){       // suppose the password is 4 bytes (4 digit) and wait for them over serial
     if((millis() - timer) > 100UL){     // Waiting... But not forever...... 
       break;                            
      } 
  }
  
  if(Serial.available() >= 4){ 
    // 1st Byte
    char c = Serial.read();
      passwordCheck = c;
    // 2nt Byte  
        c = Serial.read();
      passwordCheck += c;
    // 3rd Byte  
        c = Serial.read();
      passwordCheck += c;
    // 4rt Byte  
        c = Serial.read();
      passwordCheck += c;
       
  }
  myNex.writeStr("t2.txt", passwordCheck); // print the entered password to t2 textbox

  if(passwordCheck.equals(PASSWORD) == true ){ // check the password
    myNex.writeStr("t1.txt", "PASSWORD OK");
  }else{
    myNex.writeStr("t1.txt", "WRONG PASSWORD");
  }

}

password.zip (9.87 KB)