Easy Nextion Library Examples

Easy Nextion Library Logo

Contents



AnalogRead To Nextion Progress Bar


This example aims to show how you can use and manage progress bar on Nextion displays and change it's value.
As an example we are going to display the value of an analog input.

Progress bar's value data range is min 0 max 100. A re-map of value range must de done

To update the value of a progress bar you can use the writeNum() function.
writeNum("j0.val", 55); set the value of j0(object Name) to 55
writeNum("j0.val", volt); set the value of j0(object Name) equal with the value of volt variable
To make a vertical progress bar set the **dez** attribute to vertical and change the values of width and height of the progress bar.
To reverse the direction of progress bar where the default in horizontal is: left to right and down to up in vertical align, subtract the value from 100 and reverse the colors of foreground and background between them.

There is no need to send the value from Arduino straight to the progress bar with writeNum() ,
as most times the progress bar is not the only component on a page that must be updated usually the display of the value on a box also needed.
On some cases a change of color on a box or on progress bar also needed when value reach a point, as the value of the progress bar must be re-mapped to 0-100 and in order to not send the same value multiple times with different formats and limit the data from Serial, use the advantages of Nextion graphics to create a variable and save there the value you want to appear in the progress bar.
Use the features provided by Nextion via the user code on a timer to update the progress bar and at the same time display the value or whatever else you need.

Progress bar can take values from 0-100.
We map the value from arduino 0-5000:
The math type for map the range is:
return = (value - low1) * (high2 - low2) / (high1 - low1) + low2

As both ranges start from zero low1 and low2 = 0
The type becomes:
return = value*high2/high1
return=value*100/5000

Arduino & ESP Example:

/*
 * AnalogReadToProgressbarCode.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
 */
 
/* I have invested time and resources providing open source codes, like this one. 
 * Please do not hesitate to support my work!
 * If you found  this work useful and has saved you time and effort,
 * Just simply paypal me at: seithagta@gmail.com
 */
 
 //********************************************************************************
 //  You can find more examples, tutorials and projects with Nextion on my website
 //  https://www.seithan.com 
 //********************************************************************************
 
 /* This example aims to show how you can use and manage progress bar
  * on Nextion displays and change it's value. 
  * As example we are going to display the value of an analog input.
  */
  
  //********** Progress bar's value data range is min 0 max 100 **********
  //         **** A re-map of value range must de done ****
  
  /* To update the value of a progress bar you can use the writeNum() function
   * writeNum("j0.val", 55); set the value of j0(object Name) to 55
   * writeNum("j0.val", volt); set the value of j0(object Name) equal with the value of volt variable
  */
  
  /* To make a vertical progress bar set the **dez** attribute to vertical 
   * And change the values of width and height of the progress bar.
   */
  
  /* To reverse the direction of progress bar where the default in horizontal is: left to right
   * and down to up in vertical align, subtract the value from 100 and reverse the colors
   * of foreground and background between them
   */   
   
   /* There is no need to send the value from Arduino straight to the progress bar with writeNum();
    * as most times the progress bar is not the only component on a page that must be updated
    * usually the display of the value on a box also needed 
    * On some cases a  change of color on a box or on progress bar also needed when value reach a point.
    * As the value of the progress bar must be re-mapped to 0-100 and in order to not send the same value multiple times
    * with different formats and limit the data from Serial, use the advantages of Nextion graphics to
    * create a variable and save there the value you want to appear in the progress bar.
    * Use the features provided by Nextion via the user code on a timer to update the progress bar 
    * and at the same time display the value or whatever else you need.
    */
    

#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
                        
uint16_t voltage;  // a variable to store the reading
                 // for simplicity Reasons we do not use float and we are going to take the measure in millivolts
 

const int REFRESH_TIME = 100;           // time to refresh the Nextion page every 100 ms
unsigned long refresh_timer = millis();  // timer for refreshing Nextion's page



