MATLAB Answers

How to fix a simple callback function with a tcpip object?

29 views (last 30 days)
Damien on 22 Mar 2016
Edited: Andy on 2 Apr 2020
Hi Everyone,
I have a very simple problem: I am trying to get a callback function to execute after receiving data through a tcp/ip connection. I have been reading the asynchronuous writing and reading section of the MATLAB documentation here, and I am essentially reproducing what they suggest without any success.
Here is a simple script which illustrates my issue, when I execute it, I get a series of error and warning messages:
t = tcpip('',4000);
t.BytesAvailableFcn = 'dispcallback';
% Send some data:
fprintf(t, 'Test 123');
When I run the above script, I get these messages:
Error using dispcallback (line 13)
Not enough input arguments.
Error in instrcb (line 20)
evalin('base', val);
Warning: The BytesAvailableFcn is being disabled. To enable the callback property
either connect to the hardware with FOPEN or set the BytesAvailableFcn property.
Why is this? How can I properly invoke the callback function? I have tried with MATLAB 2014b and 2015b with the same result.

Answers (2)

Dave Behera
Dave Behera on 25 Mar 2016
Try replacing the line
t.BytesAvailableFcn = 'dispcallback';
set(t, 'BytesAvailableFcn', @dispcallback)
In the former, the event arguments were not being passed to the callback function, for some reason. Using the 'set' command should fix the issue.
  1 Comment
Andy on 2 Apr 2020
is there a way to open a useful udp server in Matlab (no echoudp...)?

Sign in to comment.

Andy on 2 Apr 2020
Edited: Andy on 2 Apr 2020
Should we specify a function:
function dispcallback(obj,event)
callbackTime = datestr(datenum(event.Data.AbsTime));
fprintf(['A ' event.Type ' event occurred for ' obj.Name ' at ' callbackTime '. Obj is the UDP object. Event is a struct w/ two fields: Type and Data. Data received over UDP: ' fscanf(obj) '\n']);
is required in the execution folder ... dispcallback doesn't seem to be available by default.
Main code:
% this opens a UDP server listening on ALL local IPs and port 8000
echoudp('on', 8000);
% this enacts a client conneting into
u = udp('', 8000);
% the below makes sure anything sent back to the client, gets echoed through the dispcallback
u.ReadAsyncMode = 'continuous';
set(u, 'BytesAvailableFcn', @dispcallback);
% this writes / sends an udp packet towards
fprintf(u, 'Hello net.')
% Since echoudp will echo back anything you throw at it ... the below is the result of us running the fprintf above command.
"A BytesAvailable event occurred for UDP- at 02-Apr-2020 16:00:29. Obj is the UDP object. Data: Hello net."

Community Treasure Hunt

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

Start Hunting!