Nextion Display and arduino

Hi everyone. I am a newbie to arduino but im learning as i go along trail and error.

I having a problem trying to figure out how to write a code in Loop() using a push button i create on my nextion display. I need the loop to switch a relay relay on and delay and off again.

Ive been searching for a example so i can figure it out but haven’t found any.

Im using arduino mega with a nextion 4.3"

Please help

Hey Fadli

I’m not 100% sure on where your problem is. Have you got the relay working without the loop?
These two commands might help you out with how to delay and turn on the Relay.

  digitalWrite(Relay, HIGH);   // Turn the relay power on)
  delay(125);               // wait for a second

Hi Clinton Thanks for the reply. Yes i have a sketch with the relay turn on and off with the button on the nextion display.
Have now started a new project now.
The problem im having is how do i go about writing in the loop using the nextion display button(s)
to pulse a relay.
So when a button is pressed on the display it pulses the relay (delay for 200) and button released it turns off.

I found examples of the using a tactile switch but nothing using the nextion display

Hey Fadli,

For starters, what are you reading over the serial connection from the Nextion when you press the buttons?

Hi Stephen

Im a newbie in to all of this. Ive been learning for examples as i need it.
Do you mean the Hex code?
This is what ive got so far.

#include “Nextion.h”


  • Declare a button object [page id:0,component id:1, component name: “b0”].
    NexButton b0 = NexButton(1, 2, “b0”);

char buffer[100] = {0};

int relay1 = 22;


  • Register a button object to the touch event list.
    NexTouch *nex_listen_list[] =


  • Button component pop callback function.

  • In this example,the button’s text value will plus one every time when it is released.
    void b0PopCallback(void *ptr)
    uint16_t len;
    uint16_t number;
    NexButton *btn = (NexButton *)ptr;
    memset(buffer, 0, sizeof(buffer));

    /* Get the text value of button component [the value is string type]. */
    btn->getText(buffer, sizeof(buffer));

    number = atoi(buffer);
    number += 1;

    memset(buffer, 0, sizeof(buffer));
    itoa(number, buffer, 10);

    /* Set the text value of button component [the value is string type]. */

void b0PushCallback(void *ptr) // Press Events


void setup(void)
/* Set the baudrate which is for debug and communicate with Nextion screen. */

/* Register the pop event callback function of the current button component. */
b0.attachPush(b0PushCallback, &b0);
b0.attachPop(b0PopCallback, &b0);

dbSerialPrintln("setup done"); 


void loop(void)
* When a pop or push event occured every time,
* the corresponding component[right page id and component id] in touch event list will be asked.



Hi Fadil,

Does the code that you have here work? The text on the button increases by one every time you press it on the screen?