Javascript required
Skip to content Skip to sidebar Skip to footer

How to Use Power Button Again Arduino

This postal service is an introduction to the Nextion brandish with the Arduino. Nosotros're going to show you how to configure the display for the outset fourth dimension, download the needed resources, and how to integrate it with the Arduino UNO lath. We'll also make a simple graphical user interface to control the Arduino pins.

Spotter the video demonstration

If you lot want to see dissimilar Nextion displays and notice the best toll, go to Maker Advisor to read our guide.

Introducing the Nextion Display

Nextion is a Homo Machine Interface (HMI) solution. Nextion displays are resistive touchscreens that makes it easy to build a Graphical User Interface (GUI). It is a great solution to monitor and control processes, being mainly practical to IoT applications.

There are several Nextion display modules, with sizes ranging from two.iv" to 7".

The Nextion has a built-in ARM microcontroller that controls the display, for example information technology takes care of generating the buttons, creating text, store images or alter the background. The Nextion communicates with whatever microcontroller using serial communication at a 9600 baud rate.

So, it works with whatsoever board that has serial capabilities like Arduino, Raspberry Pi, ESP8266, ESP32, and and then on.

To pattern the GUI, you lot apply the Nextion Editor, in which yous can add buttons, gauges, progress bars, text labels, and more to the user interface in an like shooting fish in a barrel way. We have the 2.8" Nextion display bones model, that is shown in the following figure.

Getting a Nextion Display

You can grab a Nextion basic model, or a Nextion enhanced model. The Nextion enhanced has new features when compared with the basic model:

  • has a built-in RTC
  • supports saving information to wink
  • supports GPIOs
  • has larger wink capacity and larger CPU clock

The best model for you, will depend on your needs. If yous're but getting started with Nextion, we recommend getting the 3.two" size which is the one used in the Nextion Editor examples (the examples also piece of work with other sizes, only you need to make some changes). Additionally, this is the most used size, which means more open-source examples and resource for this size.

You tin can check Maker Advisor website to become your Nextion display at the best price – just click the links below:

  • Nextion ii.viii" basic model
  • Nextion 3.2" basic model

Installing Nextion Editor

To get started with Nextion, first you need to install Nextion Editor. Get to https://nextion.itead.cc/, select the Resources tab, Download > Nextion Editor and install Nextion Editor. You tin either download the .null file or the .exe file.

Downloading Nextion Libraries

Before getting started, you also demand to install the Nextion libraries for Arduino IDE. Follow the adjacent steps to install the library:

  1. Click here to download the Nextion library for Arduino – ITEADLIB_Arduino_Nextion. You should have a .zilch binder in your Downloads folder.
  2. Unzip the .zip binder and you lot should go ITEADLIB-Arduino-Nextion-chief binder.
  3. Rename your folder from ITEADLIB_Arduino_Nextion-chief to ITEADLIB_Arduino_Nextion.
  4. Move the ITEADLIB_Arduino_Nextion binder to your Arduino IDE installation libraries folder.
  5. Finally, re-open up your Arduino IDE.

Configure Library for Arduino UNO

This library is configured for Arduino MEGA2560 by default. To get in work for Arduino Uno, you need to do the following:

1. Open the ITEADLIB_Arduino_Nextion folder

2. There should be a NexConfig.h file – open that file.

three. Comment line 27, and so that it stays equally follows:

//#ascertain DEBUG_SERIAL_ENABLE

4. Comment line 32:

//#define dbSerial Series

v. Change line 37, so that you have the following:

          #define nexSerial Series        

6. Salve the NexConfig.h file.

7. Here's the last upshot:

Now, you are gear up to first experimenting with the Nextion display with Arduino UNO.

Wiring Nextion Display to the Arduino

Connecting the Nextion display to the Arduino is very straightforward. You just need to make iv connections: GND, RX, TX, and +5V. These pins are labeled at the back of your display, equally shown in the figure beneath.

