2014-02-25 96 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秒。這就是爲什麼在超過超時的延遲之後才能執行。