For simplicity consider a rather simple state machine with a button and LEDs: A single button press should light up an LED and after a specific ammount of time the LED should automatically turn off. In fact this works if I write the condition in the loop() like this:
if (millis()-t1>=timeLimit){
digitalWrite(L1,0);
}
if (millis()-t2>=timeLimit){
digitalWrite(L2,0);
}
if (millis()-t3>=timeLimit){
digitalWrite(L3,0);
}
t1, t2, and t3 are assigned the sketch uptime 'millis()' at the time the button was pressed.
I want to declare a function just to reduce the size of my loop() function. I tried to declare this function:
void timeCheck()
{
millis();
if (millis()-t1>=timeLimit){
digitalWrite(L1,0);
}
if (millis()-t2>=timeLimit){
digitalWrite(L2,0);
}
if (millis()-t3>=timeLimit){
digitalWrite(L3,0);
}
}
and call it in the loop() function, but by doing so, the LEDs won't light up.
int buttonPIN=2; //Button
int L1=6; //LED 1
int L2=5; // LED 2
int L3=4; // LED 3
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
unsigned long t1=0;
unsigned long t2=0;
unsigned long t3=0;
unsigned long timeLimit = 2500; //The time after each LED should turn off
void setup()
{
pinMode(L1, OUTPUT);
pinMode(L2, OUTPUT);
pinMode(L3, OUTPUT);
pinMode(buttonPIN, INPUT);
}
void loop()
{
buttonState = digitalRead(buttonPIN);
if (buttonState == 1 && lastButtonState==0)
{
buttonPushCounter++;
switch(buttonPushCounter)
{
case 1:
digitalWrite(L1,1);
t1=millis();
break;
case 2:
digitalWrite(L2,1);
t2=millis();
break;
case 3:
digitalWrite(L3,1);
t3=millis();
buttonPushCounter=0;
break;
}
}
lastButtonState = buttonState;
if (millis()-t1>=timeLimit)
{
digitalWrite(L1,0);
}
if (millis()-t2>=timeLimit)
{
digitalWrite(L2,0);
}
if (millis()-t3>=timeLimit)
{
digitalWrite(L3,0);
}
}
Note:
You have set up a potential problem with the way you are using this.
if (millis() - t1 >= timeLimit)
{
digitalWrite(L1, 0);
}
The code will constantly turn off the LED when >= is met.
This might be hard find, in a much larger program, if you ever turn on L1 somewhere else.
Also, at every ~72 days >= will not be true for 2.5 seconds.
It is best to include a disable flag to preempt the above.
if (L1Flag == true && millis() - t1 >= timeLimit)
{
digitalWrite(L1, 0);
L1Flag = false;
}
And in:
case 1:
digitalWrite(L1,1);
t1=millis();
L1Flag = true;
break;