Nextion display pinout

Here's how y'all should wire the Nextion display:

Nextion Wiring to
GND GND
RX Arduino pivot 1 (TX)
TX Arduino pin 0 (RX)
VCC 5V

You can ability up the Nextion brandish directly from the Arduino 5V pivot, just it is not recommended. Working with insufficient power supply may damage the display. And so, you should use an external ability source. You should use a 5V/1A power adaptor with a micro USB cable. Along with your Nextion display, y'all'll also receive a USB to two pivot connector, useful to connect the power adaptor to the display.

Here's the schematic yous need to follow to wire the display to the Arduino.

Project Overview

The best fashion to get familiar with a new software and a new device is to make a projection example. Here we're going to create a user interface in the Nextion brandish to command the Arduino pins, and display data.

Here's the features of the application we're going to build:

  • The user interface has two pages: one controls 2 LEDs continued to the Arduino pins, and the other shows data gathered from the DHT11 temperature and humidity sensor;
  • The first page has 1 button to turn an LED on, another button to turn an LED off, a label showing the LED current land;
  • This start folio also has a slider to control the brightness of another LED;
  • The second page shows the electric current temperature in a text label, and the current humidity in a progress bar;
  • This page has an update push to update to the readings.

Parts Required

Here'southward the required parts for this projection:

  • ii.8" Nextion display (or 3.2" Nextion display)
  • MicroSD card
  • Arduino UNO – read All-time Arduino Starter Kits
  • 2x LEDs
  • DHT11 temperature and humidity sensor
  • 2x 220 Ohm resistors
  • 4.7k Ohm resistor
  • Breadboard
  • Jumper wires

You tin use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best toll!

Projection Schematic

Here's the schematic y'all need to follow to consummate this project.

Project Resources

Nosotros won't cover step-by-stride how to build the GUI in the Nextion display. Just we'll prove you how to build the most important parts, so that y'all tin learn how to actually build the user interface. After following the instructions, you should be able to complete the user interface yourself.

Additionally, we provide all the resources you demand to complete this project. Here'southward all the resources you need (exist aware that you may need to change some settings on the user interface to match your display size):

  • .HMI file (this file tin can be imported into the Nextion Editor to edit the GUI);
  • background image used in the user interface should also be in the project folder;
  • .TFT file (this file should exist uploaded to the Nextion display, this is the file that the display runs);
  • .ino file (this is the file you lot should upload to your Arduino lath).

Click here to download all the files.

Nextion Editor General Overview

Here'south a quick overview of the different sections of the Nextion Editor.

  1. Primary Menu
  2. Canvas – this is where you add your components to build the User Interface.
  3. Toolbox – this is where you accept a wide variety of components you tin can add to the user interface, like pictures, progress bar, buttons, sliders, and much more than.
  4. Picture/Fonts listing – this shows the fonts and pictures imported to your projects. Here you tin can too add new fonts and pictures.
  5. Pageexpanse – you can manage your pages hither, like add more pages, re-create and delete pages.
  6. Attributes area – this part shows your component'due south attributes. You tin edit the component'due south attributes hither.
  7. Compiler output window – this will bear witness any errors occurred during compiling.
  8. Event window – hither you can add together code to be run when an consequence is met.

Creating a New Projection in Nextion Editor

Open Nextion Editor and go to File > New to create a new file. Give it a proper name and relieve it. Then, a window pops up to chose your Nextion model, as bear witness in the effigy below.

Or you can import the .HMI file for this project.

If y'all select the Display tab, you can also set the display orientation.

For this case, nosotros've selected Horizontal.

After selecting your display and the orientation, only click the Ok button. A new project on the Nextion Editor should open up.

Calculation a Background Image

We'll outset by adding a groundwork image. To use an image equally a groundwork, it should take the exact same dimensions as your Nextion brandish. We're using the 2.8" brandish, and so the groundwork epitome needs to be 240×320 pixels. Cheque your display dimensions and edit your groundwork paradigm accordingly. As an example, we're using the following paradigm:

