Save data from Serial port of Arduino to a text file using MATLAB
15 views (last 30 days)
Show older comments
I read the data from a serial port to the MATLAB. I need to save the data to the text file using MATLAB. How to write the incoming data from the serial port to a text file instead of naming the first characters as data from the left sensor "left = [left, str2num(out(1:6))]" and 7: end as right sensors?
instrreset()
s = serial('/dev/cu.usbmodem66375701');
set(s,'BaudRate',9600);
Tmax=5;
tic;
left=[];
right=[];
fopen(s);
while toc<Tmax
out = fgetl(s);
fprintf('%s\n',out);
left = [left, str2num(out(1:6))];
right = [right, str2num(out(7:end))];
end
fclose(s);
fileName1=['savingthedata.txt'];
fid = fopen((fileName1),'wt');
if fid == -1
error('Cannot open file: %s', fileName1); AND HERE
end
fprintf(fid,'%6s %6s\n','Left sensor','Right sensor');
fprintf(fid,'%6.2f %6.8f\n',left,right);
fclose(fid);
0 Comments
Accepted Answer
Rohan Kale
on 14 Feb 2020
You may want to use the dlmwrite function to append the data read back from the serial port.
Following command construct can be used to write the data to a file in append mode
dlmwrite(filename,M,'-append');
% M is the 'out' variable in your code
It will be helpful to refer to the doc page for more options
There is one catch here, you may want to check up on the data rate and time it takes to save the data to the file so that no data points are missed out.
If the data is expected to be saved continously then doing a dlmwrite in a loop might be a good option. Otherwise, the data can be stored in a matrix before terminating the read process and finally the entire matrix can be saved on to a text file.
More Answers (0)
See Also
Categories
Find more on Text Files 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!