2013-05-16 63 views
1

我有以下代碼,但只能在通電時一次發送m1 on。之後,我的arduino忽略了發送給它的串行數據。只能讀取一次串行數據

謝謝你的幫助。

#include <AccelStepper.h> 

AccelStepper stepper(1, 3, 2); 

char inData[20]; // Allocate some space for the string 
char inChar=-1; // Where to store the character read 
byte index = 0; // Index into array; where to store the character 

void setup() 
{ 
    stepper.setMaxSpeed(1000.0); 
    stepper.setAcceleration(1000); 
    stepper.setCurrentPosition(0); 
    Serial.begin(9600); // Begin serial communiation at 9600. 
    Serial.write("Power On"); 
} 
char Comp(char* This) { 
    while (Serial.available() > 0) // Don't read unless 
            // there you know there is data 
    { 
     if(index < 19) // One less than the size of the array 
     { 
      inChar = Serial.read(); // Read a character 
      inData[index] = inChar; // Store it 
      index++; // Increment where to write next 
      inData[index] = '\0'; // Null terminate the string 
     } 
    } 

    if (strcmp(inData,This) == 0) { 
     for (int i=0;i<19;i++) { 
      inData[i]=0; 
     } 
     index=0; 
     return(0); 
    } 
    else { 
     return(1); 
    } 
} 

void loop() 
{ 
    if (Comp("m1 on")==0) { 
     Serial.write("Motor 1 -> Online\n"); 
    } 
    if (Comp("m1 off")==0) { 
     Serial.write("Motor 1 -> Offline\n"); 
    } 
} 
+0

什麼是您的串行輸出? –

+0

輸入'm1 on'或'm1 off'會產生相應的'Motor 1 - > Online \ n'或'Motor 1 - > Offline \ n'響應,但這隻能執行一次。 – mh00h

+0

然後你陷入無限循環。強制你的while循環在幾次迭代之後中斷以驗證這一點。 –

回答

1

您的代碼似乎停留在(錯誤的)假設上,只要讀取第一個字符,發送字符串就會完全可用。所以,當你開始分析時,你可能會收到「m1」,但尚未「開啓」。這反過來確保你的字符串比較總是會失敗,你的代碼似乎被卡住了。

我建議你在適當的位置添加Serial.print語句,看看你的代碼實際收到了什麼以及它如何處理它。一旦你有足夠的打印,你會更好地理解發生了什麼,並能夠自己解決這個問題。

順便說一句:最簡單的解決方法是不使用字符串作爲簡單命令,而是使用字符。另一個簡單的解決方法是give the parsing work to a suitable library.也有其他類似的庫。

另一種解決方案是使用有限狀態機來解析串行接口,就像我爲this experiment.實現的那樣這很可能是保持內存/資源消耗低但開發時間昂貴的最佳解決方案。