EasyNextionLibrary

repository·master·Indexed 41 days ago

https://github.com/seithan/easynextionlibrary

A simplified Arduino library for communication between Arduino and Nextion HMI displays. It abstracts serial protocols into simple functions and a trigger-based event system, allowing developers to execute C++ functions via Nextion touch events. Key features include writeNum(), writeStr(), readNumber(), readStr(), and a custom command protocol for advanced implementations.

Tokens
10.7K
Snippets
39
Records
49
Agent score
96%

What's inside EasyNextionLibrary

  1. Track current and previous page IDs

    master

    The library provides two public variables to manage page state:

    1. currentPageId: Stores the ID of the currently loaded page. Use this to decide which components to update when the page changes.
    2. lastCurrentPageId: Stores the ID of the page that was active before the current one.

    Pattern: Refreshing data on page change To avoid sending unnecessary data, compare currentPageId with lastCurrentPageId. Only send refresh commands when they differ, then update lastCurrentPageId to match.

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

    master

    The trigger() function is the most important feature of the library. It allows you to execute specific blocks of Arduino code directly from Nextion HMI events (like a button press).

    How it works:

    1. In Arduino: Declare a void function with a specific name, such as trigger0(), trigger1(), etc. (up to trigger50() by default, though this can be extended up to 255 in the source).
    2. In Nextion: Use the printh command in a Nextion Event (e.g., Touch Release Event) to call the corresponding function using its HEX ID.

    Mapping Table:

    Nextion CommandArduino Function
    printh 23 02 54 00trigger0()
    printh 23 02 54 01trigger1()
    printh 23 02 54 0Atrigger10()
    printh 23 02 54 32trigger50()

    Best Practices:

    • You can call the same triggerX() function from multiple components or pages.
    • To change the predefined names, you must modify trigger.cpp.
    #include "EasyNextionLibrary.h"
    
    EasyNex myObject(Serial);
    
    void setup(){
      myObject.begin(9600);
      pinMode(LED_BUILTIN, OUTPUT);
    }
    
    void loop(){
      myObject.NextionListen();
    }
    
    // This function is called when Nextion sends 'printh 23 02 54 00'
    void trigger0(){
      digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    }
  3. How triggers and the custom protocol work

    master

    The library uses a custom protocol to map Nextion touch events to specific C++ functions.

    When you define a function like void trigger0(), the library listens for a specific byte sequence. For trigger0, the sequence is 23 02 54 00 (in HEX).

    To make a button on your Nextion screen execute trigger0(), you must go to the Touch Release Event of that button in the Nextion Editor and enter the command: printh 23 02 54 00

    This allows you to bridge the Nextion UI and your Arduino code with minimal complexity.

  4. Quickstart: Use EasyNextionLibrary in 4 steps

    master

    To use the library, follow these four steps:

    1. Include the library and instantiate the object: Pass the Hardware Serial you intend to use (e.g., Serial) to the EasyNex constructor.
    2. Initialize the object: Call begin(baudrate) in setup(). If no baud rate is provided, it defaults to 9600.
    3. Listen for events: Call myNex.NextionListen() inside your loop() function. This must be called repeatedly to process touch events from the Nextion panel.
    4. Define triggers: Create a void function named triggerX (e.g., trigger0()) and place your logic inside. To execute this function, configure a button in the Nextion Editor's Touch Release Event to send the corresponding hex command (e.g., printh 23 02 54 00 for trigger0).
    #include "EasyNextionLibrary.h"
    
    EasyNex myNex(Serial); // 1. Create object
    
    void setup(){
      myNex.begin(9600); // 2. Begin with baud rate
      pinMode(LED_BUILTIN, OUTPUT);
    }
    
    void loop(){
      myNex.NextionListen(); // 3. Listen for events
    }
    
    // 4. Define a trigger function
    void trigger0(){
      digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    }
  5. Sync Nextion page IDs with Arduino

    master

    To ensure the library correctly tracks which page is currently active on the Nextion display, you must manually sync the page ID. This is done by adding a printh command to the Preinitialize Event of every page in the Nextion Editor.

    The command format is printh 23 02 50 XX, where XX is the HEX representation of the page ID.

    Examples:

    • Page 0: printh 23 02 50 00
    • Page 9: printh 23 02 50 09
    • Page 10: printh 23 02 50 0A
    // In Nextion Editor -> Page Preinitialize Event:
    printh 23 02 50 00
  6. Implement a custom protocol with easyNexReadCustomCommand()

    master

    You can define a custom communication protocol between Nextion and Arduino. The library uses a weak attribute for easyNexReadCustomCommand(), meaning you must declare this function in your main Arduino code to enable custom command handling.

    Command Format

    Commands sent from Nextion via printh should follow this structure: # (start marker) | len (number of bytes) | cmd (command group) | id (property 1) | id2 (property 2)

    Implementation Steps

    1. In Nextion: Send commands using printh. For example, to send command 'L' (Hex 4C) with index 0 and value 10 (Hex 0A): printh 23 03 4C 00 0A.
    2. In Arduino: Implement easyNexReadCustomCommand() and use a switch statement on myObject.cmdGroup to handle different command groups. Use myObject.readByte() to extract the remaining parameters.
    // Example implementation of custom command handling
    void easyNexReadCustomCommand() {
      int arrayPlace;
      int value;
      
      switch(myNex.cmdGroup) {
        case 'L': // Command group 'L'
          arrayPlace = myNex.readByte();
          value = myNex.readByte();
          dataL[arrayPlace] = value;  
          break; 
    
        case 'S': // Command group 'S'
          arrayPlace = myNex.readByte();
          value = myNex.readByte();
          dataS[arrayPlace] = value;  
          break;
      }  
    }
  7. Install EasyNextionLibrary in Arduino IDE

    master

    You can install the library using two methods:

    1. In the Arduino IDE, navigate to Sketch > Include Library > Manage Libraries.
    2. Search for EasyNextionLibrary in the search bar.
    3. Select the latest version and click Install.

    Method 2: Manual Installation

    1. Download the latest release from the GitHub repository.
    2. Extract the .zip file.
    3. Copy the EasyNextionLibrary folder into your Arduino libraries directory (typically ..../Arduino/libraries/).
  8. Track the current and previous Nextion page

    master

    The library provides variables to track page changes.

    Important Setup for currentPageId: To use currentPageId, you must manually send a specific command in the Preinitialize Event of every page on the Nextion side using the format printh 23 02 50 xx, where xx is the page ID in hex.

    • currentPageId: The ID of the page currently shown on the Nextion.
    • lastCurrentPageId: The ID of the previously displayed page.

    Example:

    // In your Arduino code
    int current = myObject.currentPageId;
    int previous = myObject.lastCurrentPageId;
  9. How trigger() functions work

    master

    The trigger() system is the core of the library, allowing you to map Nextion events to specific Arduino functions.

    1. Define the function in Arduino

    Declare a void function with a specific name between trigger0 and trigger50. For example, to create a function for the first trigger, write:

    void trigger0() {
      // Your custom code here
    }

    2. Call the function from Nextion

    In the Nextion Editor, use the printh command in a component's event (like a Touch Release Event) to trigger the function. The command follows the pattern printh 23 02 54 XX, where XX is the HEX ID of the trigger.

    Nextion CommandArduino Function
    printh 23 02 54 00trigger0()
    printh 23 02 54 01trigger1()
    printh 23 02 54 0Atrigger10()
    printh 23 02 54 32trigger50()

    Note: You can call the same trigger from multiple components or pages. You can also define up to 255 functions by modifying trigger.cpp.

    // Arduino side
    void trigger0() {
      digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    }
    
    // Nextion side (Touch Release Event)
    printh 23 02 54 00
  10. Sync currentPageId with Nextion pages

    master

    The library uses currentPageId to track which page is currently active on the Nextion display. This is critical for ensuring data is sent to the correct page.

    1. Update the library variable

    To keep the library in sync, you must add a command to the Preinitialize Event of every page in the Nextion Editor using the printh command. The command format is printh 23 02 50 XX, where XX is the page ID in HEX.

    • Page 0: printh 23 02 50 00
    • Page 9: printh 23 02 50 09
    • Page 10: printh 23 02 50 0A

    2. Detect page changes

    You can use lastCurrentPageId to detect when a user has navigated to a new page, allowing you to refresh screen data only when necessary.

    if (myObject.currentPageId != myObject.lastCurrentPageId) {
        if (myObject.currentPageId == 0) {
            // Refresh page 0 components
        }
        myObject.lastCurrentPageId = myObject.currentPageId;
    }

    3. Manual check

    You can also read the current page ID directly using the Nextion system command dp:

    int x = myObject.readNumber("dp"); // Returns current page ID
    // In Nextion Preinitialize Event for Page 0:
    // printh 23 02 50 00
    
    // In Arduino main loop:
    if (myObject.currentPageId != myObject.lastCurrentPageId) {
        // Page changed, refresh UI
        myObject.lastCurrentPageId = myObject.currentPageId;
    }
  11. Syncing Page IDs with currentPageId and lastCurrentPageId

    master

    The library tracks the current page to ensure data is sent to the correct component on the active screen.

    currentPageId

    Stores the ID of the currently loaded page. To keep this in sync, you must add a command to the Preinitialize Event of every page in the Nextion Editor:

    • printh 23 02 50 XX (where XX is the Page ID in HEX).
    • Example for Page 0: printh 23 02 50 00.
    • Tip: You can also read the current page ID directly using myObject.readNumber("dp").

    lastCurrentPageId

    Stores the previous value of currentPageId. Use this to detect when a page change has occurred so you can refresh the UI with new data only when necessary.

    // Detect page change and refresh data
    if (myObject.currentPageId != myObject.lastCurrentPageId) {
        if (myObject.currentPageId == 0) {
            // Refresh page 0 components
        } else if (myObject.currentPageId == 1) {
            // Refresh page 1 components
        }
        // Update lastCurrentPageId to prevent continuous refreshing
        myObject.lastCurrentPageId = myObject.currentPageId;
    }
  12. Quickstart: Using EasyNextionLibrary in Arduino

    master

    To use the library, follow these four steps:

    1. Include the library and instantiate an EasyNex object, passing the Hardware Serial you intend to use (e.g., Serial).
    2. Initialize the object in setup() using .begin(baudrate). The default baud rate is 9600.
    3. Listen for events by placing myNex.NextionListen() inside your loop() function. This must be called repeatedly to respond to touch events.
    4. Define triggers by creating void triggerX() functions (where X is 0-50) to execute specific code when called from the Nextion display.
    #include "EasyNextionLibrary.h"
    
    EasyNex myNex(Serial);
    
    void setup() {
      myNex.begin(9600);
      pinMode(LED_BUILTIN, OUTPUT);
    }
    
    void loop() {
      myNex.NextionListen();
    }
    
    void trigger0() {
      // Your code here
    }