2014-02-25 101 views
2

更新2:原来在打开串口后添加了一个pause(2)就是它所需要的。从Matlab通过串行通信到Arduino的问题

更新我能够手动输入Matlab代码到MATLAB命令窗口,它会更新LED作为预期,但我不能把我的函数,这样做。我会尝试添加时间延迟,或许Arduino缓冲区跟不上。

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

由于某些原因,此代码在几个月前工作,已停止工作。我现在正在使用2011b版本的Matlab,并且之前使用了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; 
    } 
    } 
} 
+1

也许这是一个愚蠢的问题,但你确定你的USB /串口适配器仍然是'/ dev/tty.usbmodem1411'吗? – ChrisJ

+0

嗨@ChrisJ,是啊 - 目前我只是手动检查串口并在必要时进行更新。 – Alex

+0

你能和你谈谈单独使用Arduino应用程序的Arduino开发板吗?没有Matlab(使用串行的例子之一)? Arduino应用程序是否也设置为使用'/ dev/tty.usbmodem1411'?另外,请确保阅读[2011b的归档文档](http://www.mathworks.com/help/releases/R2011b/index.html),而不是通过Google可能找到的新内容(或者只是使用'帮助“和”文档“)。 – horchler

回答

0

为了在Matlab的通过串行端口接合的Arduino似乎需要的〜2秒的时间延迟。在开始通过串行线路发送数据之前添加一个延迟的技巧。

0

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

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

然后在我的代码:

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

我觉得现在的问题是,MATLAB是等待终止。如果没有满载,则执行超时并将其设置为2秒。这就是为什么在超过超时的延迟之后才能执行。