Save data from Serial port of Arduino to a text file using MATLAB

43 visualizaciones (últimos 30 días)
RN
RN el 12 de Feb. de 2020
Comentada: RN el 15 de Feb. de 2020
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);

Respuesta aceptada

Rohan Kale
Rohan Kale el 14 de Feb. de 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
However, you may want to explore the writematrix function for the same.
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.

Más respuestas (0)

Categorías

Más información sobre MATLAB Support Package for Arduino Hardware en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by