Serial - COM function call basic

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Guillaume
Guillaume il 25 Gen 2017
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 Commento
benjamin Højgaard
benjamin Højgaard il 25 Gen 2017
Hi Guillaume, Thanks - I have both a A, and a B version !! I'll try to switch. Please, how do I address the event? function (S1,xxx)? Bg Benjamin

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 25 Gen 2017
"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

Categorie

Scopri di più su Use COM Objects in MATLAB in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by