Serial communication with Arduino

5 views (last 30 days)
Tom
Tom on 7 Mar 2015
Answered: William Gaillard on 28 Mar 2019
I am attempting some basic serial communication with an arduino with the following matlab code:
%%ARDUINO INTERFACING
% Connect to Arduino the specified port
delete(instrfindall);
Port = '/dev/tty.usbmodem1421';
BaudRate = 9600;
DataBits = 8;
StopBits = 1;
Parity = 'none';
% Create the serial connection and open communication with the Arduino.
ser = serial(Port);
set(ser, 'BaudRate', BaudRate);
set(ser, 'DataBits', DataBits);
set(ser, 'Parity', Parity);
set(ser, 'StopBits', 1);
set(ser, 'Terminator', 'LF');
fopen(ser);
disp('Serial port created')
% VERIFY SERIAL COMMUNICATION HAS BEEN SETUP
a = 'b';
while (~strcmpi(a,'a'))
if (ser.BytesAvailable > 0)
a = fread(ser,1,'uchar');
end
end
if (strcmpi(a,'a'))
disp('Serial read')
end
fprintf(ser,'%c','a');
mxbox = msgbox('Serial Communication Initialized'); uiwait(mxbox);
fclose(ser);
delete(ser);
clear ser;
delete(instrfindall);
The issue is there is no data being read so it gets stuck in the while loop while verifying. My arduino code successfully prints to the serial monitor so I think it's fine, it is:
void setup()
{
Serial.begin(9600);
Serial.println('a');
char a = 'b';
while (a != 'a')
{
a = Serial.read();
}
}
void loop()
{
}
I have tried using numerous examples on this forum and around the internet but I simply cannot get any communication between the two. Any pointers would be greatly appreciated.
Thanks in advance.

Answers (2)

Pasc Peli
Pasc Peli on 14 Aug 2016
What Oparating system are you on?

William Gaillard
William Gaillard on 28 Mar 2019
I'm not sure why your code does not work as written but in Matlab when I changed:
while (~strcmpi(a,'a'))
to
while (a~='a')
and
if (strcmpi(a,'a'))
to
if (a=='a')
it worked
I did not make any changes to Arduino

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!