Compare Byte/Serial Data from Serial.read()

I have a need to check incoming serial values as they arrive so I can look at the message type then do an event based on the message type.

What is the best method to check a serial val and compare it? Example: Byte 7, if 0x05 then it's an "EVENT message".

Next condition would check byte 13 and see what value it is. For example, if its a 7F, then that means a "next" button was pressed and I will do something else.

My biggest challenge is how do I check for these conditions? A serial "EVENT" is 21 bytes long and begin with F0 and end with a F7.

This is what I currently have: if (Serial.available() > 0) { byte iByte = Serial.read(); Serial.println(iByte, HEX); }

Returns the following when event happens (which you can see it got two "EVENTS"): 7F 0 0 0 5 3 2 0 0 2 4 3 68 0 0 0 0 0 1 1 F7 F0 0 7D 2 0 0 7F 5 2 1 0 2 1 0 E 0 0 0 2 0 1 1F F7

Any advise would be grateful!

Cheers!

You'll need to store the values retrieved from the serial port into an array, so that you can reference them later.

byte inData[24]; // Make this big enough to hold the entire event
byte index; // Use this to keep track of where the next byte goes

When you read a value from the serial port, see if it is F0. If it is, set index to 0, and store the value in inData[index], and increment index.

If not, see if it is F7. If it is, store the data in the array, and then process the array.

If the value is neither F0 or F7, store the value in inData[index] and increment index.

When processing the array, you now have all the data that was sent, for reference.

So to check the incoming would it be something like this:

if (Serial.available() > 0) {

while (Serial.available()){

byte iByte = Serial.read();

if (iByte == 0xF0){ Serial.println("start of msg"); index = 0; } else { Serial.println("adding to msg"); index += 1; }

inData[index] = iByte;

if (iByte == 0xF7){ // call process function Serial.println("end of msg"); } }

}

Something like that???

Something like that???

Exactly like that.

The "if" clause here:

if (Serial.available() > 0) {

  while (Serial.available()){

is redundant, surely?

The "if" clause here...is redundant, surely?

Oh, OK. So, maybe not exactly like that... But, it was a good effort.

int index=-1;

while (Serial.available()) {   
    byte iByte = Serial.read();

    if (iByte == 0xF0){
        Serial.println("start of msg");
        index = 0;
    }

    if (index>=0) {
        inData[index++] = iByte;  // adding to message

        if (iByte == 0xF7) {
            // call process function
            index = -1;
            Serial.println("end of msg");
        }
    }
}

we don't really need that "else" either, but maybe something to ignore noise between/before the first message?