2013-05-16 61 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.实现的那样这很可能是保持内存/资源消耗低但开发时间昂贵的最佳解决方案。