Assistance with Arduino reacting to Nextion

Hi All,

A little guidance required if you have time...

I have a Nextion with four buttons (b0-b3) and the buttons write out serially as follows:

b0 = 31 30
b1 = 31 31
b2 = 31 32
b3 = 31 33

These are hex values received via Serial1 on the Micro.

Ok, what I'm having trouble with is figuring out the logic of how to parse the incoming data so the program can "do something" with it.

i.e. if Serial1.available(){
if the second byte received = 30 then execute a
if the second byte received = 31 then execute b
if the second byte received = 32 then execute c
if the second byte received = 33 then execute d

So, how do I scan and read the second byte of an incoming two-byte packet?

Many thanks

Wait until serial.available >= 2. Then read each byte into a separate variable and act on the second. It's probably worth verifying that the first is 31 too.

Interesting, so if I understand correctly, Serial.available is looking for only the first byte?

No, it tells you how many are waiting to be read.

Ok, so does the >=2 imply a serial buffer of 2 bytes?

No, the buffer can contain up to 64 bytes before it overflows. You're expecting a button press to give you two bytes, so the >= 2 is intended to wait until you have two before reading them.

I am understanding that a bit now, thanks.

Do first and second bytes need their own individual variables? I don't understand how to programmatically differentiate between them.

Individual variables is one way to do it and probably easiest at this stage. Later on you may want a more clever parser if you add other stuff to your display.


if(Serial1.available() >=2){
int a = ( first byte);
int b = ( second byte);
if (b = 30){
if (b = 31){
... etc

Hello negativ3,
Please read my tutorial

It covers what you are trying to do.

This topic was automatically closed after 120 days. New replies are no longer allowed.