Serial read works for only a few seconds

3 views (last 30 days)
Taoran
Taoran on 9 May 2017
Commented: Taoran on 9 May 2017
I am reading data packets trough serial port to MATLAB and try to plot it. The data packet has a 2-byte token in the beginning, a 3-byte some other message in the middle and an 8-byte adc data for 2 channels. In the code (got most parts from https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/ ), I wait for the token and store the rest of the data packet in a buffer.
while ishandle(plotGraph) %Loop when Plot is Active
while (not(isequal(fread(s,2),TOKEN))) % tokn is a 2x1 uint8 vector
end
payload(1:11,1) = fread(s,11); % Read USEFUL information (11 bytes) from Serial
% parse data
end
However, the plot and data saving work fine only for the first few seconds and then the data is crashed. I checked the workspace and find that the token was saved into the buffer as useful information for the crashed data. I tried to rerun the program several times and it turns out that it messed up at the same time.
I have attached my code and I appreciate if anyone has any comments to it.

Answers (1)

Walter Roberson
Walter Roberson on 9 May 2017
I notice that you typecast() to int32 . I would worry about about the byte order of the devices is the same.
>> typecast(uint8([1 2 3 4]), 'int32')
ans =
int32
67305985
>> dec2hex(ans)
ans =
'4030201'
That is, your MATLAB side is using "Little-Endian" byte order, where the first byte in memory is the least significant byte. Is it known that the device producing the data is writing in the same order?
  1 Comment
Taoran
Taoran on 9 May 2017
Hi, Walter. Thank you for your response. For now, I think the data parsing should be okay because for the first several seconds the plot is what I expected. My problem is that the "wait for token" part seems not working after first 5 seconds because I found token in my data buffer.

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!