简体   繁体   English

Matlab和Arduino串行通讯

[英]Matlab & Arduino serial communication

I am trying to get some basic serial communication up and running. 我正在尝试启动和运行一些基本的串行通信。 My arduino code is shown below. 我的arduino代码如下所示。

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

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

and my matlab code: 和我的Matlab代码:

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. matlab代码执行后,我得到一个消息框,告诉我它已经初始化,但是变量a没有成功读取,而while循环过早退出,调试时我发现它实际上只循环一次迭代,然后继续。 'Serial read' is never displayed. 从不显示“串行读取”

Any help would be appreciated, thanks in advance. 任何帮助将不胜感激,在此先感谢。

Note 注意

adding disp(size(a));disp(double(a)); 添加disp(size(a));disp(double(a)); after the fread yielded output 1 0 and no output respectively fread之后分别输出1 0和无输出

It looks like your conditions are a logical negation, but it is not. 看来您的条件是合乎逻辑的否定,但事实并非如此。 Both conditions are false for a=[] (or a=['a','b'] ). 对于a=[] (或a=['a','b']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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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