2016-02-19 56 views
0

我正在为Arduino的游戏结束计时器。基本上,程序从串口获取命令,翻转引脚,等待5秒钟,然后触发重置命令。它可以工作,但是它并不是43年第一次通过这个系列。它会第二次做到这一点,并在此后正常工作。这是为什么?我错过了什么?为什么第一次使用命令43时该引脚不会触发?

#include <elapsedMillis.h> 
elapsedMillis timeElapsed; 
int pin = 13; 
unsigned int wait = 5000; 

//// SERIAL ////////////////////////////////////////////// 
byte incomingByte; // from python 
int command = 0; // command (1 = open, 2 = close) 
int servoCom = 0; // the incoming command shit 

void setup() 
{ 
    Serial.begin(9600); 
    pinMode(pin, OUTPUT); 
    digitalWrite(pin, LOW); 
    Serial.println("setup done"); 

    // wait 20 ms 
    delay(20); 
} 

void loop() 
{ 
    if (Serial.available() > 0) 
    { 
    incomingByte = Serial.read(); 
    command = incomingByte; 
    servoCom = ServoGo(command); 
    } 

    if (servoCom == 43){ 
    digitalWrite(pin, HIGH); 
    // run for 5 seconds 
    if (timeElapsed >= wait) 
    { 
     // trigger reset 
     servoCom = 70; 
    } 
    } 
    if(servoCom == 70){ 
    // reset 
    digitalWrite(pin, LOW); 
    timeElapsed = 0; 
    } 
} 

int ServoGo(int com) 
{ 
    Serial.println("!inServoGo"); 
    Serial.println(com); 
    return com; 
} 
+0

因为你没有给'timeElapsed'分配一个初始值? – mindriot

回答

1

timeElapsed不是在设置初始化为零;它在第一个命令70后重新初始化,然后只有命令23正常工作。

+0

是的,就是这样。完全错过了。附加问题:当我初始化它时,第一次以2或3秒而不是全部5秒发射。任何想法? –

+0

@mishap_n为此提出另一个问题。它可能是不相关的东西。另外,我们需要查看您的修改后的代码。但只是猜测,如果在打开串口设备之前初始化变量,串口初始化的时间可能会影响您的(笨拙的)时间计算机制。 – YSC

相关问题