Serial communication with Arduino

4 visualizaciones (últimos 30 días)
Tom
Tom el 7 de Mzo. de 2015
Respondida: William Gaillard el 28 de Mzo. de 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.

Respuestas (2)

Pasc Peli
Pasc Peli el 14 de Ag. de 2016
What Oparating system are you on?

William Gaillard
William Gaillard el 28 de Mzo. de 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

Categorías

Más información sobre MATLAB Support Package for Arduino Hardware en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by