【问题标题】:Matlab & Arduino serial communicationMatlab & Arduino 串行通信
【发布时间】:2015-03-07 12:11:56
【问题描述】:

我正在尝试启动并运行一些基本的串行通信。我的 arduino 代码如下所示。

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

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

还有我的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);

matlab 代码执行,我得到消息框告诉我它已经初始化,但是变量 a 没有成功读取,while 循环过早退出,调试我发现它实际上只是循环进行一次迭代,然后继续。 'Serial read' 永远不会显示。

任何帮助将不胜感激,在此先感谢。

注意

fread之后添加disp(size(a));disp(double(a));分别产生输出1 0和无输出

【问题讨论】:

  • 出于调试目的,您能否在fread 行之后添加disp(size(a));disp(double(a)); 并将输出附加到您的问题中?

标签: matlab serial-port arduino


【解决方案1】:

看起来您的条件是逻辑否定,但事实并非如此。对于a=[](或a=['a','b']),这两个条件都是错误的。什么都不读可以解释你观察到的行为。试试这个代码:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
相关资源
最近更新 更多