Afterward having your groundwork image with the correct dimensions, follow the next instructions:

1. In the bottom left corner of the Nextion display, there'south a window for fonts and pictures. Select the Moving picture tab.

2. Click the (+) button and select your background image. The image will exist added to the pictures listing and it will be given an id. In this example it is 0.

3. Go to the toolbox, and click on the Picture component. It will exist automatically added to your display area.

four. Having that component selected, you should see its attribute in the attribute area.  You tin can double click on the attributes to edit them. Double-click on the pic attribute to select the film you desire. Y'all must write "0" which is the index of the flick y'all want, or select the prototype on the new window that pops up. After writing "0", you lot actually demand to hit ENTER to save the changes.

Calculation Fonts

To write text on the display, you need to generate a font in the Nextion Editor. Go to Tools > Font Generator. A new window should open.

Here you can select the font height, type, spacing and if you desire it to be bold or non. Give it a proper noun and click the Generate font button. Afterwards that, relieve the .zi file and add the generator font by clicking aye.

The font will be added to the Fonts library at the left bottom corner and information technology will exist given an index. Equally this is your first font, it will have the index 0.

Note : At the time of writing this instructions there is an result with font types. Whatsoever font blazon y'all chose, information technology will ever wait the same. Notwithstanding, you can edit the font size and if it is bold or non.

Adding text labels, sliders and buttons

At this moment, you tin start calculation components to the display area. For our projection, drag three buttons, two labels and one slider, as shown in the figure beneath. Edit their looks as you like.

All components have an attribute chosen objname. This is the name of the component. Give good names to your components because yous'll demand them later for the Arduino code. Also notation that each component has one id number that is unique to that component in that page. The effigy below shows the objname and id for the slider.

You can edit the components the fashion yous want, just make certain to edit the slider maxval to 255, and so that it works with the Arduino lawmaking we'll be using.

Touchable components

Yous should trigger an event for the touchable components (the buttons and the slider) so that the Arduino knows that a component was touched. You can trigger events when yous press or when you release a component.

Here we're going to trigger an upshot when the touch is released. That result will be simply sending the ID of the component that was touched.

To practise that, select 1 of the buttons, and in the event window, select the Touch Release Event tab, and put a tick on the Ship Component ID option. Repeat this process for the other button, and the slider.

Creating and Navigating to a New Folio

Adding more pages to your GUI is actually elementary. On the top right corner, in the Folio expanse, select the Add push button to add a new folio. A new page will exist created. In this case, page1.

To navigate to one page to another, we've added a push in each page, at the bottom right corner – in this case it is called bNext.

To make this button redirect to page1, you lot need to add the following to the Event window, in the user code department (as highlighted in red below).

If you want to redirect to another page, you just accept to change the User Code with the number of the page.

Our second page volition brandish data from the DHT11 temperature and humidity sensor. We have several labels to hold the temperature in Celsius, the temperature in Fahrenheit, and the humidity. We also added a progress bar to display the humidity and an UPDATE button to refresh the readings. The bBack button redirects to page0.

Observe that we have labels to hold the units like "ºC", "ºF" and "%", and empty labels that will be filled with the readings when we have our Arduino code running.

Testing the Interface in the Simulator

Y'all tin can test your interface in the simulator. For that, you need to click on the debug button at the principal bill of fare.

A new window should open.

In that window y'all tin can click on the buttons and run into what happens. You should exist able to swap between pages by clicking the corresponding buttons. You should also see the data returned when you lot click each button equally highlighted in blood-red in the effigy to a higher place.

Compiling and Uploading lawmaking to the Nextion Display

To upload your projection to the Next display, follow the next steps:

one. Click the Compile push in the chief menu;

2. Insert the microSD card on your computer;

3. Become to File > Open Build Folder;

4. Copy the .TFT file corresponding to the file you're currently working;