void setup() {

  pinMode(A0, INPUT); // set A0 pin as INPUT
 
  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() {
  
  if((millis()-refresh_timer) > REFRESH_TIME){ //IMPORTANT do not have serial print commands in the loop without a delay
                                              // or an if statement with a timer condition like this one.
                                              
      int tempData = analogRead(A0);  // Read the analog pin
      voltage = map(tempData, 0, 1024, 0, 5000); // same like: voltage = analogRead(A0)*5000/1024
    
      /* We Re-map the value of tempData from 0-1024 (steps) to 0-5000 millivolt
       * connect the pins of a Potentiometer on A0 pin, 5v (5000 millivolt) and GND. Outer pins to 5v and GND, middle pin to A0
       * https://www.arduino.cc/en/tutorial/potentiometer
       * Turn it over and read values from 0 to 5000 millivolts
       */
               
      myNex.writeNum("Nvoltage.val", voltage); // Nvoltage.val is a variable that we have create on Nextion.        
                                              // we send the value of the voltage variable on Arduino
                             // you can use the same name for variables on Nextion for easy recognition with a capital N in front
                             // Avoid the use of big variable names as every character is one byte to serial. 
                             // In here we use big names for the sake of example.
      refresh_timer = millis();  // Set the timer equal to millis, create a time stamp to start over the "delay"
     
    }       
}

/* The rest work is on Nextion with the code on a timers user event

n0.val=Nvoltage.val         // write Nvoltage.val to n0.val
sys0=Nvoltage.val*100/5000  // use sys0 to make the calculations
j0.val=sys0                //  add the value to the Progress bar
//
//Reverse direction progress bar
j1.val=100-sys0
//
// Vertical allign
j2.val=sys0
//
// Progress bar can take values from 0-100
// we map the value from arduino 0-5000 :
// the math type for map the range is:
// return = (value - low1) * (high2 - low2) / (high1 - low1) + low2
// as both ranges start from zero low1 and low2 = 0
// the type becomes
// return = value*hight2/hight1
// return=value*100/5000

//
// And some graphic effects
if(n0.val>3300)
{
  n0.bco=RED
  j0.pco=RED
  j1.bco=RED //bco for the reversed
  j2.pco=RED
}else
{
  n0.bco=YELLOW
  j0.pco=1024
  j1.bco=1024
  j2.pco=1024
}
*/


The .zip file contains:

  • .HMI file for Nextion
  • .ino file for Arduino



File downloaded 3266 times.


AnalogRead To Nextion Waveform


This example aims to show how you can use and manage single waveform on Nextion displays. As an example we are going to display the value of an analog input.
With the same way you can manage more than one channels or waveforms

Every waveform can have up to 4 channels. They are numbered from 0 to 3
Don't mistake the number of channels with the ID of the channel
ID is 0 for the first channel, 1 for the second, 2 for the third, 3 for the fourth

Every waveform can have up to 4 channels. They are numbered from 0 to 3. Don't mistake the number of channels with the ID of the channel ID is 0 for the first channel, 1 for the second, 2 for the third, 3 for the fourth.

TIP: Waveform 1 pixel column used for every data value added on x - axis. On y - axis as the Data range is from 0 to 255 the height of waveform must be 255 pixels, in order to have a represent of zero to the lower point and 255 to the higher point of the waveform.
If the height of the waveform is not 255 pixel use the *dis* attribute for scaling the data from 10 to 1000%.
if waveform has a height of 127 pixel set data scaling *dis* to 50. Set *dis* to 200 for 510 pixel waveform height.
You can use this math type: < dis = 100*(waveform height in pixels)/255 >

There is no need to send from Arduino the command add <waveform>,<channel>,<value>,
as most times the waveform is not the only component on a page that must be updated usually. The display of the value on a box also needs to.
On some cases, a change of color on a box also needed when value reach a point.
As the value to waveform must be re-mapped to 0-255 and in order to not send the same value multiple times, with different formats and limit the data from Serial, use the advantages of Nextion graphics to create a variable and save there the value you want to appear in the waveform.
Use the features provided by Nextion via the user code on a timer to update the waveform and at the same time display the value or whatever else you need

Arduino & ESP Example:

/*
 * AnalogReadToWaveformCode.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
 */
 
/* I have invested time and resources providing open source codes, like this one. 
 * Please do not hesitate to support my work!
 * If you found  this work useful and has saved you time and effort,
 * Just simply paypal me at: seithagta@gmail.com
 */
 
 //********************************************************************************
 //  You can find more examples, tutorials and projects with Nextion on my website
 //  https://www.seithan.com 
 //********************************************************************************
 
 /* This example aims to show how you can use and manage single waveform
  * on Nextion displays. As an example we are going to display the value of an analog input.
  * With the same way you can manage more than one channels or waveforms
  */
  
  /* Every waveform can have up to 4 channels. They are numbered from 0 to 3
   * Don't mistake the number of channels with the ID of the channel
   * ID is 0 for the first channel, 1 for the second, 2 for the third, 3 for the fourth  
  */
  //********** Waveform's channel data range is min 0 max 255 **********
  //         **** A re-map of value range must de done ****
  /* The command to Add single value to Waveform Channel is:
   * add <waveform>,<channel>,<value>
   * <waveform> is the .id of the waveform component
   * <channel> is the channel the data will be added to
   * <value> is ASCII text of data value, or numeric value
   */
   
   /* TIP: Waveform 1 pixel column used for every data value added on x - axis
    * on y - axis as the Data range is from 0 to 255 the height of waveform must be 255 pixel
    * in order to have a represent of zero to the lower point and 255 to the higher point of the waveform
    * If the height of the waveform is not 255 pixel use the * dis * attribute for scaling the data from 10 to 1000%
    * if waveform has a height of 127 pixel set data scaling * dis * to 50. Set dis to 200 for 510 pixel waveform height
    * You can use this math type < dis = 100*(waveform height in pixels)/255 >
    */
   
   /* There is no need to send from Arduino the command add <waveform>,<channel>,<value>
    * as most times the waveform is not the only component on a page that must be updated
    * usually the display of the value on a box also needed 
    * On some cases a  change of color on a box also needed when value reach a point.
    * As the value to waveform must be re-mapped to 0-255 and in order to not send the same value multiple times
    * with different formats and limit the data from Serial, use the advantages of Nextion graphics to
    * create a variable and save there the value you want to appear in the waveform.
    * Use the features provided by Nextion via the user code on a timer to update the waveform 
    * and at the same time display the value or whatever else you need
    */

#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
                        
uint16_t voltageGraph;   // a variable to store the reading
                 // for simplicity reasons, we do not use float and we are going to take the measure in millivolts
 

const int REFRESH_TIME = 100;           // time to refresh the Nextion page every 100 ms
unsigned long refresh_timer = millis();  // timer for refreshing Nextion's page



void setup() {

  pinMode(A0, INPUT); // set A0 pin as INPUT
 
  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() {
  
  if((millis()-refresh_timer) > REFRESH_TIME){ //IMPORTANT do not have serial print commands in the loop without a delay
                                              // or an if statement with a timer condition like this one.
                                              
      int tempData = analogRead(A0);  // Read the analog pin
      voltageGraph = map(tempData, 0, 1024, 0, 5000); // same like: voltageGraph = analogRead(A0)*5000/1024
    
      /* We Re-map the value of tempData from 0-1024 (steps) to 0-5000 millivolt
       * connect the pins of a Potentiometer on A0 pin, 5v (5000 millivolt) and GND. Outer pins to 5v and GND, middle pin to A0
       * https://www.arduino.cc/en/tutorial/potentiometer
       * Turn it over and read values from 0 to 5000 millivolts
       */
               
      myNex.writeNum("NvoltageGraph.val", voltageGraph); // NvoltageGraph.val is a variable that we have create on Nextion.        
                                                        // we send the value of the voltageGraph variable on Arduino
                             // you can use the same name for variables on Nextion for easy recognition with a capital N infront
                             // Avoid the use of big variable names as every character is one byte to serial. 
                             // In here we use big names for the sake of the example.
      refresh_timer = millis();  // Set the timer equal to millis, create a time stamp to start over the "delay"
     
    }        
}

/* The rest work is on Nextion with the code on a timers user event

   sys0=NvoltageGraph.val*255/5000  // use sys0 to make the calculations
   add 2,0,sys0                  // add the value to the waveform with id=2 at first channel (0) 
   n0.val=NvoltageGraph.val      // write NvoltageGraph.val to n0.val
 //
 // Waveform can take values from 0-250
 // we map the value from arduino 0-5000 :
 // the math type for map the range is:
 // return = (value - low1) * (high2 - low2) / (high1 - low1) + low2
 // as both ranges start from zero low1 and low2 = 0 
 // the type becomes
 // return = value*hight2/hight1
 // return=value*255/5000
 //
 
 
 // And some graphic effects
if(n0.val>3300)
{
  n0.bco=RED
}else
{
  n0.bco=YELLOW
}
*/


The .zip file contains:

  • .HMI file for Nextion
  • .ino file for Arduino



File downloaded 1835 times.


Change Pages And Send Float Values on Nextion


This project aims to show how to manage page changes, how to send different data in different pages and how to limit the data sent to Nextion to minimum and avoid unnecessary use of the Serial and a possible buffer overflow.

This project also demonstrates the two ways you can send float values on Nextion, as Nextion DOES NOT SUPPORT float numbers. Instead it uses integer mathand 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. Go to the refreshPage0() function and see the comments on how we can send float values
Go to the refreshPage0() function and see the comments on how we can send float values.
The best way to demonstrate the change of the pages, is to use the DHT11 sensor, as it is very common and the chances of someone having one, are very high. Also, it gives us at least 3 different types of data.
*DHT11, DHT21 or DHT22 can be used.

Arduino & ESP Example:

/*
 * ChangePagesAndSentFloatValuesCode.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!
 * If you found  this work useful and has saved you time and effort,
 * Just simply paypal me at: seithagta@gmail.com
 */
 
// Compatible for Arduino and WeMos D1 mini
 
/* This project aims to show how to manage page changes,
 * how to send different data in different pages and 
 * how to limit the data sent to Nextion to minimum
 * and to avoid unnecessary use of the Serial and 
 * a possible buffer overflow.
 */
 
/* This project also demonstrates the two ways you can send float values
 * on Nextion, as Nextion DOES NOT SUPPORT float numbers. 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. 
 * Go to the refreshPage0() function and see the comments on how we can send float values 
 */
 
/* The best way to demonstrate the change of the pages,
 * is to use the DHT11 sensor, as it is very common and
 * the chances of someone having one, are very high.
 * Also, it gives us at least 3 different types of data.
 * DHT11, DHT21 or DHT22 can be used.
 */
 
//---------------------------------- 
// EasyNextionLibrary Initialization
//---------------------------------- 
#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

//--------------------------------------
// DHT Library and Sensor Initialization
//--------------------------------------
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library

#include "DHT.h"   // Include DHT library

#define DHTPIN 2   // Digital pin connected to the DHT sensor D2 for UNO, NANO, MEGA,  D4 for WeMos D1 mini

// Uncomment whatever type you're using!
#define DHTTYPE DHT11       // DHT 11
//#define DHTTYPE DHT22     // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21     // DHT 21 (AM2301)

#define GET_DATA_EVERY 2000 // DHT sensors can give us measurements every 2 seconds,
                            // as Adafruit suggests
                            
unsigned long getDataTimer = millis(); // Timer for GET_DATA_EVERY 

DHT dht(DHTPIN, DHTTYPE);

// Reading temperature or humidity takes about 250 milliseconds!

// We create the lastXX value variables, in order to store the last value that we have sent on Nextion,
// compare the last value with the new value (current value that we have take from sensor) and send 
// the new value ONLY if it is different from the last and not send data to Nextion if there is no need.

// For the needs of this project, the last value comparison might be not needed,
// but I write these, just to show how you can do it, if it is really needed, at more complicated projects.

float humidity = 0.0;     // Store the value of humidity
float lastSentHumidity = 0.0; // Store the last value of humidity that we have Sent on Nextion

float temperature = 0.0;     // Store the value of the temperature in Celsius
float lastSentTemperature = 0.0; // Store the last value of the temperature in Celsius that we have sent on Nextion

float fahrenheit = 0.0;     // Store the value of the temperature in Fahrenheit
float lastSentFahrenheit = 0.0; // Store the last value of the temperature in Fahrenheit that we have sent on Nextion

float heatIndexFahrenheit = 0.0;     // Store the value of the heat index in Fahrenheit
float lastSentHeatIndexFahrenheit = 0.0; // Store the last value of the heat index in Fahrenheit that we have sent on Nextion

float heatIndexCelsius = 0.0;     // Store the value of the heat index in Celsius
float lastSentHeatIndexCelsius = 0.0; // Store the last value of the heat index in Celsius that we have sent on Nextion

//---------------------------------- 
// Change Page Initialization
//---------------------------------- 

/* In order to update currentPageId variable with the current Id of the page, 
 * you must write at 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`
 */
#define DATA_REFRESH_RATE 1000 // 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, 
                               // as DHT sensor is a slow sensor and gives measurements every 2 seconds

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

bool newPageLoaded = false; // true when the page is first loaded ( lastCurrentPageId != currentPageId )

 
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 
  dht.begin();
  
  delay(500);               // give Nextion some time to finish initialize
  myNex.writeStr("page 0"); // For synchronizing Nextion page in case of reset to Arduino
  delay(50);
  myNex.lastCurrentPageId = 1; // At the first run of the loop, the currentPageId and the lastCurrentPageId
                               // must have different values, due to run the function firstRefresh()
}

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.
  readSensorValues();
  
  refereshCurrentPage();
  
  firstRefresh();
  
}

