How to go from one page to another in Nextion using a rotary switch ?

Hello,
I would like your help please regarding programming the Nextion Display NX4024T032_011 with arduino. I made several page on the display and what I am trying to do is using a rotary switch of 6 positions to surf the pages means position 1 on the rotary switch should go to page0, position 2 to page1 and so on. So far I did not find any tutorial but about touching the screen to go to next page.
How can I do this using which line of code ?

Thanks in advance :slight_smile:

Hello firashelou,

You read the rotary switch and use it to determine which page you want. I suggest you maintain a global variable something like:

uint8_t page;

Which holds the page the Nextion is on.
To tell the Nextion to change page you can use something like:

  Serial.print ("page");
  Serial.print (page);
  Serial.write(0xff);
  Serial.write(0xff);
  Serial.write(0xff);

Note I put that together in a hurry and have not tested it, apologies if it is not quite right.

Just a thought, what kind of rotary switch are you thinking of? I suggest a rotary encoder is what will work best, these need only 2 wires to connect to the Arduino. There are plenty of discussions on here about how to read them.

PerryBebbington:
Just a thought, what kind of rotary switch are you thinking of? I suggest a rotary encoder is what will work best, these need only 2 wires to connect to the Arduino. There are plenty of discussions on here about how to read them.

hello PerryBebbington thank you for your reply
ok I will test and post back about it

regarding the rotary switch that i have it is like this

@PerryBebbington i tried it and it did not work so i added the escape and added = in case but none worked

    uint8_t page0 = "Main";
    uint8_t page1 = "Temp";
    uint8_t page2 = "SimBat";
    uint8_t page3 = "CarBat";
    uint8_t page4 = "Light";
    uint8_t page5 = "Pedal";   
    
    Serial.print ("page");
    //Serial.print("\"");
    Serial.print ("Pedal");
    //Serial.print("\"");
    Serial.write(0xff);
    Serial.write(0xff);
    Serial.write(0xff);

Regarding the rotary switch that i have it is like this

The you will need an input for each switch position. Ground the common, enable pull ups for each input.

 uint8_t page0 = "Main";

Please go and study C variable types. You are trying to store text in a 8 bit unsigned integer.

I meant a single variable that holds the page number, not a variable per page that holds text.

Also study my previous post and use exactly what I said.

PerryBebbington:
The you will need an input for each switch position. Ground the common, enable pull ups for each input.

 uint8_t page0 = "Main";

Please go and study C variable types. You are trying to store text in a 8 bit unsigned integer.
I meant a single variable that holds the page number, not a variable per page that holds text.
Also study my previous post and use exactly what I said.

ah ok i see,
well for the switch i connected resistors between the pins of the switch and i made it act as a potentiometer so are good to go i am getting different values for different positions from A0 of the arduino

regarding the display i was digging around on google and found a post where they used Nextion library so i checked the examples from the library and used codes from it and i managed to change the page but there is too much flickering and the page takes too much time to change

here are my code so far:

#include "Nextion.h"

int potPin = A0;    // select the input pin for the potentiometer
int val = 0;       // variable to store the value coming from the sensor

NexPage page0    = NexPage(0, 0, "page0");
NexPage page1    = NexPage(1, 0, "page1");
NexPage page2    = NexPage(2, 0, "page2");
NexPage page3    = NexPage(3, 0, "page3");
NexPage page4    = NexPage(4, 0, "page4");
NexPage page5    = NexPage(5, 0, "page5");

void setup() {
  Serial.begin(9600);
  //pinMode(ledPin, OUTPUT);
}

void loop() {
  val = analogRead(potPin);    // read the value from the potentiometer
  
  if(val < 750 && val > 735){
    // Go to page 0 which is Main on the Nextion Display
    //sendCommand("page0");
    page0.show();

  } else if (val < 660 && val > 640) {
    // Go to page 1 which is Temp on the Nextion Display
    //sendCommand("page1");
    page1.show();
  }

}

Well for the switch I connected resistors between the pins of the switch and I made it act as a potentiometer so are good to go I am getting different values for different positions from A0 of the arduino.

