How do I properly read from an Arduino's serial array?
4 views (last 30 days)
Show older comments
Good evening!
I'm developing a project where I take data from an Arduino (UNO) via Serial port, this data is stored in float arrays.
The problem I'm having is not how to read the data, but rather how to automate the process. Currently I send 2 "orders" to Arduino: 'a', which ask the board to collect, analize and store the data and 'b', which sends the arrays. The problem is that, since it takes sometime to do the second process, when i ask how many bytes are available sometimes it tells me that thera are any data in the Serial Buffer, thus, making impossible to read the data from the board until there is at least one byte available. Doing this manually (aka waiting time between asking for something and beginning the process) is slow but give me the data I need, but the automated process, even programming pauses to let the board prepare the data, seems to loop looking for a byte.
Thus, I ask you:
1) Is there a better way to send arrays via Serial between Arduino-Matlab?
2) If not, how much time to I wait to begin the data recollection from the buffer?
I leave the code below so you can tell me where I might be wrong
Thank, you.
clear all; close all; clc;
s=serial('COM5','BaudRate',9600); %Serial settings
fopen(s);
fwrite(s,'a'); %Ask the board to collect data
pause(.15);
fwrite(s,'b'); %Ask the board to send the data and waits till is done
pause(.15);
i=s.BytesAvailable; %Ask if there are any available bytes, if no, keeps asking till there is data available
while i==0
i=s.BytesAvailable;
end
data=fread(s,1); %Reads the data until the buffer is finally empty, concatenating every data
pause(.01);
while i~=0
for j=1:i
dato=fread(s,1);
data=cat(2,data,dato);
pause(.01);
end
pause(.5);
i=s.BytesAvailable
end
fclose(s); delete(s); %Closes the serial port
j=size(data,2); %Transform the ASCII data to numbers (No problems here)
datos=zeros(1,240); lim_inf=1; lim_sup=2; i=1;
while (lim_sup<=j)&(i<=240)
while data(lim_sup)~=13
lim_sup=lim_sup+1;
end
lim_sup=lim_sup-1;
datos(i)=str2num(char(data(lim_inf:lim_sup)));
lim_inf=lim_sup+3;
lim_sup=lim_inf+1;
i=i+1;
end
0 Comments
Answers (1)
Walter Roberson
on 22 Jan 2019
Use BytesAvailableFcn property on the serial object to configure a callback either when a line terminator is reached (default Terminator mode) or when a particular number of bytes have been processed.
If the arduino is sending newlines after the data, often the easiest is to not configure BytesAvailableFcn and simply fgets() the line and then parse it.
0 Comments
See Also
Categories
Find more on MATLAB Support Package for Arduino Hardware 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!