void firstRefresh(){ // This function's purpose is to update the values of a new page when is first loaded,
                     // and refreshing all the components with the current values as Nextion shows the Attribute val.

  if(myNex.currentPageId != myNex.lastCurrentPageId){ // If the two variables are different, means a new page is loaded.
    
    newPageLoaded = true;    // A new page is loaded
                             // This variable is used as an argument at the if() statement on the refreshPageXX() voids, 
                             // in order when is true to update all the values on the page with their current values
                             // with out run a comparison with the last value.
    
    switch(myNex.currentPageId){
      case 0:
        refreshPage0();
        break;
      
      case 1:
        refreshPage1();
        break;
        
      case 2:
        refreshPage2();
        break;
        
      case 3:
        refreshPage3();
        break;
    }
    
    newPageLoaded = false;  // After we have updated the new page for the first time, we update the variable to false.
                            // Now the values updated ONLY if the new value is different from the last Sent value.
                            // See void refreshPage0()
    
    myNex.lastCurrentPageId = myNex.currentPageId; // Afer the refresh of the new page We make them equal,
                                                   // in order to identify the next page change.
  }
}

void readSensorValues(){

  if((millis() - getDataTimer) > GET_DATA_EVERY){
  
    humidity = dht.readHumidity(); // Read relative humidity
    
    temperature = dht.readTemperature(); // Read temperature as Celsius (the default)    
    fahrenheit = dht.readTemperature(true);// Read temperature as Fahrenheit (isFahrenheit = true)
    
    heatIndexFahrenheit = dht.computeHeatIndex(fahrenheit, humidity);// Compute heat index in Fahrenheit (the default)
    heatIndexCelsius = dht.computeHeatIndex(temperature, humidity, false); // Compute heat index in Celsius (isFahreheit = false)
    
    getDataTimer = millis();
    
  }
}

