Save and plot data using a TCPIP connection

4 views (last 30 days)
I am trying to save and plot data from an instrument using a tcp-ip connection. I am reading and saving the data in a .txt file and using a function (test_function) that is activated with BytesAvailableFcn. If I only save the data I have no problems.
I am now trying to plot the data that I receive from the instrument (it doesn't need to be at the same frequency of the receiving data, 25hz, it can be for instance 1 plot every 5 measurements). The only time I made it work was by using a feval loop inside of my test_function. However, after a couple of minuts my script crashes and my data stops being saved. I believe the reason for this is because the plotting is slower than the speed at which data is sent to the computer. I need to plot the data but my priority is making sure that my data is always being saved. Even if the plot crashes I need that the data keeps being saved.
How can I solve this problem?
Is there a more efficient way to do this?
I was thinking on using my test_function with parfeval and using the parallel.data.queue to obtain my data from the parallel function, but I cannot make it work. Also, parfeval cannot hanfle figures.
My main script:
clear all;
clc;
%% Establish TCP/IP connection
t=tcpip('192.168.0.1',2111,'NetworkRole','client');
t.InputBufferSize = 30000; % Needs to be bigger than LiDAR output
fopen(t);
%% Open .txt to save output in
outputfolder = 'C:\Users\...';
outputfile = 'tryploting.txt';
fid=fopen(fullfile(outputfolder, outputfile),'w+'); %a
h=plot(1);
t.BytesAvailableFcn=@(x,y) test_function(fid,x,h) %activate function only when there are bytes available
t.Terminator=3;
%% Close .txt
fclose(fid);
%% Close TCP/IP
fclose(t);
My test_function
function test_function(fid, t, h)
if t.BytesAvailable<1
return
end
dat=fread(t,t.BytesAvailable);
%% Write data in .txt
fwrite(fid, dat);
fprintf(fid,'\r\n');
%% Plot data
if length(dat) > 500 % if data is lower than 500 is info, not measurements
feval(@dataplotting,dat,h); %function where I cut part of the data to be plotted and plot using set(h,datax,datay)
end
end
Thank you.

Answers (0)

Categories

Find more on Programming Utilities 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!