0

Is there a simple method to sync the data stream of pyserial serial connection with arduino? The simple piece of code I run gives weird values from time to time which I can only assume is due to a bit shift or garbage data.

For example, some runs i get a data array with the correct output:

[4.697265625, 4.7021484375, 4.6923828125, 4.6826171875, 4.677734375, 4.66796875, 4.658203125, ....]

Then some runs I would get data which looks like this:

[1.6408595718088704e-28, 2.524370304146793e-28, 1.640838386579482e-28, 2.524370304146793e-28, 1.640838386579482e-28 ... ]

I assume the garbage data is due to out of sync bytes being sent (ie the python program is receiving the first byte of the next data packet and bytes 2,3,4 of the first packet).

Has anyone encountered this before and have a solution?

Here is the code I use to send the value across the serial port:

Arduino

void loop(){
  double val = 5.0*(analogRead(1))/1024.0;
  //Serial.println(val);
  sendToPc(&val);
}

void sendToPc(double* data){
  byte* byteData = (byte*)(data);
  Serial.write(byteData, 4);
}

The the simple python code to access it.

Python code

self.handle.reset_input_buffer()
self.handle.reset_output_buffer()
while(True):
   self.handle.readinto(self.rawData)

rawData is a byte array of size 4 bytes.

Thanks in advance.

Paul Kumar
  • 29
  • 1
  • 2
  • 10
  • 1
    Transmitting multi-byte data in a raw form is inherently prone to byte synchronization issues. That is what message or packet protocols are for, which at a minimum should have a means of validating the message, e.g. https://stackoverflow.com/questions/16177947/identification-of-packets-in-a-byte-stream. – sawdust Jan 02 '21 at 22:36
  • 1
    A simple idea is to convert 4-byte data to an 8-character hexadecimal string, add a carriage return code, and send it. The carriage return code is treated as a delimiter for each data, and it can be judged whether the data is complete by checking whether there are eight hexadecimal characters. – kunif Jan 03 '21 at 00:45

0 Answers0