mishap_n
mishap_n

Reputation: 618

Why does this pin not fire the first time the command 43 comes in?

I'm working on a timer for the end of a game in Arduino. Basically, the program gets a command from serial, flips a pin, waits for 5 seconds, then triggers a reset command. It works, but it doesn't do it the very first time '43' comes through the serial. It will do it the second time and work fine after that. Why is that? What am I missing?

#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;
}

Upvotes: 0

Views: 40

Answers (1)

YSC
YSC

Reputation: 40100

timeElapsed is not initialized to zero at setup; it got reinitialized after the first command 70, then only command 23 works properly.

Upvotes: 1

Related Questions