void refereshCurrentPage(){
// In this function we refresh the page currently loaded every DATA_REFRESH_RATE
  if((millis() - pageRefreshTimer) > DATA_REFRESH_RATE){
    switch(myNex.currentPageId){
      case 0:
        refreshPage0();
        break;
      
      case 1:
        refreshPage1();
        break;
        
      case 2:
        refreshPage2();
        break;
        
      case 3:
        refreshPage3();
        break;
     
    }
  }
}

void refreshPage0(){
  // Use lastSentTemperature, in order to update the components ONLY when their value has changed 
  // and avoid sending unnecessary data over Serial.
  // Also with the newPageLoaded boolean variable, we bypass the if() argument of temperature != lastSentTemperature (last value comparison)
  // so as to update all the values on Nextion when a new page is loaded, independant of if the values have changed
  
  if(temperature != lastSentTemperature || newPageLoaded == true){
    
    String tempString = String(temperature, 1); // Convert the float value to String, in order to send it to t0 textbox on Nextion
    myNex.writeStr("t0.txt", tempString);       //Write the String value to t0 Textbox component
    
    int tempInt = temperature*10;    // We convert the float to int, in order to send it to x0 Xfloat component on Nextion
                                     // We multiply it x10, because Xfloat will put a comma automatically after the last digit
                                     // if vvs1 is set to 1
    myNex.writeNum("x0.val", tempInt);
    
    lastSentTemperature = temperature;   // We store the last value that we have sent on Nextion, we wait for the next comparison 
                                         // and send data only when the value of temperature changes
  }
}

