#define NXTSerial Serial2 // Serial port to connect with Nextion panel
Set serial port to use with the arduino board
void NxtOpenSerial()
{
//This is for serial Nextion display.
NXTSerial.begin(19200);
}
To open the serial communication with the HMI display.
void InitNxtData(String dev, String data)
{
memset(NxtMsg, 0, sizeof NxtMsg);
sprintf(NxtMsg, "%s=%s%c%c%c", dev.c_str(),data.c_str(),0xff,0xff,0xff);
}
To add data to write something to the screen (first data)
void Add_NxtData(String dev, String data)
{
sprintf(NxtMsg, "%s%s=%s%c%c%c", NxtMsg,dev.c_str(),data.c_str(),0xff,0xff,0xff);
}
Add next data as long as needed (to repeat).
void SendNxtData()
{
NXTSerial.print(NxtMsg);
}
Send all the data.
To write to the HMI dispay, use it this way;
void Nxt_Write()
{
InitNxtData("P1.val",NxtMessage);
Add_NxtData("P2.val",NxtMessage);
...
Add_NxtData("P3.val",NxtMessage);
Add_NxtData("P4.val",NxtMessage);
Add_NxtData("P5.val",NxtMessage);
Add_NxtData("P6.val",NxtMessage);
...
SendNxtData();
}
Example: Write 6 parameters to the Nextion screen.
repeat this routine on every 50ms and send only data when it changes to shorten your data transfer.
Because you send just one line of data it stays very responsive.
if (old_P1!=P1) {
sprintf(NxtMessage, "%u", P1);
Add_NxtData("P1.val",NxtMessage);
old_P1 = P1;
}
This way you only add the data when there was a change in data.
On the other hand we wanted to read data from the nextion screen.
void Nxt_Poll()
{
// READE DATA FROM PANEL
delayMicroseconds(10); // 10 usec delay
if (NXTSerial.available())
{
byte inc;
inc = (char)NXTSerial.read();
if ((inc >= 0xF0 && inc <= 0xFE) && !NxtSetStart) // <START MESSAGE>
{
NxtBufCnt = 0;
NxtSetStart=true;
}
if(NxtSetStart)
{
NxtBuf[NxtBufCnt++] = inc;
if (inc == 0x0A) // <END MESSAGE>
{
NxtSetStart=false;
...
Listen to the port if data is available, if so read char start message between (0xF0>0xFE)
If found read and store next character until character 0x0A has been read. This is the end of the message.
As you can see it is a very simple communication but it works very good.
Now lets check some data and do something with it.
CheckNxtHex(0xF0,NXTparam); // Read parameter data from 0xF0
CheckNxtHex(0xF1,NXTstart); // Read parameter data fron 0xF1 and do something
if (NXTstart==1 && !NXTstartFlag) {ee.active=!ee.active;NXTstartFlag=true;} // Toggle button (start/stop)
if (NXTstart==0) {NXTstartFlag=false;}
and close communication
NxtBufCnt = 0;
}
}
}
else
{
// WRITE DATA TO PANEL
Nxt_Write();
}
}
I hope this explains a litle how I made a good and fast working communication with the nextion display.
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.