Excellent idea! ++Karma;

Regarding the display i was digging around on google and found a post where they used Nextion library so i checked the examples from the library and used codes from it and I managed to change the page but there is too much flickering and the page takes too much time to change

Now you are in territory I can't help with as I don't use the Nextion libraries, sorry. I can help you more if you use my methods.

My next suggestion is to open your Nextion configuration in the Nextion IDE and use the debug feature. Type into the instruction input area whatever you want to test and see if you get the expected result. When you know what works then you can write code on your Arduino to send to the Nextion.

Sorry I got involved.

You can try this:

int potPin = A0;    // select the input pin for the potentiometer
int val = 0;       // variable to store the value coming from the sensor


void setup() {
  Serial.begin(9600);
  //pinMode(ledPin, OUTPUT);
}

void loop() {
  val = analogRead(potPin);    // read the value from the potentiometer
 
  if(val < 750 && val > 735){
    // Go to page 0 which is Main on the Nextion Display
     Serial.print("page 0"); // or Serial.print("page Main"); //
     Serial.print("\xFF\xFF\xFF"); // Nextion end command

  } else if (val < 660 && val > 640) {
    // Go to page 1 which is Temp on the Nextion Display
     Serial.print("page 1"); // or Serial.print("page Temp"); //
     Serial.print("\xFF\xFF\xFF"); // Nextion end command
  }

}

-Thanasis Seitanis

PerryBebbington:
Excellent idea! ++Karma;Now you are in territory I can't help with as I don't use the Nextion libraries, sorry. I can help you more if you use my methods.

My next suggestion is to open your Nextion configuration in the Nextion IDE and use the debug feature. Type into the instruction input area whatever you want to test and see if you get the expected result. When you know what works then you can write code on your Arduino to send to the Nextion.

Thanks for the karma :slight_smile:

Ok i still want to know your method please

Ok i still want to know your method please.

Read 'Using Nextion displays with Arduino' at the top of the Displays forum.

PerryBebbington:
Read 'Using Nextion displays with Arduino' at the top of the Displays forum.

I started reading it last time but ok i will continue with it :slight_smile:

Edit:
Perry i did not find any related to changing the page from arduino command, you talked about changing the page from a button on the nextion display itself by touch event

Seithan:
Sorry I got involved.

You can try this:

int potPin = A0;    // select the input pin for the potentiometer

int val = 0;      // variable to store the value coming from the sensor

void setup() {
  Serial.begin(9600);
  //pinMode(ledPin, OUTPUT);
}

void loop() {
  val = analogRead(potPin);    // read the value from the potentiometer

if(val < 750 && val > 735){
    // Go to page 0 which is Main on the Nextion Display
    Serial.print(“page 0”); // or Serial.print(“page Main”); //
    Serial.print("\xFF\xFF\xFF"); // Nextion end command

} else if (val < 660 && val > 640) {
    // Go to page 1 which is Temp on the Nextion Display
    Serial.print(“page 1”); // or Serial.print(“page Temp”); //
    Serial.print("\xFF\xFF\xFF"); // Nextion end command
  }

}




-Thanasis Seitanis

Hello Seithan, thank you for your reply, I will test your suggestion when i reach home and let you know :slight_smile:

Perry i did not find any related to changing the page from arduino command, you talked about changing the page from a button on the nextion display itself by touch event

I think you are confusing a few things:

I mentioned that any help I could give you would be limited as you are using Nextion libraries, not my methods. You asked me about my methods and I suggested the tutorial. I didn't say that within my tutorial there were specific instructions on how to have the Arduino tell the Nextion to change page.

If you write code to send:
page 1 (not Page 1)
to the Nextion it will go to page 1.

Something like this will do that:

uint8_t active_page = 1;  //Or whatever page you want
  Serial.print ("page");
  Serial.print (active_page);
  Serial.write (0xff);
  Serial.write (0xff);
  Serial.write (0xff);

However, for all I know the Nextion library might interfere with this, I have no idea.

When I suggested this earlier you wrote something quite different and then told me it didn't work...

