HELP: If Sensor Reached This Value, Pin HIGH for certain time.

Hi, I am just new to microcontrollers and I need help. I have a sensor (waterflow sensor) and a relay to turn on a 12v motor.

as of now, my code is like this:

if (sensorvalue <=100) { digitalWrite(relaypin, HIGH); }
else { digitalWrite(relaypin, LOW); }

the problem is, I cannot seem to find (or understand) codes that I may need.

what I would like to do is:

if sensorvalue <=100 , then it should do this: digitalWrite(relaypin, HIGH) continous if condition is still true, then if condition turned false, it will start count 12seconds before it goes LOW or off.

I hope I have explained the logic clear enough. Thanks in advance!

BTW, is it okay to use delay() here? I mean, would it affect other tasks?

read about state machines and using millis() (in the thread at the top "Useful links - check here for reference posts / tutorials")

The cheap and dirty way:

  if (sensorvalue <= 100)
  {
    digitalWrite(relaypin, HIGH);
    while (sensorvalue <= 100)
    {
      // Must update or the loop will never end
      sensorvalue = ReadSensorValue();
    }
    delay(12000);  // Wait 12 seconds
    digitalWrite(relaypin, LOW);
  }

Thanks for the inputs masters. After watching videos and doing trial and errors, I managed to crack it. I ended up mastering the millis function and found myself replacing all the delay functions with millis. It was cool!

well done Jaus2s !

Jaus2s:
Thanks for the inputs masters. After watching videos and doing trial and errors, I managed to crack it. I ended up mastering the millis function and found myself replacing all the delay functions with millis. It was cool!

Very good! For all but the simplest sketches, using a state machine model and millis() instead of delay() is the right way to do it.