Borrar filtros
Borrar filtros

Serial communication : data missing with readasync

1 visualización (últimos 30 días)
catherine magar
catherine magar el 9 de Abr. de 2018
Respondida: Walter Roberson el 5 de Oct. de 2023
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.

Respuestas (1)

Walter Roberson
Walter Roberson el 5 de Oct. de 2023
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.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by