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

53 ビュー (過去 30 日間)
RN
RN 2020 年 2 月 12 日
コメント済み: RN 2020 年 2 月 15 日
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);

採用された回答

Rohan Kale
Rohan Kale 2020 年 2 月 14 日
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.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB Support Package for Arduino Hardware についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by