Arduino - Why is serial data written in the wrong order?

796 Views Asked by At

Basically, I have this code on a Bluno M3 Arduino:

#define MSG_LEN 2
unsigned char pixel;
char buff[MSG_LEN];

int i;
void setup() {
  Serial4.begin(9600); 
  pixel=0xDD;
}


void loop() {
  if(Serial4.peek() == -1){
    while(Serial4.available() < MSG_LEN);  
    Serial4.readBytes(buff, 2);


  if(buff[0] == 0xC8 && buff[1] == 0x00){ 
    //send image       
    Serial4.write(0xC7); //send Image ACK
    Serial4.flush();
    for(i=0;i<4800;i++){
      Serial4.write(pixel);
      Serial4.flush();
    }
    for(i=0;i<MSG_LEN;i++){
      buff[i]=0xFF;
    }
  }
  }else{
    while(Serial4.available()>0){
      Serial4.read();
    }
  } 
}

I'm using a PL2303 USB-Serial Adapter, Bluno M3 arduino, CoolTerm serial monitor.

And if you check this image:

image

You can see that in the data this code sends, the 0xC7 byte is mixed in with the 0xDD bytes (so called pixel bytes)

Why does that happen?

2

There are 2 best solutions below

3
On
  1. You do not assign your pixel variable and always send the same value;
  2. Flush serial only at end of the transmission. It should help. otherwise it is the bug

Do another test: instead of sending the same value increment it with every time. It will give more diagnostic data

0
On

Thanks to everyone pointing out that the issue might be the PL2303 module. From further testing I did confirm the PL2303 USB adapter is not working correctly.

The code works well when I use the same serial monitor but on the same COM port used for programming that Bluno arduino. This weird behaviour has been very frustrating but I appreciate everyone who pointed me in the right direction.