5. Paste that file in the microSD card (note: the microSD card should have been previously formatted every bit FAT32);

6. Insert the microSD card on the Nextion brandish and plug power.

7. Yous should see a message on the display proverb the code is being uploaded.

eight. When information technology is set up, it should brandish the following message:

9. Remove the ability from the Nextion display, and unplug the microSD card.

10. Utilise power once more, and you should run into the interface you've built in the Nextion Editor on your Nextion display.

Writing the Arduino Code

Once the GUI is set, you need to write the Arduino code so that the Nextion tin can collaborate with the Arduino and vice-versa. Writing code to interact with the Nextion display is non straightforward for beginners, but it too isn't as complicated equally it may seem.

A practiced fashion to learn how to write code for the Arduino to interact with the Nextion display is to get to the examples folder in the Nextion library folder and explore. Yous should exist able to copy and paste code to make the Arduino do what you want.

The showtime thing you should practice is to take notation of your components in the GUI that will interact with the Arduino and take notation of their ID, names and page. Hither'southward a tabular array of all the components the code will interact to (your components may have a different ID depending on the order you've added them to the GUI).

Objname Type Page ID ID
tState text 0 4
bOn push 0 two
bOff push 0 three
h0 slider 0 5
tSlider text 0 half-dozen
tTempC text 1 v
tTempF text 1 4
jHumidity Progress bar 1 8
tHumidity text 1 ix
bUpdate push button one 10

Below yous can find the lawmaking you should upload to your Arduino board. Make sure you lot have the right board and COM port select.

You also need to take the Adafruit_DHT library installed.

Note: make sure you lot remove the TX and RX connections when uploading code.

          /*  * Rui Santos   * Complete Project Details https://randomnerdtutorials.com  */  #include "Nextion.h"  #include "DHT.h" #define DHTPIN iv     // what digital pivot we're continued to  // Uncomment whatever type you're using! #define DHTTYPE DHT11   // DHT 11 //#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321 //#define DHTTYPE DHT21   // DHT 21 (AM2301)  // Initialize DHT sensor. DHT dht(DHTPIN, DHTTYPE);  // LED pins const int led1 = 8; const int led2 = 9;  // Declare your Nextion objects - Instance (page id = 0, component id = 1, component name = "b0")  NexText tState = NexText(0, 4, "tState");  NexButton bOn = NexButton(0, 2, "bOn"); NexButton bOff = NexButton(0, three, "bOff"); NexSlider h0 = NexSlider(0, 5, "h0"); NexText tSlider = NexText(0, vi, "tSlider"); NexText tTempC = NexText(one, five, "tTempC"); NexText tTempF = NexText(1, four, "tTempF"); NexProgressBar jHumidity = NexProgressBar(1, 8, "jHumidity"); NexText tHumidity = NexText(1, 9, "tHumidity"); NexButton bUpdate = NexButton(i,10, "bUpdate");  // Register a push object to the touch event list.   NexTouch *nex_listen_list[] = {   &bOn,   &bOff,   &h0,   &bUpdate,   Nothing };   /*  * Push button bOn component pop callback function.   * When the ON button is released, the LED turns on and the state text changes.   */ void bOnPopCallback(void *ptr) {   tState.setText("State: on");   digitalWrite(led1, High); }  /*  * Button bOff component pop callback function.   * When the OFF button is released, the LED turns off and the state text changes.   */ void bOffPopCallback(void *ptr) {   tState.setText("State: off");   digitalWrite(led1, Low); }  /*  * Slider h0 component pop callback office.   * When the slider is released, the LED effulgence changes and the slider text changes.   */ void h0PopCallback(void *ptr) {   uint32_t number = 0;   char temp[10] = {0};   // modify text with the current slider value   h0.getValue(&number);   utoa(number, temp, 10);   tSlider.setText(temp);   // change LED brightness   analogWrite(led2, number);  }  /*  * Push bUpdate component popular callback role.   * When the UPDATE button is released, the temperature and humidity readings are updated.   */ void bUpdatePopCallback(void *ptr) {   // Reading temperature or humidity takes about 250 milliseconds!   // Sensor readings may also be up to two seconds 'old' (its a very wearisome sensor)   bladder h = dht.readHumidity();   // Read temperature as Celsius (the default)   float t = dht.readTemperature();   // Read temperature as Fahrenheit (isFahrenheit = true)   bladder f = dht.readTemperature(true);    // Check if whatever reads failed and go out early (to try once more).   if (isnan(h) || isnan(t) || isnan(f)) {     return;   }   // Update temperature in Celsius   static char temperatureCTemp[6];   dtostrf(t, 6, 2, temperatureCTemp);   tTempC.setText(temperatureCTemp);    // Update humidity percentage text and progress bar   char hTemp[10] = {0};    utoa(int(h), hTemp, 10);   tHumidity.setText(hTemp);   jHumidity.setValue(int(h));    // Update temperature in Fahrenheit   static char temperatureFTemp[half-dozen];   dtostrf(f, 6, 2, temperatureFTemp);   tTempF.setText(temperatureFTemp); }  void setup(void) {       dht.brainstorm();   Serial.begin(9600);        // Y'all might need to modify NexConfig.h file in your ITEADLIB_Arduino_Nextion folder   // Set the baudrate which is for debug and communicate with Nextion screen   nexInit();    // Register the pop result callback function of the components   bOn.attachPop(bOnPopCallback, &bOn);   bOff.attachPop(bOffPopCallback, &bOff);   h0.attachPop(h0PopCallback);   bUpdate.attachPop(bUpdatePopCallback, &bUpdate);        // Fix LEDs equally outputs   pinMode(led1, OUTPUT);   pinMode(led2, OUTPUT); }  void loop(void) {      /*    * When a pop or push upshot occured every fourth dimension,    * the respective component[correct folio id and component id] in touch event list will be asked.    */   nexLoop(nex_listen_list); }                  

