Random data while reading through serial Communication

Hi guys,…
Am using my arduino Mega to communicate with PIC controller through serial communication.
the data passed from PIC controller is like, <LVL 0000><RLY 0000> and some more data. The problem is while reading that data serially, in my serial monitor random characters exists with my original data. Please help me to fix the problem. Thank you in advance.

TEst.ino (245 Bytes)

void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
}
void loop(){
  while(Serial1.available()){
  char a[15];
    Serial1.readBytesUntil('>',a,15);
    // a=Serial1.readString();
    Serial.print('\n');
    Serial.print(a);
   
  }
}

Are there long cables involved? (>30cm)

No. Just a jumper wire length of wire may be less than 10cm only.

What's the clock of the PIC? This can cause some error in the serial of it.

The clock for PIC is 4MHz

Which PIC? If I look at the datasheet for a PIC16F628 then 9600 isn't valid @ 4Mhz. Ow, sorry, in high speed mode it is with an error of 0,16%.

Also, is that 4Mhz the internal oscillator? This can have a significant error resulting in some error when using serial.

PIC16F886.. Internal oscillator with 4MHZ

Image embedded for our convenience. Technique described here.

error.PNG

The problem is here:

  char a[15];
    Serial1.readBytesUntil('>',a,15);
      ...
    Serial.print(a);

readBytesUntil does not NUL-terminate the string, so the print will keep going past the end of the array and print whatever is next in RAM, until it randomly runs into a zero byte.

The second problem is that the array needs to have room for that extra terminating NUL:

  char a[16];
    size_t len = Serial1.readBytesUntil( '>', a, sizeof(a)-1 );
    a[ len ] = '\0'; // NUL-terminate
      ...
    Serial.print( a );

Note the use of sizeof: you can change the dimension of a without having to change all the places you used the magic number 15.

Cheers,
/dev

Nice catch. I assumed readUntil would terminate it...

I personally wouldn't put it in a extra buffer to begin with.

void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
}
void loop(){
  if(Serial1.available()){
    if(Serial1.peek() == '>'){
      Serial.write(Serial1.read());
      Serial.println();
    }
    else{
      Serial.write(Serial1.read());
    }
  }
}

Or if that's the only thing, connect both serial together (with diodes and resistors).