Time Function...

I am doing a project that runs a specific code once two probes are submerged in water, hence completing the circuit. I want the code to only run if the two probes have been submerged in water for 10 seconds or more. I was wondering what function to use to find out the elapsed time since the probes were submerged in water. I googled around, but I couldn't find a function to find out the elapsed time. I appreciate in advance for your advice!!

When you dunk the electrodes, set an unsigned long variable to millis() like this:

unsigned long startTime = millis();

and define a constant to represent 10 seconds worth of millis:

const long tenSeconds = 10000L;

Then loop through your code, and check millis() minus the startTime each time through, like this:

if (millis() - startTime > tenSeconds)
  {  // do whatever you want to do after 10 seconds
  }

Thanks a lot!! I really appreciate it!!

I want to add something on state flags and not running the "// do whatever you want to do after 10 seconds" code more than once (unless it runs forever in which case that's ok) since millis() - startTime is still > tenSeconds even when it's finished.

But I'm hectically busy right now and can't think that through. So I'm just posting this placeholder so that a) you can think about that and b) so I can watch the thread and post when I have a chance.

Thanks a lot!! I really appreciate it!!

JimboZA: I want to add something on state flags and not running the "// do whatever you want to do after 10 seconds" code more than once (unless it runs forever in which case that's ok) since millis() - startTime is still > tenSeconds even when it's finished.

But I'm hectically busy right now and can't think that through. So I'm just posting this placeholder so that a) you can think about that and b) so I can watch the thread and post when I have a chance.

Hey Jimbo, the way I deal with that is to have a flag that is true if it hasn't been run yet, but is set to false when the "whatever you want" routine runs. Then there would be some mechanism (like pushing a button, or ...) that would reset the flag, so that it could be run again at some point.

ChrisTenone: Hey Jimbo, the way I deal with that is to have a flag that is true if it hasn't been run yet, but is set to false when the "whatever you want" routine runs. Then there would be some mechanism (like pushing a button, or ...) that would reset the flag, so that it could be run again at some point.

Yep, some mechanism like that is what I had in mind

Hey Chris and Jimbo, Thanks for your input and knowledge! I used the delay function to resolve my problem. I put a delay for 1 second and validated the circuit's completion. I repeated this 10 times. If the circuit was incomplete anytime during the 10 seconds, I will come out from the loop, which is what I wanted. I am an eighth grade student and may come back with more questions until I finish my project :) Thanks!!

Blueberry16: Hey Chris and Jimbo, Thanks for your input and knowledge! I used the delay function to resolve my problem. I put a delay for 1 second and validated the circuit's completion. I repeated this 10 times. If the circuit was incomplete anytime during the 10 seconds, I will come out from the loop, which is what I wanted. I am an eighth grade student and may come back with more questions until I finish my project :) Thanks!!

Hi Blueberry16, wow - eighth grade sure isn't what it used to be! Congratulations on getting a first rate education (at least in the vowel of STEM!) Be cautious with the delay() function. It stops everything else on your Arduino from happening until the delay period has elapsed. It's much better to count millis until a certain number of them have elapsed (there are 1000 millis per second - it means "milliseconds") then do the thing you want to do when the 'timer runs out', that is, when the number of millis reaches your time period. That way, you can make your sketch more complex without needing to re-write every routine. It never stops running just to wait. This is called "non-blocking code" in the Arduino parlance.

Be cautious with the delay() function. It stops everything else on your Arduino from happening until the delay period has elapsed.

@Blueberry16.
If you continue with the Arduino and want to become proficient, listen to the words above words.

Here is a sketch that you might want to look at when you get more into writing code.
Non blocking code - no delay() - is a must when writing sketches.

//Blink without Delay skeleton example using a structure.
//LarryD

//======================================================================
struct timer
{
  //lastMillis = the time this "timer" was (re)started
  //waitMillis = delay time (mS) we are looking for. You can use math 60*60*1000 for 1 hour
  //restart    = do we start "this timer" again and again  
  //enableFlag = is "this timer" enabled/allowed to be accessed
  //**********************
  //For each timer object you need: 
  //Example:
  //   timer myTimer = //give the timer a name "myTimer"
  //   {
  //     0, 200UL, true, true  //lastMillis, waitMillis, restart, enableFlag 
  //   };
  // You have access to: 
  // myTimer.lastMillis, myTimer.waitMillis, myTimer.restart, myTimer.enableFlag, myTimer.CheckTime() 
  //**********************

  unsigned long lastMillis; 
  unsigned long waitMillis; 
  bool          restart; 
  bool          enableFlag;
  bool CheckTime() //Delay time expired function "CheckTime()"
  {
    //is the time up for this task?
    if (enableFlag && millis() - lastMillis >= waitMillis) 
    //Note: if delays of < 2 millis are needed use micros() and adjust waitMillis as needed
    {
      //should this start again? 
      if(restart)
      {
        //get ready for the next iteration
        lastMillis += waitMillis;  
      }
      //time was reached
      return true;
    }
    //time was not reached
    return false;
  } //END of CheckTime()

}; //END of structure timer
//======================================================================


//**********************************************************************
//Let's create 6 timer objects and initialize them in this sketch
//**********************************************************************
timer pin13 = //create timer pin13
{
  0, 200UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer pin12 = //create timer pin12
{
  0, 3*1000UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer pin11 = //create timer pin11
{
  0, 10*1000UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer pin10 = //create timer pin10
{
  0, 6*1000UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer Toggle10 = //create timer Toggle10
{
  0, 50UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************
timer checkSwitches = //create timer checkSwitches
{
  0, 50UL, true, true //lastMillis, waitMillis, restart, enableFlag
};
//***************************

byte lastMySwitchState = 1; //for mySwitch on Pin 2
byte counter           = 0; 

const byte Pin13 = 13;
const byte Pin12 = 12;
const byte Pin11 = 11;
const byte Pin10 = 10;
const byte Pin9  =  9;

const byte mySwitch = 2;

//**********************************************************************

void setup()
{
  Serial.begin(9600);

  pinMode(Pin13,OUTPUT);
  pinMode(Pin12,OUTPUT);
  pinMode(Pin11,OUTPUT);
  pinMode(Pin10,OUTPUT);
  pinMode(Pin9, OUTPUT);

  digitalWrite(Pin13,LOW);
  digitalWrite(Pin12,LOW);
  digitalWrite(Pin11,LOW);
  digitalWrite(Pin10,LOW);
  digitalWrite(Pin9, LOW);

  pinMode(mySwitch,INPUT_PULLUP);


} //  >>>>>>>>>>>>>> E N D  O F  s e t u p ( ) <<<<<<<<<<<<<<<<<


void loop()
{
  //Below are examples demonstrating different timing situations 

  //***************************
  //example 1    Toggle Pin13 every 200ms
  if (pin13.CheckTime())
  {
    //Toggle Pin13
    digitalWrite(Pin13,!digitalRead(Pin13));

    //if you only want this section of code to happen once
    //uncomment the next line 
    //pin13.enableFlag = false;
  }

  //***************************
  //example 2    After 3 seconds, Pin12 goes and stays HIGH 
  if (pin12.CheckTime())
  {
    //Make Pin12 HIGH now
    digitalWrite(Pin12,HIGH);
    //disable timing section of code 
    pin12.enableFlag = false;
  }

  //***************************
  //example 3    Pin11 is HIGH for 10 seconds, then goes and stays LOW
  if (pin11.enableFlag && !pin11.CheckTime())
  {
    digitalWrite(Pin11,HIGH);
  }
  //10 seconds is now up now, leave the Pin11 LOW
  else
  {
    digitalWrite(Pin11,LOW);
    //disable timing section of code 
    pin11.enableFlag = false;
  }

  //***************************
  //example 4    For 6 seconds, toggle Pin10
  if (pin10.enableFlag && !pin10.CheckTime())
  {
    //example 5  Toggling Pin10 every 50mS
    if(Toggle10.CheckTime())
    {  
      //toggle Pin10
      digitalWrite(Pin10,!digitalRead(Pin10));    
    }
  }
  //6 seconds is now up, toggling is stopped
  else
  {
    digitalWrite(Pin10,LOW);
    //disable timing section of code 
    pin10.enableFlag = false;
  }

  //***************************
  //example 6    Is it time to check the switches?
  if (checkSwitches.CheckTime())
  {
    //time to read the switches
    Switches();      
  } 

  //**********************************
  //Put other non-blocking stuff here
  //**********************************

} //  >>>>>>>>>>>>>> E N D  O F  l o o p ( ) <<<<<<<<<<<<<<<<<


//======================================================================
//                      F U N C T I O N S
//======================================================================


//**********************************************************************
//switches are checked every checkSwitches.waitMillis milli seconds 
//no minimum switch press time is validated with this code (i.e. No glitch filter)
void Switches()  
{
  boolean thisState; //re-usable for all the switches      

  //*************************** mySwitch Pin 2 code  
  //check if this switch has changed state
  thisState = digitalRead(mySwitch); 
  if (thisState != lastMySwitchState)
  {  
    //update the switch state
    lastMySwitchState = thisState;  

    //This switch position has changed, let's do some stuff

    //"HIGH condition code"
    //switch goes from LOW to HIGH
    if(thisState == HIGH)        
    {
      //example: LED on Pin9 is Push ON, Push OFF
      digitalWrite(Pin9,!digitalRead(Pin9)); 
    }

    //"LOW condition code"
    //switch goes from HIGH to LOW
    else                          
    {
      //example: display the current switch push count 
      Serial.println(++counter);      
    }
  } //END of mySwitch Pin 2 code

  //******************************************  
  //similar code for other switches goes here 
  //******************************************  

} //END of Switches()


//======================================================================
//                        E N D  O F  C O D E
//======================================================================