Go Down

Topic: Serial read: misplaced values (Read 479 times) previous topic - next topic



I'm new to Arduino and I hace an issue with serial read.

I have a PC program (boblight) that sends to Arduino via a serial port {R,G,B} hex values. Portmon shows the following data being sent to Arduino (every second it sends three bytes):

Second 1: 00 EC 2A
Second 2: EB 12 0F
Second 3: FD 01 0D
Second 4: 14 8A EC       

I wrote a program in Arduino to get the above {R,G,B} values and process them.

Essentially the Arduino program is

Code: [Select]
unsigned char RGB[3];

void setup() {

 // Init serial communications


void loop()
   if (Serial.available() >= 3) {
     for (int i = 0; i < 3; ++i)
       { RGB[i] = Serial.read(); }
    // Do something with RGB[0], RGB[1], RGB[2]

So I hope that RGB[0], RGB[1] and RGB[2] store the integer values sent from the PC in the same sent order.

But what I really seem to get is that the order of the received bytes is misplaced. For example, when the PC sends {EB, 12, 0F}, the above Arduino program gets {0F, EB, 12}.

Obviously I can teak the indexes and make it work as expected, but I can't understand why RGB[0], RGB[1] and RGB[2] have wrong values.

Any ideas why this is happening?



The sending program is sending a stream of bytes. The Arduino is reading a stream of bytes. If a byte gets lost, somewhere, the next three bytes read will not be in the correct order. That seems to be what you are seeing.

The sending program should send some marker followed by three values. The Arduino should then look for that marker, ignoring bytes until it sees the marker, and then reading, and storing the next three bytes.

For example, send #, 00, EC, 2A, #, BB, 12, 0F, #, FD, 01, 02, ...

If the Arduino sees #, 00, EC, 2A, #, BB, 12, 0F, #, FD, 01, 02, ..., great. Store and process the 00, EC, 2A, the BB, 12, 0F, and the FD, 01, 02.

If, instead it sees #, 00, EC, 2A, #, BB, 0F, #, FD, 01, 02, ..., you would store and process the 00, EC, 2A. But, then BB, 0F, # aren't valid values, so they get discarded. Then, FD, 01, 02 don't contain the # marker, so they get discarded, too.

Any time you get #, nn, nn, nn, you can use the data. Anytime you get something other than #, nn, nn, nn, you discard it.


Thanks, got it. Gonna try it.



OK, that was the issue. I added some control byte and controlled its presence from Arduino and it did the trick.

Really grateful!


Go Up