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!