PerryBebbington:
I think you are confusing a few things:

I mentioned that any help I could give you would be limited as you are using Nextion libraries, not my methods. You asked me about my methods and I suggested the tutorial. I didn't say that within my tutorial there were specific instructions on how to have the Arduino tell the Nextion to change page.

If you write code to send:
page 1 (not Page 1)
to the Nextion it will go to page 1.

Something like this will do that:

However, for all I know the Nextion library might interfere with this, I have no idea.

When I suggested this earlier you wrote something quite different and then told me it didn't work...

I'm sorry Perry i did not mean to not follow your instructions, what happened is i entered the code you gave me but i made a mistake with the variable type i though it can be used as a string and because i had the pages named as a string so i played around with the code adding lines and eliminating lines.

So for what you suggested in the last post i used it, i had to add a space after "page " and it worked but it is taking so much time to change the page and there is too much flickering. So what do you think might be the solution for this ? (thanks again Perry i really appreciate your help)

    Serial.print ("page ");
    Serial.print (page0);
    Serial.write (0xff);
    Serial.write (0xff);
    Serial.write (0xff);

So for what you suggested in the last post i used it, i had to add a space after "page " and it worked but it is taking so much time to change the page and there is too much flickering. So what do you think might be the solution for this ?

Yes, a space is good. I missed that, ++Karma; for correcting my mistake :slight_smile:

I suspect, but I don't know as I can't see all your code, that you are sending this repeatedly instead of just once to change the page.

I return to my ealier suggestion; read my tutorial. You will however have to choose between my methods and using the Nextion libraries, they are not intended to be mixed.

Hello,

Like Perry said before, you are sending a command to change the page continuously and you are changing the page all the time. Meanwhile, I made a piece of code for you, as I suspected that this was going to happen.

#define Nextion Serial
/* define that Serial will de writed as Nextion (when we write Nextion.print the  compiler read Serial.print)    
 *By define the Nextion as Serial you can change at ones the serial port at the hole code,
 * with changing the Serial to Serial1 for example
 */  
#define POTPIN A0   // select the input pin for the potentiometer
#define RETRY_LOOP   100           // The number of times that it will read the value of potentiometer for more accurate reading
int page_selector_val = 0;       // variable to store the value coming from the sensor
int last_page_selector_val = 0;  // variable to store the last value coming from sensor 
byte page_loaded =0;               // variable to store the page ID that is loaded on Nextion
byte goto_page ;                //  variable to store the page that is selected from the switch

void setup() {
  Nextion.begin(9600);
  delay(500) // give Nextion some time to finish initialize
          Nextion.print("page 0"); // for synchronize Nextion in case of reset to Arduino 
          Nextion.print("\xFF\xFF\xFF"); 
  Nextion_serial_listen(); // reading Nextion first time
  read_page_selector(); // This is going to read the selector and load the selected page on Nextion for first start up.
}

void loop() {
  
  read_page_selector();

}
void read_page_selector()
{             
    // ---- Software filter. Average values for more accurate reading----                  
    uint32_t adc_val = 0;                 // 32-bit variable used for adding up analogRead of potentiometer.
    for(int i = 0; i < RETRY_LOOP; i++){
     adc_val += analogRead(POTPIN);        // at adc_val, it adds the value of analogRead as long as the number of times are less than the RETRY_LOOP
     delay(1);        // one ms delay between readings.
                      // with RETRY_LOOP set to 100 in total 100ms needed to have the reading 
                      // for faster but not so accurate read remove delay and set RETRY_LOOP to 1000
  }
    page_selector_val = (adc_val / RETRY_LOOP);  
    
    // Check that the reading is changed and send commands only when needed to avoid buffer overflow on Nextion
    if(page_selector_val != last_page_selector_val){
        
       if(page_selector_val < 750 && page_selector_val > 735){
            goto_page = 0;
        }
       if (page_selector_val < 660 && page_selector_val > 640) {
            goto_page = 1;
        } 
       if(goto_page != page_loaded){
          Nextion.print("page "); 
          Nextion.print(goto_page);
          Nextion.print("\xFF\xFF\xFF"); // Nextion end command
        }
     last_page_selector_val = page_selector_val ; // Refresh the value of <last_page_selector_val> variable
    }    
}

