Plotting data using Simulink event listeners
Show older comments
I'm trying to use event listeners to extract data from my simulink model so I can plot it in Matlab. I'm following this guide https://matlabideas.wordpress.com/2011/11/02/guideing-simulink-with-matlab/ but am getting this error.
Error evaluating 'StartFcn' callback of block_diagram 'Practice'. Caused by: Can add listener only when block diagram is executing.
StartFcn is a pushbutton that starts the simulation. It is also the place where listeners are supposed to be attached. Here is the code for pushbutton % --- Executes on button press in start. function start_Callback(hObject, eventdata, handles) % hObject handle to start (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
% open the simulink model
open_system(handles.modelName);
% Simulink may optimise your model by integrating all your blocks. To
% prevent this, you need to disable the Block Reduction in the Optimisation
% settings.
set_param(handles.modelName,'BlockReduction','off');
% When the model starts, call the localAddEventListener function
set_param(handles.modelName,'StartFcn','localAddEventListener');
%eventhandle = add_exec_event_listener('Practice/Mux', ...
%'PostOutputs', @localEventListener);
% Start the model
set_param(handles.modelName, 'SimulationCommand', 'start');
global ln1 ln2 ln3 ln4 ln5 ln6 ln7;
h = findobj('Type','axes','Tag','axes1');
cla(h) % Clear axes in case stop, then start is pressed
ln1 = line(0,0,'Color',[1 0 0],'Marker','o','Parent',h);
ln2 = line(0,0,'Color',[0 1 0],'Marker','*','Parent',h);
Here is the code for the listener function eventhandle = localAddEventListener
eventhandle = add_exec_event_listener('Practice/Mux', ...
'PostOutputs', @localEventListener);
% The function to be called when event is registered.
function localEventListener(block, eventdata)
global ln1 ln2 ln3 ln4 ln5 ln6 ln7;
% Use this or cell arrays to shorten the code
%eval([char(variable_names{k}) ' = ' num2str(values(k)) ';'],1 )
xData = get(ln1,'xData');
xData = [xData block.CurrentTime];
yData1 = get(ln1 ,'yData');
yData2 = get(ln2 ,'yData');
yData3 = get(ln3 ,'yData');
yData4 = get(ln4 ,'yData');
yData5 = get(ln5 ,'yData');
yData6 = get(ln6 ,'yData');
yData7 = get(ln7 ,'yData');
% Gets the time and output value
% Add the latest point to the data
yData1 = [yData1 block.OutputPort(1).Data(1)];
yData2 = [yData2 block.OutputPort(1).Data(2)];
yData3 = [yData3 block.OutputPort(1).Data(3)];
yData4 = [yData4 block.OutputPort(1).Data(4)];
yData5 = [yData5 block.OutputPort(1).Data(5)];
yData6 = [yData6 block.OutputPort(1).Data(6)];
yData7 = [yData7 block.OutputPort(1).Data(7)];
Answers (0)
Categories
Find more on Event Functions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!