void refreshPage1(){
  
  if(humidity != lastSentHumidity || newPageLoaded == true){
    
    String tempString = String(humidity, 1);
    myNex.writeStr("t0.txt", tempString);
    
    int tempInt = humidity*10;
    myNex.writeNum("x0.val", tempInt);
    
    lastSentHumidity = humidity;
  }
}

void refreshPage2(){

  if(fahrenheit != lastSentFahrenheit || newPageLoaded == true){
    
    String tempString = String(fahrenheit, 1);
    myNex.writeStr("t0.txt", tempString);
    
    int tempInt = fahrenheit*10;
    myNex.writeNum("x0.val", tempInt);
    
    lastSentFahrenheit = fahrenheit;
  }
}

void refreshPage3(){

  if(heatIndexCelsius != lastSentHeatIndexCelsius || newPageLoaded == true){
    
    String tempString = String(heatIndexCelsius, 1);
    myNex.writeStr("t0.txt", tempString);
    
    int tempInt = heatIndexCelsius*10;
    myNex.writeNum("x0.val", tempInt);
    
    lastSentHeatIndexCelsius = heatIndexCelsius;
  }
  
  if(heatIndexFahrenheit != lastSentHeatIndexFahrenheit || newPageLoaded == true){
    String tempString = String(heatIndexFahrenheit, 1);
    myNex.writeStr("t1.txt", tempString);
    
    int tempInt = heatIndexFahrenheit*10;
    myNex.writeNum("x1.val", tempInt);
    
    lastSentHeatIndexFahrenheit = heatIndexFahrenheit;
  }
  
}
                   