As it is very important for Arduino to know what page is currently loaded on Nextion, you must use: page_loaded=getCurrentPage();

This helps you get the current id of the page loaded on Nextion.

If you are lucky, of course, and the library that you are using is supports the command without any bugs. :slight_smile:

Most libraries have an issue with taking the current page ID.

You must take seriously what Perry told you, to avoid using libraries.

If you decide not to use libraries and make a code for this as an example, to see how it works.

So, the way is based on a custom protocol that you must create upon your needs and I am providing you a function that you are able to read this from serial.

If you want to see more examples on how you can create your custom protocol, you can find then at
How to send values and store them on Arduino

How to control relays

Or from my website at:
https://www.seithan.com

#define Nextion Serial
/* define that Serial will de writed as Nextion (when we write Nextion.print the  compiler read Serial.print)    
 *By define the Nextion as Serial you can change at ones the serial port at the hole code,
 * with changing the Serial to Serial1 for example
 */  
#define POTPIN A0   // select the input pin for the potentiometer
#define RETRY_LOOP   100           // The number of times that it will read the value of potentiometer for more accurate reading
int page_selector_val = 0;       // variable to store the value coming from the sensor
int last_page_selector_val = 0;  // variable to store the last value coming from sensor 
byte page_loaded =0;               // variable to store the page ID that is loaded on Nextion
byte goto_page ;                //  variable to store the page that is selected from the switch
// getCurrentPage ()
void setup() {
  Nextion.begin(9600);
  delay(500) // give Nextion some time to finish initialize
          Nextion.print("page 0"); // for synchronize Nextion in case of reset to Arduino 
          Nextion.print("\xFF\xFF\xFF"); 
  Nextion_serial_listen(); // reading Nextion first time
  read_page_selector(); // This is going to read the selector and load the selected page on Nextion for first start up.
}

void loop() {
  
  Nextion_serial_listen();
  read_page_selector();

}
void read_page_selector()
{             
    // ---- Software filter. Average values for more accurate reading----                  
    uint32_t adc_val = 0;                 // 32-bit variable used for adding up analogRead of potentiometer.
    for(int i = 0; i < RETRY_LOOP; i++){
     adc_val += analogRead(POTPIN);        // at adc_val, it adds the value of analogRead as long as the number of times are less than the RETRY_LOOP
     delay(1);        // one ms delay between readings.
                      // with RETRY_LOOP set to 100 in total 100ms needed to have the reading 
                      // for faster but not so accurate read remove delay and set RETRY_LOOP to 1000
  }
    page_selector_val = (adc_val / RETRY_LOOP);  
    
    // Check that the reading is changed and send commands only when needed to avoid buffer overflow on Nextion
    if(page_selector_val != last_page_selector_val){
        
       if(page_selector_val < 750 && page_selector_val > 735){
            goto_page = 0;
        }
       if (page_selector_val < 660 && page_selector_val > 640) {
            goto_page = 1;
        } 
       if(goto_page != page_loaded){
          Nextion.print("page "); 
          Nextion.print(goto_page);
          Nextion.print("\xFF\xFF\xFF"); // Nextion end command
        }
     last_page_selector_val = page_selector_val ; // Refresh the value of <last_page_selector_val> variable
    }    
}

