-1

I'm receiving bytes from the USART and put them in the memory register. The bytes are the commands I have to read and reply with messages accordingly. As I know how to compare a single byte, would suggest me an algorithm to compare multiple bytes.

For example, the received bytes looks like this in hex 16 04 32 01 00 32. They are with different length, so the comparison would be more difficult.

georgiar
  • 379
  • 3
  • 7
  • 1
    Compare in a loop? Also, [what have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Some programmer dude Sep 26 '12 at 08:06
  • I don't know what approach to take. I have a couple of commands that I have to compare with. Do I have to make loop for every command or is there a simpler way with table lookups. I need some kind of sample code for this. I tried to sum the bytes from the commands but this is not working because I found 2 different commands with same sums – georgiar Sep 26 '12 at 08:19
  • 1
    I'm guessing that not _all_ of the received message is significant, but one or two bytes is a message code and the rest is data. This will simplify things as then you only have to compare that single (or those two) bytes, and then jump to a subroutine to handle the actual message data. – Some programmer dude Sep 26 '12 at 08:27
  • So Joachim, you suggest comparing the data part of the message with a loop. So I have to create as many loops as the messages I expect and jump accordingly? – georgiar Sep 26 '12 at 08:32
  • Draw a workflow diagram for your logic. Things should become apparent when seeing it. – Alexey Frunze Sep 26 '12 at 09:05

1 Answers1

1

You only need to compare enough bytes to distinctly recognize what kind of message it is (the actual data payload you don't need to care about in this first step). For most serial protocols it's just a single byte at a specified position.

By looking at your example message, I'm guessing the first byte is the message type and the second the length of the data payload. If that's the case then you don't need to check more than that first byte and jump accordingly. This is mostly done through a jump-table indexed with the message type (that first byte).

The function handling the actual message data payload can do whatever it want to do with the data, but you don't need to check the complete message just to find out what to do with the message.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621