Time counting using millis I am trying to write a code where photoresistors (a or b) sense blinking of the light, and lights LED (k and d) simultaneosly with that blinking. And I want that when both photoresistors sense dark for more than 3 secs, the LEDs would light up and stay until one of them again gets lighting. But I cannot understand in which part should I put millis time count?


int k = 2;
int d = 3;
int fk = A0;
int fd = A1;
int a = 0;
int b = 0;

void setup() {
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  a = analogRead (fk);
  b = analogRead (fd);
  while (a &lt; 1000 &amp;&amp; b &lt; 1000)
  {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    a = analogRead (fk);
    b = analogRead (fd);
  }
  if (a &gt; 1000)
    digitalWrite(2, HIGH);
  else
    digitalWrite(2, LOW);
  if (b &gt; 1000)
    digitalWrite(3, HIGH);
  else
    digitalWrite(3, LOW);
}
This is one of those cases where the solution is simply to implement a
finite state machine. Consider a state machine with these three
states:


LIGH: light has been detected by at least one of the sensors, the
LEDs follow the light sensors
SHORT_DARK: neither sensor sees light, both LEDs are off
LONG_DARK: it has been at least three seconds since neither sensor
saw light, both LEDs are on.


The transitions between those states can be depicted by the following
state diagram:



where “darkness detected” means that no sensor sees light, and “light
detected” means that at least one sensor sees light.

As a general rule, it is a good practice to always draw a state diagram
before you start writing code. Once you are sure your diagram describes
the desired behavior, it is almost trivial to translate it into code.
Here is how I would code it:

void loop()
{
    bool light_k = analogRead(IN_K) &gt;= 1000;
    bool light_d = analogRead(IN_D) &gt;= 1000;

    static enum { LIGHT, SHORT_DARK, LONG_DARK } state;
    static uint32_t darkness_start;
    switch (state) {
    case LIGHT:
        digitalWrite(OUT_K, light_k ? HIGH : LOW);
        digitalWrite(OUT_D, light_d ? HIGH : LOW);
        if (!light_k &amp;&amp; !light_d) {
            darkness_start = millis();
            state = SHORT_DARK;
        }
        break;
    case SHORT_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        } else if (millis() - darkness_start &gt;= 3000) {
            digitalWrite(OUT_K, HIGH);
            digitalWrite(OUT_D, HIGH);
            state = LONG_DARK;
        }
        break;
    case LONG_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        }
        break;
    }
}