analogRead() when value is lower than 500 and it takes longer than 2 seconds

Hi all,
I need little help with time in arduino. I have arduino uno with mega 328P.

I am reading from analog input, and i want a condition, when the value form photoresistor is lower than 500 AND this value is longer than 2 seconds on analog input A0? How can I write this condition ?

This doesn’t work for me:

void loop()
{
unsigned long currentMillis = millis();
int photosensor = analogRead(A0);
if(photosensor < 500 && currentMillis > 3000 )
{
Serial.println("“done”)
}

Thanks for any help

}

So you need to capture the moment when A0 starts to be above 500 and then keep looping and reading A0, ensuring it's still above 500 and comparing current time with the start time

unsigned long StartTime = 0;
void setup() {Serial.begin(9600);}
void loop() {
  unsigned long currentMillis = millis();
  int photosensor = analogRead(A0);
  if (photosensor < 500) {
    if (StartTime == 0) {
      StartTime = currentMillis;
    } else {  // photosensor < 500 && StartTime != 0
      if (currentMillis - StartTime >= 2000) {
        Serial.println("done");
      }
    }
  } else {  // photosensor >= 500
    StartTime = 0;
  }
}

Thank you very much. I will try the code tomorow. Dudes You are awesome :slight_smile: