Serial communication with Arduino

2 次查看(过去 30 天)
Tom
Tom 2015-3-7
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.

回答(2 个)

Pasc Peli
Pasc Peli 2016-8-14
What Oparating system are you on?

William Gaillard
William Gaillard 2019-3-28
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

类别

Help CenterFile Exchange 中查找有关 MATLAB 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