View raw lawmaking

Continue reading the post to learn how the lawmaking works.

Including needed libraries

Commencement, you lot include the Nextion and the DHT libraries.

#include "Nextion.h" #include "DHT.h"

The DHT sensor will be connected to the Arduino digital pivot 4.

#ascertain DHTPIN 4

Then, you lot should select the DHT type you're using:

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

And initialize the DHT sensor

DHT dht(DHTPIN, DHTTYPE);

After that, you define led1 and led2. These variables refer to the digital pins 8 and 9 respectively. (led 1 will exist controlled with the ON and OFF buttons of the user interface, and led2 brightness will be controlled using the slider).

const int led1 = eight; const int led2 = 9;

Declaring Nextion Objects

You lot need to declare all your Nextion objects as follows:

NexText tState =          NexText(0, 4, "tState");  NexButton bOn =          NexButton(0, 2, "bOn"); NexButton bOff =          NexButton(0, 3, "bOff"); NexSlider h0 =          NexSlider(0, five, "h0"); NexText tSlider =          NexText(0, half-dozen, "tSlider"); NexText tTempC =          NexText(one, 5, "tTempC"); NexText tTempF =          NexText(one, iv, "tTempF"); NexProgressBar jHumidity =          NexProgressBar(1, 8, "jHumidity"); NexButton bUpdate =          NexButton(i,ten, "bUpdate"); NexText tHumidity =          NexText(1, 9, "tHumidity");

Hither yous use the page ID, the component ID and their name – just check the table above with all the components. To define a text you use NexText, to define a button you apply NexButton, for a slider you use NexSlider and for the progress bar yous use NexProgressBar.

Next, yous should add in the post-obit snippet all the touchable components that should trigger events on the Arduino.

NexTouch *nex_listen_list[] = {     &bOn,     &bOff,     &h0,     &bUpdate,     Zero };

