I've spent the last several days tearing my hair out over Nextion problems. I'm using the Nextion library, which I'm convinced was written by someone who had no idea what he was doing. What I found was my application was FREQUENTLY simply never seeing button events. It was not unusual for 30-50% of the events to simply go missing.
I finally wrote a test program to just exercise the interface, and found the display itself worked perfectly, but the library was randomly throwing away messages. So, I looked at how the library was parsing and processing messages, and it was a MESS!
nexLoop would read a single character, then delay 10 mSec, then check if there were at least 6 more waiting. If not, it would simply toss that one character, and return. If there were 6 or more characters, it would read the first 6. If the 7 character this read were a valid message, it would process it. If not it would toss the whole thing! This created several (bloody obvious!) problems:
- EVERY time you call nexLoop, it WASTES 10 mSec if there is even a single character waiting.
- If an ENTIRE message was not received during those 10 mSec, it would throw away the first character, which MIGHT be the first character of a valid message. This GUARANTEES the rest of that message WILL be discarded.
Even worse, EVERY time you call sendCommand (which is called by ANY set method that sends a message to the Nextion), it FLUSHES the receive pipe! This randomly discards even more data.
I don't doubt this all works fine, IF you NEVER use events, but otherwise, you are screwed, and will NEVER get events reliably.
So, I re-wrote several key sections of code. Now, I have a separate function, parseRx, that reads and parses the receive pipe, and places events and response messages into their own, separate FIFOs. This is the ONLY place where the Serial port is ever read. nexLoop and other functions now call two new functions, getEvent() or getResp() to get the next event, or the next response from the FIFOs.
This has COMPLETELY cured the problems I was having, and GREATLY improved performance. I have not seen a single missed event, the the whole application is MUCH more responsive.
There are two remaining bugs I have NOT fixed, which are related. recvRetNumber and recvRetString, which are used when you use numeric and string "getters", are broken, as I see no obvious way to deal with them given how stupid the Nextion protocol is. Right now, I don't need those, so it's not hurting me. If I get bored, I'll see if I can make them work again.
This is with the v0.9.0 library, which is, AFAICT, the latest version. But I fail to understand how anyone could use it as-is for anything but the simplest possible applications.