void Nextion_serial_listen() 
  // the void that I use for reading commands from Nextion with a custom protocol that you can customize it for your needs
  // you can find few words on how you can make your own protocol to the end of the code
{
    if(Nextion.available() > 2){                // Read if more then 2 bytes come (we always send more than 2 <#> <len> <cmd> <id>
        char start_char = Nextion.read();      // Create a local variable (start_char) read and store the first byte on it  
        if(start_char == '#'){                // And when we find the character #
          uint8_t len = Nextion.read();      // Create local variable (len) / read and store the value of the second byte
                                            // <len> is the lenght (number of bytes following) 
          unsigned long tmr_1 = millis();
          boolean cmd_found = true;
            
          while(Nextion.available() < len){ // Waiting for all the bytes that we declare with <len> to arrive              
            if((millis() - tmr_1) > 100){    // Waiting... But not forever...... 
              cmd_found = false;              // tmr_1 a timer to avoid the stack in the while loop if there is not any bytes on Serial
              break;                            
            }                                     
            delay(1);                            // Delay for nothing delete it if you want
          }                                   
                                               
            if(cmd_found == true){            // So..., A command is found (bytes in Serial buffer egual more than len)
              uint8_t cmd = Nextion.read();  // Create local variable (cmd). Read and store the next byte. This is the command group
                                             
              switch (cmd){
                                    
                case 'P': /*or <case 0x50:>  IF 'P' matches, we have the command group "Page". 
                           *The next byte is the page <Id> according to our protocol.
                           */
             /* We have write in everys page "preinitialize page" the command
              *  printh 23 02 50 xx (where xx is the page id in HEX, 00 for 0, 01 for 1, etc).
              * <<<<Every event written on Nextion's pages preinitialize page event will run every time the page is Loaded>>>>
              *  it is importand to let the Arduino "Know" when and which Page change.
              */
                  page_loaded = Nextion.read();
                   
                  break;      
                  
                case 'X': 
                   // for future use, adding new command group
                  break;  
              }
            }
        }  
    }    
}
/* The communication between the Nextion Displays and the Arduino is quite simple. There is no need for libraries and complicate commands
 * as Nextion uses a simple and complete instruction_set. A library cannot cover and guess all the needs of the projects wide field.
 * The only that we must do is to organize the commands that we are going to use with a simply as possible method,
 * identifying them with Arduino code and assign them to the functions we want.
 * Nextion has a protocol to send the ids of the components via Serial but is very difficult 
 * For this we develop our own protocol to categorize, organize, read, and assign the commands.
 * 
 * We use the following Data Format: <#> <len> <cmd> <id>
 * It is more practical to send a specific command that it will activate the function we want.
 * As you can send the same command from different events and pages as times you want.
 * So we have to organize the commands that we are going to use and assign them to the functions
 * AND NOT trying to assign the IDs from a big number of objects to the function, as Nextion do with the event id protocol.
 * An example with the group command “Page” is :
 * From nextion we send in HEX the following:< printh 23 02 50 00 >
 *           means < # 2 P 0 >  
 *           <#>   declares that a command is followed
 *           <len> declares the number of bytes that will follow (len = 2, <P> is the one Byte and <0> is the other)
 *           <cmd> declares the group of commands( P = page L=Line)
 *           <id>  declares the id, to which the command is referring to. ( id = 0)
 * This means that we are in page 0 (we have write in everys page "preinitialize page" the command
 * printh 23 02 50 xx (where xx is the page id in HEX, 00 for 0, 01 for 1, etc).
 * We have assign a fuction name < first_refresh_page(uint8_t page) >
 * and with a switch case command, we sent to each page the data that must updated in first load.
 */

PerryBebbington:
Yes, a space is good. I missed that, ++Karma; for correcting my mistake :slight_smile:

I suspect, but I don't know as I can't see all your code, that you are sending this repeatedly instead of just once to change the page.

I return to my ealier suggestion; read my tutorial. You will however have to choose between my methods and using the Nextion libraries, they are not intended to be mixed.

I read your tutorial 3 parts well i confess i need to take more time but for now i don't need to change pages using the touch

Seithan:
So, the way is based on a custom protocol that you must create upon your needs and I am providing you a function that you are able to read this from serial.

If you want to see more examples on how you can create your custom protocol, you can find then at
How to send values and store them on Arduino

How to control relays

Or from my website at:
https://www.seithan.com

thanks Seithan, i tried it it gave an error saying "expected ; before Serial" :confused:

I don't understand why you divide here

page_selector_val = (adc_val / RETRY_LOOP);

So as i understand from your second sketch, that we must enter page Num on every page preinitialize right ?