简体   繁体   中英

Matlab & Arduino serial communication

I am trying to get some basic serial communication up and running. My arduino code is shown below.

   void setup()
    {
      Serial.begin(9600);

      Serial.println('a');
      char a = 'b';
      while (a != 'a')
      {
        a = Serial.read();
      }
    }
    void loop()
    {
    }

and my matlab code:

delete(instrfindall);
s = serial('/dev/tty.usbmodem1421');
set(s, 'BaudRate', 9600);
set(s, 'DataBits', 8);
set(s, 'StopBits', 1);
set(s, 'Parity', 'none');
set(s, 'Terminator', 'LF');
fopen(s);

% VERIFY SERIAL COMMUNICATION HAS BEEN SETUP
a = 'b';
while (a~='a')
        a = fread(s,1,'uchar');
end
if (a == 'a')
    disp('Serial read')
end
fprintf(s,'%c','a');
mxbox = msgbox('Serial Communication Initialized'); uiwait(mxbox);

The matlab code executes and I get the message box telling me that it has initialised, however the variable a is not read successfully and the while loop exits prematurely, debugging I found that it actually only loops for one iteration and then continues. 'Serial read' is never displayed.

Any help would be appreciated, thanks in advance.

Note

adding disp(size(a));disp(double(a)); after the fread yielded output 1 0 and no output respectively

It looks like your conditions are a logical negation, but it is not. Both conditions are false for a=[] (or a=['a','b'] ). Reading nothing could explain the behaviour you observed. Try this code instead:

a = 'b';
while (~strcmpi(a,'a'))
        a = fread(s,1,'uchar');
end
if (strcmpi(a,'a'))
    disp('Serial read')
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM