matlab bytesAvailableCallback with empty buffer

4 views (last 30 days)
TS
TS on 25 Dec 2014
Edited: TS on 28 Dec 2014
When opening any communication instrument in matlab, you can set the object with a BytesAvailableFcn. i.e.
u.BytesAvailableFcn = @bytesAvailable_callback;
Every time the callback is called, it clears the buffer completely. For example, with a udp client:
function bytesAvailable_callback(udp_obj, event)
bytesAvailable = get(udp_obj, 'BytesAvailable');
fprintf('callback - bytesAvailable = %d\n',bytesAvailable);
while bytesAvailable
data = fread(udp_obj, bytesAvailable, 'int32');
fprintf('rec = %d\n',data(1));
bytesAvailable = get(udp_obj, 'BytesAvailable');
end
end
what happens next is the problem: the buffer has been cleared but the BytesAvailableFcn is still in the call stack and will be called many time, only to return nothing.
an example running the above callback with udp:
clc
echoudp('on', 8000)
%
u = udp('127.0.0.1', 8000);
u.OutputBufferSize = 10000;
u.InputBufferSize = 10000;
u.BytesAvailableFcn = @bytesAvailable_callback;
u.BytesAvailableFcnCount = 10;
u.BytesAvailableFcnMode = 'byte';
fopen(u);
%
for i = 1:2
fprintf('send = %d\n',i );
fwrite(u, [i ones(1,10)], 'int32');
end
pause(1)
fclose(u);
delete(u);
clear u
echoudp('off');
the results are:
send = 1
send = 2
callback - bytesAvailable = 88
rec = 1
rec = 2
callback - bytesAvailable = 0
callback - bytesAvailable = 0
callback - bytesAvailable = 0
callback - bytesAvailable = 0
callback - bytesAvailable = 0
callback - bytesAvailable = 0
callback - bytesAvailable = 0
We can easlly see the unwanted behaviour - callback called when the InputBuffer is empty. The above can be very demanding in a busy program where every callback counts. Is there a way to "flush" the above unwanted callback calls?
Using drawnow did not help - it executed the callbacks, so still accesses the function.

Answers (0)

Categories

Find more on Startup and Shutdown 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!