Online exchange of data between Matlab and MEX-file/thread

7 views (last 30 days)
I want to read data from a CANBus and visualize the data online. Everything works fine, except that the visualization is really slowing down the process. To clarify the situation, I do the following:
time = zeros(1000, 1);
value = zeros(1000, 1);
n = 1;
p1 = plot(time, value, 'k', 'LineWidth', 1);
while(1)
time = circshift(time, 1);
value = circshift(value, 1);
% Read data from CANBus
[time(1), value(1)] = MatlabCAN('get');
% Update plot data
set(p1, 'XData', time - time(1), 'YData', value);
% Update plot
drawnow;
n = mod(n, 1000) + 1;
end
Some questions:
  1. I've found some steps to accelerate the plotting (choosing fixed limits etc.), but is the approach of first updating the line data (XData & YData) and subsequently calling drawnow ok? I'm a bit concerned about drawnow, but without it, the plot is only updated when I stop the program.
  2. The function MatlabCAN is a MEX-function that takes care of all the communication with the CANBus. I already found information on how to start a thread in the MEX-file that keeps on running when returning to Matlab. My idea is now to start a data acquisition thread in the MEX-file and occasionally give data to Matlab for plotting. Is there a way to do this safely? I would like to achieve some kind of asynchronous behavior, that gives high priority to the acquisition and only updates the plot, when it doesn't hurt. It would also be perfectly fine to call the plot function from within the MEX-file.

Answers (1)

Abhi Sundararaman
Abhi Sundararaman on 12 Oct 2017
1. The updating of line data + drawnow is the best way to go about updating the plot. However, instead of using "while(1)", you could control the interval at which the plot gets updated using a timer object. You could then set the "TimerFcn" property of this timer object to be your "update plot" part of the code.
For more info on timers, check the following link: https://www.mathworks.com/help/matlab/ref/timer-class.html
2. I think this question could also be resolved with the timer object. Set the interval for the timer to be some medium-sized value, so that the plot only updates every X seconds. That way the plot wouldn't be updated every frame, and it wouldn't "hurt" MATLAB.

Categories

Find more on Specifying Target for Graphics Output in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!