Serial - COM function call basic
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Guillaume
2017-1-25
Unless you're using R2016b, functions definitions are not allowed in scripts. In earlier versions, functions have to be in their own separate file.
更多回答(1 个)
Walter Roberson
2017-1-25
"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?"
All event callbacks are automatically passed two parameters, the first being the object that triggered the callback, and the second being a structure with additional information about the event. The event structure is empty for most types of events, including for BytesAvailableFunction events, but it is part of the way that callbacks are handled that it will be passed anyhow.
function SerialData(S1, event)
out = fread(S1, S1.BytesAvailable);
disp(out);
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Use COM Objects in MATLAB 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!