The .zip file contains:

  • .HMI file for Nextion
  • .ino file for Arduino



File downloaded 1867 times.


Four Step Example to Power ON OFF a LED from Nextion


trigger() is the most important method 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 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.
Example: printh 23 02 54 01 to call trigger1() ... printh 23 02 54 0A to call trigger10() and so on...

Arduino Example:

/*
 * 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
 */
 
/* I have invested time and resources providing open source codes, like this one. 
 * Please do not hesitate to support my work!
 * If you found  this work useful and has saved you time and effort,
 * Just simply paypal me at: seithagta@gmail.com
 */
 
// Compatible for Arduino 

/* trigger() is the most important method 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 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.
 * Example: printh 23 02 54 01 to call trigger1() ... printh 23 02 54 0A to call trigger10() and so on...
 */

/*
  Declare the void by simply writing:
  void trigger1(){
  [ put your code here !!!!]
  }
*/
 
#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          
  digitalWrite(LED_BUILTIN, LOW); // Setting the built-in LED to LOW = off
}

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

                    

ESP Example:

/*
 * 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
 */
 
/* I have invested time and resources providing open source codes, like this one. 
 * Please do not hesitate to support my work!
 * If you found  this work useful and has saved you time and effort,
 * Just simply paypal me at: seithagta@gmail.com
 */
 
