繁体   English   中英

从Matlab通过串口与Arduino通信的问题

[英]Issue communicating over serial to Arduino from Matlab

更新2 :事实证明,在打开串行端口后,只需要添加一个pause(2)即可。

更新我能够在Matlab命令窗口中手动输入Matlab代码,它将按预期更新LED,但是我无法调用执行此操作的函数。 我将尝试添加时间延迟,也许Arduino缓冲区无法跟上。

我正在使用带有Sparkfun PWM屏蔽的Arduino Uno来控制3个LED。 我编写了一个Arduino草图,该草图寻找用于设置LED值的串行输入,以及准备和发送串行输出的Matlab代码。 请参阅下面的所有代码。

由于某种原因,几个月前起作用的该代码已停止工作。 我现在使用的是Matlab的2011b版本,以前使用的是2013a。 没有其他改变。

我相信问题出在串行通信上,因为我可以通过同时运行Matlab和Arduino IDE,在Arduino IDE中打开串行监视器,然后发出Matlab命令来使其正常工作。 它根据需要设置LED值。 为了发送另一个命令,我需要首先关闭,然后重新打开Arduino串行监视器。

Matlab代码:

function [] = displayColor(RGB)

s1 = serial('/dev/tty.usbmodem1411','BaudRate',9600);

fopen(s1)

messageRed = bitshift(1,12)+RGB(1);
messageGreen = bitshift(2,12)+RGB(2);
messageBlue = bitshift(3,12)+RGB(3);
fwrite(s1,messageRed,'uint16','sync');
fwrite(s1,messageGreen,'uint16','sync');
fwrite(s1,messageBlue,'uint16','sync');
updateMessage = 0;
fwrite(s1,updateMessage,'uint16','sync');

fclose(s1)

end

Arduino代码:

#include "Tlc9540.h"
int newVal = 0;

void setup(){
Tlc.init();
Serial.begin(9600);
delay(1000);
}

void loop(){

updateChannel();  

}

int updateChannel()
{

int B;
int code;
int value;

  if (Serial.available())
  {
    //Read First Byte
    B = Serial.read();
    //Blocking - waiting for second byte
    while (!Serial.available()){}
    B+=Serial.read()<<8;
    code = (B&(B1111<<12))>>12;
    value = B&4095;
    switch (code)
    {
      case 0:
        Tlc.update();
        break;
      case 1:
        Tlc.set(0,value);
        Serial.print(Tlc.get(0));
        break;
      case 2:
        Tlc.set(1,value);
        Serial.print(Tlc.get(1));
        break;
      case 3:
        Tlc.set(2,value);
        Serial.print(Tlc.get(2));
        break;
    }
  }  
}

为了通过Matlab通过串行端口使用Arduino,似乎需要约2秒的时间延迟。 在开始通过串行线路发送数据之前增加延迟就可以了。

我通过设置自己的串行终结器(我用!作为终结器)解决了这个问题。 当我发送串行命令时,我使用! 作为终结者。

set(arduino,'Terminator','!'); % setting my terminator

然后在我的代码中:

test_free = 'mode=free,axis=1,dir=1,speed=50,pos=13245!';
fprintf(arduino,test_free);

我认为问题在于matlab正在等待终止符。 如果未满,则执行超时并将其设置为2秒。 这就是为什么延迟大于超时后才可以执行的原因。

暂无
暂无

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

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