Serial communication with Arduino
5 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(2 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File 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!