// Compatible for WeMos D1 mini
 
/* trigger() is the most important method 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 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.
 * Example: printh 23 02 54 01 to call trigger1() ... printh 23 02 54 0A to call trigger10() and so on...
 */

/*
  Declare the void by simply writing:
  void trigger1(){
  [ put your code here !!!!]
  }
*/
 
#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            
  digitalWrite(LED_BUILTIN, HIGH); // Setting the built-in LED to HIGH = off
}

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) == LOW){
    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) == HIGH){
    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"
  }
}

                    

The .zip file contains:

  • .HMI file for Nextion
  • .ino file for Arduino & ESP



File downloaded 1870 times.


Read And Write Number on Nextion


This example shows how to send and read values to and from Nextion's numeric components, like:
Numeric component, float component and also the attributes of all components like .bco(background color), .pco(font color) etc.

Arduino & ESP Example:

/*
 * ReadAndWriteNumberCode.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!
 * If you found  this work useful and has saved you time and effort,
 * Just simply paypal me at: seithagta@gmail.com
 */

 // Compatible for Arduino and WeMos D1 mini ESP8266 
 
#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
uint32_t number = 0;
uint32_t lastnumber = 0;

#define LOOP_TIME 2000
unsigned long timer ;

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
  delay(500);        // Wait for Nextion to start
  
  timer = millis();
}

void loop(){

  if((millis() - timer) > LOOP_TIME){
    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;                  // The chances of getting a wrong value is one in a million.
                                            // Use this if() to ensure it if you believe it is needed.    
                                            // You can either call the readNumber funtion again 
                                            // or set a safe value in case of failure.
                                            // Ex: number = 2222; or use the last value method
    } else if(number == 7777){
      number = lastnumber;
    }
    
    myNex.writeNum("n1.val", number);       // After that, we send the number variable, as value to n1
    
    number = myNex.readNumber("page0.bco"); // Read and store the background color code to number variable
    if(number == 33823){
      myNex.writeNum("page0.bco", 63488);   // Change background color to RED(63488) if it was BLUE(33823)
    }else if(number == 63488){
      myNex.writeNum("page0.bco", 33823);   // Change background color to BLUE(33823) if it was RED(63488)
    }
                  // 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
  
    timer = millis();
               
  }
}

                

The .zip file contains:

  • .HMI file for Nextion
  • .ino file for Arduino



File downloaded 1878 times.


Trigger fuctions on Arduino From Nextion


This is the most important method 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 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.
Example: printh 23 02 54 01 to call trigger1() ... printh 23 02 54 0A to call trigger10() and so on...

Aduino Example:

/*
 * TriggerCode.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!
 * If you found  this work useful and has saved you time and effort,
 * Just simply paypal me at: seithagta@gmail.com
 */
 
// Compatible for Arduino

/* This is the most important method 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 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.
 * Example: printh 23 02 54 01 to call trigger1() ... printh 23 02 54 0A to call trigger10() and so on...
 */

/*
  Declare the void by simply writing:
  void trigger1(){
  [ put your code here !!!!]
  }
*/

#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
  digitalWrite(LED_BUILTIN, LOW);
}

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

  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"
    myNex.writeNum("p0.pic", 1);    // Set picture 1 as background picture for p0
    
  }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 "OFF"
    myNex.writeNum("p0.pic", 0);     // Set picture 0 as background picture for p0 picture component
  }
}

