How can i change ascii text from arduino serial port to number in matlab?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi, i am trying to receive numbers from arduino serial port. Arduino serial port prints number in ascii text format. But when i am receiving it in matlab using fscanf command i get an ascii equivalent. For example when i print 1 to arduino serial port monitor i receive its ascii equivalent 49 in matlab. At present i am receiving a 1 X 16 element array. Arduino serial port [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] = Matlab side [49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49] In matlab side also i want it to be 1 as entry elements. What should i do i am also open to convert the received array in matlab to 111 after receiving.
%%Create serial object for Arduino
s = serial('COM7'); % change the COM Port number as needed
%%Connect the serial port to Arduino
s.InputBufferSize = 1; % read only one byte every time
%s.baudrate = 9600;
try
fopen(s);
catch err
fclose(instrfind);
error('Make sure you select the correct COM Port where the Arduino is connected.');
end
%%Create a figure window to monitor the live data
Tmax = 6; % Total time for data collection (s)
figure,
grid on,
xlabel ('Time (s)'), ylabel('Data (8-bit)'),
axis([0 Tmax+1 -10 300]),
%%Read and plot the data from Arduino
Ts = 0.3125; % Sampling time (s)
i = 0;
data = 0;
t = 0;
tic % Start timer
while toc <= Tmax
i = i + 1;
%%Read buffer data
data(i) = fscanf(s,'%c');
%pause(0.1);
%disp(data(i));
%%Read time stamp
% If reading faster than sampling rate, force sampling time.
% If reading slower than sampling rate, nothing can be done. Consider
% decreasing the set sampling time Ts
t(i) = toc;
if i > 1
T = toc - t(i-1);
while T < Ts
T = toc - t(i-1);
end
end
t(i) = toc;
%%Plot live data
if i > 1
line([t(i-1) t(i)],[data(i-1) data(i)])
drawnow
end
end
fclose(s);
Copyright 2014 The MathWorks, Inc.
2 commentaires
Guillaume
le 6 Oct 2018
How do your differentiate between sending two consecutive 1s, and sending the number 11?
Voir également
Catégories
En savoir plus sur MATLAB Support Package for Arduino Hardware dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!