I'm trying to connect my arduino kit to matlab but it seems that i have error using fread.

20 views (last 30 days)
function [s, flag] = setupSerial(comPort)
flag = 1;
s = serial(comPort);
set(s, 'DataBits', 8 );
set(s, 'StopBits', 1) ;
set(s, 'BaudRate', 9600 );
set(s, 'Parity', 'none');
fopen(s);
a='b';
while (a~='a')
a=fread(a,1,'uchar');
end
if (a=='a')
disp('serial read');
end
fprintf(s, '%c','a');
mbox = msgbox('Serial Communication Setup'); uiwait(mbox);
fscanf(s, '%u');
end
--------------------------------------------------------------------------
above is the code i write for the editor and i keep getting the below error when trying to run the code
--------------------------------------------------------------------------
>> comPort = serial('com3');
Warning: serial will be removed in a future release. Use serialport instead.
If you are using serial with icdevice, continue using serial in this MATLAB release.
>> [s, flag] = setupSerial(comPort);
Warning: serial will be removed in a future release. Use serialport instead.
If you are using serial with icdevice, continue using serial in this MATLAB release.
Error using fread
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in setupSerial (line 16)
a=fread(a,1,'uchar');

Answers (1)

Cris LaPierre
Cris LaPierre on 3 Apr 2023
Have you installed the MATLAB Support Package for Arduino Hardware? You can find instructions here.
I suggest going though the Getting Started with MATLAB Support Package for Arduino Hardware to see how it is recommended you connect with and communicate with an Arduino.
  3 Comments
Cris LaPierre
Cris LaPierre on 5 Apr 2023
I figured the best I could do is share what works for me. Here's s snippet of code I use to read a streaming signal from an Arduino using serialport and readlines.
sp = serialport('COM1',115200);
flush(sp);
data = str2double(readline(sp));
delete(sp)
clear sp
It is recommended to not use serial with fread. Use serialport with read instead (or readlines).

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!