void trigger2(){
  // To call this void send from Nextion's component's Event:  printh 23 02 54 02
  // In this exmaple, we send this command from the Release Event of b1 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
  
  if(digitalRead(LED_BUILTIN) == HIGH){
    digitalWrite(LED_BUILTIN, LOW);  // Start the function with the LED off
    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 "OFF"
    myNex.writeNum("p0.pic", 0);     // Set picture 0 as background picture for p0 picture component
  }
  
  myNex.writeStr("t0.txt", "LED STROBE\\rON");
  for(int i = 0; i < 10; i++){
    for(int x = 0; x < 10; x++){
      digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // If LED_BUILTIN is ON, turn it OFF, or the opposite
      delay(50);
    }
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));   // If LED_BUILTIN is ON, turn it OFF, or the opposite
    delay(500);
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));   // If LED_BUILTIN is ON, turn it OFF, or the opposite
  }
  myNex.writeStr("t0.txt", "LED STROBE\\rOFF"); // Setting the text of t0 textbox to "LED STROBE OFF"
                                                // \\r is the newline character for Nextion.
                                                // The text will look like this:
                                                // 1st line: LED STROBE
                                                // 2nd line: OFF                                                
}

ESP Example:

/*
 * TriggerCode.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 is the most important method 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 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.
 * Example: printh 23 02 54 01 to call trigger1() ... printh 23 02 54 0A to call trigger10() and so on...
 */

/*
  Declare the void by simply writing:
  void trigger1(){
  [ put your code here !!!!]
  }
*/

#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
  digitalWrite(LED_BUILTIN, HIGH);
}

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

  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // If LED_BUILTIN is ON, turn it OFF, or the opposite
  if(digitalRead(LED_BUILTIN) == LOW){
    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"
    myNex.writeNum("p0.pic", 1);    // Set picture 1 as background picture for p0
    
  }else if(digitalRead(LED_BUILTIN) == HIGH){
    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 "OFF"
    myNex.writeNum("p0.pic", 0);     // Set picture 0 as background picture for p0 picture component
  }
}

void trigger2(){
  // To call this void send from Nextion's component's Event:  printh 23 02 54 02
  // In this exmaple, we send this command from the Release Event of b1 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
  
  if(digitalRead(LED_BUILTIN) == LOW){
    digitalWrite(LED_BUILTIN, HIGH);  // Start the function with the LED off
    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 "OFF"
    myNex.writeNum("p0.pic", 0);     // Set picture 0 as background picture for p0 picture component
  }
  
  myNex.writeStr("t0.txt", "LED STROBE\\rON");
  for(int i = 0; i < 10; i++){
    for(int x = 0; x < 10; x++){
      digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // If LED_BUILTIN is ON, turn it OFF, or the opposite
      delay(50);
    }
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));   // If LED_BUILTIN is ON, turn it OFF, or the opposite
    delay(500);
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));   // If LED_BUILTIN is ON, turn it OFF, or the opposite
  }
  myNex.writeStr("t0.txt", "LED STROBE\\rOFF"); // Setting the text of t0 textbox to "LED STROBE OFF"
                                                // \\r is the newline character for Nextion.
                                                // The text will look like this:
                                                // 1st line: LED STROBE
                                                // 2nd line: OFF                                                
}

The .zip file contains:

  • .HMI file for Nextion
  • .ino file for Arduino & ESP



File downloaded 1388 times.


Write Text And Commands on Nextion


This example demonstrates the two uses of writeStr() function.
writeStr(String, String) is the first one. We can write text on textboxes.
writeStr(String) is the second and we can send ANY command we want, based on the Instruction Set.

Aduino & ESP Example:

/*
 * 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!
 * If you found  this work useful and has saved you time and effort,
 * Just simply paypal me at: seithagta@gmail.com
 */
 
#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
}

The .zip file contains:

  • .HMI file for Nextion
  • .ino file for Arduino



File downloaded 1484 times.