MATLAB: Serial – COM function call basic

bytesavailablefcnMATLABserial function call

I'm trying to invoke a function call via the SERIAL object BytesAvailableFcn.
I cannot find one example that works!
I may have a concept understanding issue – so my question is more addressed on the basic understanding of the object call.
I always end up with: "Function definitions are not permitted in this context".
In this example I would like to invoke a function call when 4 bytes has been received in the input buffer.
Can I interpret this function call as a kind of interrupt being called randomly in my code (here while 1 loop)?
the function address is set in the serial setup: @SerialData. When I define the function I cannot understand how it has to be declared. I have to pass an Object -is S1 the object in this example?
Why do I have to pass a event -it is the event that triggers the function? My declaration is not accepted. which event has to be written in the function declaration and how?
My first goal is to write the received data to "out" and display the data. in the Command window.
%%Variable definition
Count = 0;
% create serial object
S1 = serial('COM7');
set(S1, 'BaudRate', 500000);
set(S1, 'Parity', 'none');
set(S1, 'DataBits', 8);
set(S1, 'StopBit', 1);
set(S1, 'FlowControl', 'hardware');
%set(S1, 'Terminator', 'CR/LF');
%set(S1, 'Timeout',3);
set(S1, 'BytesAvailableFcnMode','byte');
set(S1, 'BytesAvailableFcnCount',4);
set(S1, 'BytesAvailableFcn',@SerialData);
%%function definition
function SerialData(S1,BytesAvailable)
out = scanf(S1);
disp(out);
end
fopen(S1); % open serial
while 1

Best Answer

Unless you're using R2016b, functions definitions are not allowed in scripts. In earlier versions, functions have to be in their own separate file.