Creating Callback Functions

Subsequently that, you should create callback functions that volition exist triggered when yous touch the corresponding components.

The post-obit function will exist triggered when you lot release the affect from the bOn push:

void          bOnPopCallback(void *ptr) {     tState.setText("State: on");     digitalWrite(led1, High); }

This function volition set the led1 to High, as well equally update the tState label with the text "Land: on". Updating text labels is as unproblematic as using setText().

The bOff button works in a like way:

void          bOffPopCallback(void *ptr) {     tState.setText("State: off");     digitalWrite(led1, LOW); }

For the slider (h0), you have the following function that writes the current slider position on the tSlider characterization and sets led2 brightness accordingly:

void          h0PopCallback(void *ptr) {     uint32_t number = 0;     char temp[10] = {0};     h0.getValue(&number);     utoa(number, temp, 10);     tSlider.setText(temp);     analogWrite(led2, number);  }

Finally, you demand a part for the bUpdate (the update push). When you click this push button the DHT temperature and humidity sensor reads temperature and humidity and displays them on the corresponding labels, as well equally the humidity on the progress bar. That is the bUpdatePopCallback() role.

Inside that office, the post-obit snipet reads temperature and humidity:

float h = dht.readHumidity();  // Read temperature as Celsius (the default)  float t = dht.readTemperature();  // Read temperature every bit Fahrenheit (isFahrenheit = truthful)  float f = dht.readTemperature(truthful);  // Cheque if any reads failed and exit early on (to try again).  if (isnan(h) || isnan(t) || isnan(f)) {  //Series.println("Failed to read from DHT sensor!");  return;  }

The next piece writes the temperature in celcius on the tTempC characterization

static char temperatureCTemp[6]; dtostrf(t, 6, 2, temperatureCTemp); tTempC.setText(temperatureCTemp);

In a similar manner, to update the temperature in Fahrenheit:

static char temperatureFTemp[vi]; dtostrf(f, 6, 2, temperatureFTemp); tTempF.setText(temperatureFTemp);

To update the humidity characterization likewise every bit the progress bar:

char hTemp[10] = {0}; utoa(int(h), hTemp, 10); tHumidity.setText(hTemp); jHumidity.setValue(int(h));

To set the value of the progress bar you simply employ setValue().

setup()

In the setup(), you demand to attach the functions created to the corresponding events. For example, when you click on the bOn button, the bOnPopCallback function will be triggered.

    bOn.attachPop(bOnPopCallback, &bOn);     bOff.attachPop(bOffPopCallback, &bOff);     h0.attachPop(h0PopCallback);     bUpdate.attachPop(bUpdatePopCallback, &bUpdate);

loop()

The loop is every bit simple every bit the following:

void loop(void) {      nexLoop(nex_listen_list); }

When an event occurs, the corresponding function volition be triggered.

Sit-in

With the User Interface congenital and the code on the Arduino, you lot should be able to control the Arduino pins from the Nextion display.

Tap the On and Off buttons to turn on and off led1 and movement the slider to command led2 brightness.

On the second screen, tap the update push to update with the latest sensor readings.

Wrapping up

In this post we've introduced yous to the Nextion display. We've besides created a simple application user interface in the Nextion display to control the Arduino pins. The application built is just an instance for yous to sympathise how to interface different components with the Arduino – we promise yous've establish the instructions as well as the example provided useful.

In our opinion, Nextion is a swell brandish that makes the process of creating user interfaces simple and piece of cake. Although the Nextion Editor has some problems and limitations it is a great choice for building interfaces for your electronics projects. Nosotros accept a projection on how to create a Node-RED physical interface with the Nextion display and an ESP8266 to control outputs. Feel gratis to take a look.

What projects would you like to see using the Nextion brandish? Write a annotate down beneath.

Cheers for reading.

noackfece1948.blogspot.com

Source: https://randomnerdtutorials.com/nextion-display-with-arduino-getting-started/