Running .m and simulink (.slx) file together

I ran in to trouble while working with NI DAQ (USB 6251). I wanted to integrate everything is simulink and they dont provide block for counter (Can't use DIs). So I used function block with coder.extrensic() function and it works but my counter resets everytime. Following is my code,
function data = functionRead1()
data = zeros(1,1); %Preinitialization
coder.extrinsic('daq','addinput','read','table2array'); %define functions as external
d = daq("ni"); % Add DAQ
ch1 = addinput(d, 'Dev1', 'ctr0', 'Position'); % Add Inputs
data = table2array(read(d)); %reads 1 scan cycle and returns accumulated value
end
So the problem is everytime counter resets and I get wront data read in code. Cant use while loop or if...else logic as it goes in loop or throws error.
I have .m file as well for code which works fine. It there any way I can run .m and .slx together on same machine? Or any other solution is fine.
Thanx in advance.

 Accepted Answer

Use persistent. Check if the persistent variable is empty and if it is then configure it. Then either way, read from the daq.
Note: consider using OutputFormat 'Matrix' instead of the default table.

3 Comments

Well I tried with ur solution. below is my code in matlab function block. Now its throwing error as d is not defined in all instances. May be because I am configuring DAQ in a IF statement and next execution I am neglecting that code.
Error "Variable 'd' is not fully defined on some execution paths. Function 'FunctionRead1' (#29.313.314), line 12, column 13: "d"".
Any solutions?
Thanx in advance.
function data = FunctionRead1
persistent n
coder.extrinsic('daq','addinput','read','table2array'); %define functions as external
if isempty(n)
n = 0;
data = zeros(1,1);
d = daq("ni"); % Add DAQ
%% Add Inputs
ch1 = addinput(d, 'Dev1', 'ctr0', 'Position'); %
end
%% Set encoder type
data = read(d, 1, 'OutputFormat', 'Matrix');
n = 1;
end
Thanx a lot. Works really well. :)

Sign in to comment.

More Answers (0)

Categories

Find more on Data Acquisition Toolbox in Help Center and File Exchange

Products

Release

R2020a

Community Treasure Hunt

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

Start Hunting!