簡體   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