フィルターのクリア

Serial communication : data missing with readasync

1 回表示 (過去 30 日間)
catherine magar
catherine magar 2018 年 4 月 9 日
回答済み: Walter Roberson 2023 年 10 月 5 日
I'm writing data to serial port with fwrite function and would like to read the answer with readasync function. My code is :
wanted_position1 = 240;
fwrite(s, [170;0;wanted_position1],'async');
pause(1)
readasync(s)
while strcmpi(get(s, 'TransferStatus'), 'read') % wait till the read asynchronous operation is finished
pause(0.1)
end
while s.BytesAvailable>0 % read the data coming from serial port
read_position = fscanf(s)
end
The problem is that the value of s.ByteAvailable is lower than expected and I don't receive all the data sent by the device connected to the serial port. For example instead of having : read_position = '100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,' I get : read_position ='190,200,210,'
I've also noticed that the value of s.ByteAvailable is changing from an execution to another : sometimes it is equal to zero and I get no data.
  1 件のコメント
Michael McKinney
Michael McKinney 2023 年 10 月 5 日
I'm having this same issue. Did you ever find a solution

サインインしてコメントする。

回答 (1 件)

Walter Roberson
Walter Roberson 2023 年 10 月 5 日
I do not recommend readasync() because the transfer is not started until the readasync() call -- so anything that was sent after the prior read might or might not happen to still remain within the internal buffers.
The hardware buffer capacity of cheap serial ports used to be as little as 1 byte, with up to 16 bytes for more expensive (but not unreasonable) boards -- and considerably larger buffers for fairly expensive boards.
When you use readasync() whatever was in transit will have been discarded, except for whatever is left in the hardware buffers.
You are better off using bytes received function callback: when you use that, then the model is that MATLAB itself will take care of collecting the data in the buffer in the background, and will invoke the callback when the buffer is full or the terminator character is reached or there is a timeout.

製品

Community Treasure Hunt

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

Start Hunting!

Translated by