can arduino keep track of time


What is a time sensitive while loop, oh it’s, a loop that will perform a task for a set interval of time. However long you want the task to be the Arduino to perform that task, that’s. What the particular control structure in this piece of code does and as it performs one task say for five seconds, then it shifts over and performs a different task for three seconds and then it loops back around and goes back to doing the other tasks for five Seconds on and on and on, and but it could just as well perform one task for a set interval of time, and then you could do other things for, however long it takes what this particular coding structure is useful, for is when you want to test performed For an interval of time, but you and you don’t really want to have to worry about how many iterations that task is performed during that interval of time. So you don’t really care say if you were blinking an LED is your task that you won’t perform for five seconds and you don’t really care how many times the LED blinks. So much as you just want it to blink for five seconds and then stop blinking or go stable and just beyond and go do other things you have. The Arduino perform some other tasks, that’s. What it’s good for, in cases where you don’t know the number of iterations that will occur within five seconds, for example? Nor do you care how many iterations occur during that five seconds.

You just know that you want it done for a certain interval of time, a particular task, and you want it to stop after that interval of time and their Arduino do something else. That’S what time sensitive while loops are good for? Is there a solution to that problem? There nothing only solution or the only way to accomplish that behavior. But they are a kind of handy little code structure to have on hand at times to see an example of this let’s upload this piece of code and to open the serial monitor and what we’ll see on the serial monitor is two different sentences or printing. The first sentence is inside first, while loop and it prints for five seconds, and then this other sentence occurs well there’s inside the first, while loop, then there’s inside the second, while loop we’re back inside the first while loop inside the second while loop, and if you Watch this long enough, what you’ll notice is that this sentence inside the first while loop prints for a longer interval than inside the second while loop, namely this sentence, is printing for five seconds and then it shifts out of printing that sentence and starts printing the other One for three seconds – and this is just a cereal example of performing tasks for specific intervals and jumping from one to the other after that interval is passed. Look at the code again so what’s going on there is that we’re having the Arduino use a while loop control structure, which we’ll look at in just a second to do something for 5 seconds.

And then after that, 5 seconds has passed. It exits one loop and then jumps into another while loop then does something else for 3 seconds, namely prints particular sentences to the screen relative to each of the loops jumps back and forth back forth. You wouldn’t have to have it jump back and forth. It could just do that first sentence for five seconds and then do something totally different, but that’s what time sensitive while loops are good for they’re good for cases where you want the Arduino to perform a task for a certain period of time. You don’t care. How many iterations like how many individual sentences it would print to the screen in that 5 seconds? You just want it to print that sentence for the 5 seconds or you won’t. Let, for example, advance a stepper motor by one step for 5 seconds. You don’t know the exact number of steps you want that stepper motor to go, but you know you want it to run for 10 seconds, 5 seconds, a half, a second etc. That should give everybody a sense of what this particular control structure can accomplish. For you, I’ll have another video that I’ll upload right behind this one, showing it applied to the control of stepper motors. So you get an application in your mind immediately after this video, so let’s start looking. The first thing we’ll need is some global variables will have one variable of the unsigned long type.

Then it needs to be unsigned long, because this is where we’re going to be restoring a return value from that inbuilt function known as mils, and it returns an unsigned long value. So you want your variable that’s going to be capturing and storing that value to match the type that it’s returning, and I have just named it time since last reset because that’s what the Mules function returns. It returns the amount of milliseconds the Arduino has been running since it was initially turned on or since the last time the reset button was pressed. But when you turn your dueo on it does a reset that is the coming own of the Arduino. Is everything starts back at the top of your code, we’re going to capture that number and use it as a reference throughout this code, but we just need an unsigned long time variable. You can name it something differently, initialize it to zero, just for simplicity, sake and then we’ll have to, in this case, integer type variables because I’m not going to exceed an upper limit that an integer type can be. But you could just as well use a long or an unsigned long if you wanted this interval to be really long. If you wanted the Arduino to perform a task to say for six minutes and then jump out, you want your variable to be of a type that could handle the whatever number that you need, and in this case we’re thinking in terms of milliseconds.

A thousand milliseconds per second first interval interval – one is 5000 milliseconds – is what this will eventually come out to be or it’s five seconds, that’s the way to think about it and we’re going to associate interval one with a first while loop that we’ll see below then Interval two is 3000, which is 3000 milliseconds or three seconds. Then you could add is many intervals, as you want moving right long in the setup given that I’m using this is a serial example printing stuff to the monitor we have to initialize a serial can action. I did it at 9600. Baud brief delay just to give that connection a little time to establish now to the interesting bit what’s inside the main loop or void loop. However, you prefer to refer to it. We have our first while loop, and then we cannotice – we have your second while loop down here. You wouldn’t have to have a second one, but in this example, I’ve used two old just to show how you can jump back and forth between two performing tasks at different intervals. First thing we’ll do, is we make a call to the mills function? What that function? Will return is the amount of milliseconds since the Arduino was first turned on or the last time it was reset we’ll collect that return, value and store it in the time since last, reset that’s going to be our stable reference point for this while loop is that’ll, Be the unchanging number it’s, the one we will use as the stable reference when we enter the while loop beside the while loop it’s test, while loop always has to have a test in order that it’s going to say is this true and if it is I’m Going to loop, if it’s not true, that I’m going to stop or I’m going to go on to some other tasks, that’s the way a while loop works, a lot like a for loop, the except a while loop is good.

When you don’t know the number of iterations you need, a for loop is good, say. If you know you want a task repeated 15 times or 20 times or 50 times for loops a way to go because it’s, just simple, it’s, very straightforward. If you know the exact number of iterations, you need for loops away to go, but a while loop is good. When you don’t really know the amount of times you want the task inside the loop performed or you don’t really care. You just want it to loop. For a certain period of time, or you want it to loop until some other event occurs, maybe an interrupt or some values updated in some way as soon as we enter the while loop in its test, we’re going to call the Mules function again. What will this return the times? Well, it’ll return the time since the Arduino was last reset notice. We froze that earlier up here. We before we ever win in the while loop. We said how long has it been since you were last turned on for the sake of this example: let’s assume it’s been a thousand milliseconds, so we have 1000, as our reference say, 1000 milliseconds has passed since the Arduino was turned on in this case. Of this example it’s not going to be 1000, but in other examples it might be. You might have done a lot of stuff in setup and it took time to do those things so say: it’s been a thousand milliseconds since the Arduino was first turned on that’s.

The number that’s stored in our time since last reset we called Mills, it returned a thousand milliseconds. We stored it in the time since last reset variable. Then, when we enter this while loop, we call the mills function again, we say well, how long is it being now, given that these are then the initial pass through of the main loop? This will be a very these two numbers will be very close. It’S, like this number, might it could be 1000. This one might be 1001. Let’S just add that in there save 1001 and replace meals with it that’s the value it returned. Then what are we going to do? We’Re going to subtract the 1000 that we have stored in time since last reset from the 1001. What will be the result, while a 1 that’s, the number you would have here? If you have 1000 on our initial call to mils, then we call it again and then, given that these two lines of code are executing back to back you don’t leave a very, very little difference between the two numbers have 1000 here have 1001 here. Well, 1001 minus 1000 will be 1. Then we ask is 1 less than interval 1. Well, what was interval 1 up here. We started it out with 5000 is 1 less than 5000. Yes, so what is the while loop? Do? It performs the task inside its bracket? There’S the curly brackets for the while loop – and in this case the task is to print the sentence inside the first while loop.

This could be advancing a stepper motor by one step or ten steps or whatever you desire. It could be blinking an LED. It could be collecting an input from a sensor say you want to collect the input from a temperature sensor for five seconds and then go do other things and then come back and collect it for five seconds, more etc. Whatever you would need with you won’t, whatever your task is you want it to appear inside that, while loop, while loop test, we ended up with? We have the number one here. One is less than 5000, so it’s going to print inside the first while loop, it will get the bottom curly braket roll back up and go back through the while it’ll say. Okay. What time is it now? We’Ll say your tasks took 50 milliseconds that when we make our call to meals, it’s going to say woody we’re going to ask how long since the last time you were reset, it could return. 1051. Then we’re going to subtract from that 1051. Our stable reference value, which remember, was one thousand thousand fifty one minus one thousand, will return. Fifty one be one less than five thousand. Yes, it is so it’s going to print inside the first, while loop, then it’ll hit the bottom of the bracket, go back up to the wild and say it took 50 more milliseconds. Now we have 11 hundred and one 101 minus 1000 will be one hundred and one that’ll be less than five thousand so it’s going to print the sentence again on and on and on until after five seconds has passed, where this number will return, the subtraction will Be like say, 50, 101 or 5050 will be.

The number that will come out of the subtraction. Well, that’ll be greater than interval, one which is five thousand, so the while loop will stop we’ll exit the while loop – and this is just for display purposes with this – is just printing empty spaces on the screen, and then it will jump into the second while loop. What do we do, then? Each get a new reference point. We make a call to meals, and we say how long is it being since your last reset for simplicity, let’s just say that in thousand that’s, the time since last reset you are doing has been running for 10 seconds, and then we store that in time. Since last reset meals returns 10000, we store it here. Then we enter the while loop and we call mewls again the first time this first initial move as soon as we come from this line of code to this one there’ll be very little difference between this number and what’s returned what the number returned here, but as We make it through this loop. This number will be constantly getting bigger, as it should have. Meals say it could be 10000 and one the first time, it’s called well 10000. One minus 10000 will be one and well 1, is less than interval 2, which up above was set to 3000. That means we’ll end. While the test will be true, 1 is less than or yeah 1 is less than 3000, so it will print the sentence hit the bottom of the while loop go back up to the top then we’ll sample it again.

This could be 10050, so 10050 minus 10000. Will be 50, 50 is less than 3000 sotell and it’ll print the sentence inside second while loop. Then it will do this until the value returned from this case of subtraction is higher or greater than interval 2 and just notice. It’Ll. Do that and it’ll give you the time you want. It may be off a few milliseconds. It may be 3000 in 2 milliseconds just a that. It takes before it exits this while loop, but if you don’t really care, if it’s a millisecond or two off you just want it for them very close to 3. Second sight 3 seconds and a few fractions over 3 seconds isn’t going to matter. This will work perfectly fine and then we’ll and once that 3 Sciences past it prints two spaces to the serial monitor just I’ve done that for demonstration purposes. Then it hits the bottom of the main loop and it goes back up to the top mm that’s. All there is to the code that’s how it works. I’Ll put this code in the first comment on the video, but I hope this video has been helpful. I hope that explanation is helpful. If there are questions just post them in the comments, I’ll be glad to do my best to help and also for an application of this.


can arduino keep track of time Video







can arduino keep track of time news








can arduino keep track of time Social






Last weekend we announced that we’re working on a new development environment with advanced features. Let’s take a deeper look at what is in store for the Arduino Pro IDE!
safe image.php?d=AQB3t842udQGDBtr&w=720&h=720& content%2Fuploads%2F2019%2F10%2FPRO IDE BlogpostFeatured - can arduino keep track of time

“Let us change the world by making technology accessible to everyone and put it into the hands of every student and educator.”
safe image.php?d=AQCy9PEcAbMgaw1B&w=720&h=720&url=fbstaging%3A%2F%2Fgraph.facebook - can arduino keep track of time



(Visited 77 times, 1 visits today)

About The Author

You might be interested in

Comment (19)

  1. Code discussed in the video.

    title: Time_Sensitive_While_Loops
    by: philomech
    date: 1/2015
    description: While loops that perform tasks for specific intervals

    * global variables         *
    unsigned long time_since_last_reset = 0;  
    int interval_one = 5000;                  //5 seconds, 1st while loop
    int interval_two = 3000;                  //3 seconds, 2nd while loop

    * setup                     *
    void setup(){
    * main loop                 *
    void loop(){
    //1st while loop  
      time_since_last_reset = millis();                 //obtain reference  
      while((millis() – time_since_last_reset) < interval_one){      Serial.println("Inside 1st while loop.");      //task one wants repeated                                                                      //for interval_one     }      Serial.println(""); Serial.println("");      //2nd while loop   time_since_last_reset = millis();                //obtain reference    while((millis() - time_since_last_reset) < interval_two){      Serial.println("Inside 2nd while loop.");   //task one wants repeated                                                                    //for interval_two    }    Serial.println(""); Serial.println("");      }  // <--- end of main loop

  2. Hi Philo,
    You were a major help in the past and I was wondering if you could help me again. I am trying to use arduino to close a relay once every hour and log data before relay closure and then after.  
    I’ve been trying to understand how to create a time LONG time delay for arduino, from my understanding, the regular delay cannot do something more than a minute? Others I have seen have used some strategy which uses millis() against a set interval in order to approximate the period when to activate the relay? but this is a bit much for my software understanding.  Or am I really making this more complex than it needs to be? I can’t just use delay for a long amount of time?  Thanks 

    1. Appreciate the question!
      In principle, one could use the inbuilt delay function to halt an Arduino for longer than a minute, but there tends to be a ‘better’ (relatively speaking) way to achieve multi-minute, and especially–>hour to multiple hour delays.  Namely, one can use a real time clock chip/module.  Just connect one to the Arduino and have it trigger the data storage/relay trigger  events every hour on the hour.  

      I’ve had a lot of success with Adafruit’s DS1307 real time clock breakout board kit.  

      Adafruit also provides a helpful description of the setup and library needed to use the DS1307 under their learn section.  The chip might lose a second or so every now and then, but it tends to be accurate enough for many projects.  

      I’ve used the the DS1307 breakout to control everything from arduino based clocks, automatic door locks, automatic pet doors, automatic feeders, etc., etc., always with reliable performance.  I’d definitely encourage you to check it and Adafruit’s description out and see if it might be suitable for your project.  It not, then just let me know and we’ll go from there.  

      Hope these comments help.  And, please continue to let me know if/when there are more questions.  I’ll always do my best to help.      

    2. @philo mech Thanks philo you are awesome I really appreciate the help! I now see delay sucks.  I wanted to get a RTC but I was being frugal with cash, and havent had the need for such precision. I just want a valve to open every now and then, and thats fine for me.  What i figured out is that I could use millis() to just open a contact for 1 second, and every hour since the variable  resets every ~49 days will this stay accurate saying I reset the arduino every day 24 hrs? How inaccurate does millis become?. I’m now attempting to code data acquisition into the eeprom. 

  3. I have a question I am trying to stay in a while loop
    when the button is not being published anymore for a few seconds I wanted to exit
    the loop
    go back to

    void loop

    1. @Michael Parrish Appreciate the comment and question.  

      Might you say a little more about the target behavior?

      Are you trying to accomplish something like the following:
      (1) Void Loop() is running
      (2) a button is pressed which triggers entry into a while loop
      (3) the processor remains inside the while loop as long as the button is pressed(?)  
      (4) and then exits the loop as soon as the button is released(?)

      Or might you be seeking something else?

      Just let me know and I will do my best to help.

  4. Can you trigger this particular price of code on a with a tactile switch? Or does time_until_last_reset start counting the minute the Arduino boots? I keep trying to implement this code… By giving a particular task a certain amount of time to execute. If there is no more activity on the button for 3 seconds: It takes whatever increment it is on and performs that task.


    If(buttonState == 1)

    While(time_until_last_reset == threeSeconds)

    If(buttonState == high)




    Case 1

    Do this

    Case 2

    Do This

    Case 3

    Do This


    Not understood



    someVariable = 0

    1. @Jaren Hudson
      I’m trying to understand the order and logic of what you want the arduino to do.  

      Do you want: 

      (1) the arduino to listen for a button press
      (2) if a button press doesn’t occur within 3 seconds,
      (3) then do something


      (1)the arduino to be performing various tasks
      (2) and if/when a button press occurs,
      (3) do some task for 3 seconds
      (4) and then return to what it was previously doing?


      Might you have some other order/event logic in mind?

      Just let me know and I will do my best to help.

      Also, time_since_last_reset will equal whatever the current value of millis() happens to be. For example, suppose one enters the following inside void loop

      void loop(){

      time_since_last_reset = millis();




      The first time through the loop a value in ms will be returned from the millis() function and assigned to the time_since_last_reset variable. This value will reflect how long the arduino has been powered up/running since either battery power was initially applied or since the last time the reset button on the board was pressed. Each time through the main loop (in the above example) one will notice around a 500ms increase in the value of time_since_last_reset.  

      Essentially, calling millis() asks for the amount of milliseconds the processor has been operating since power up or since the reset button was pressed. The value returned by millis() will always be increasing each time it’s called. Time is always passing. Calling millis() is asking the arduino “how long have you been running?” One can and often does use the answer to this question combined with later calls to millis() to do things like determine a duration, ‘delay’ without technically ‘delaying’, etc.  


      void loop(){ 
      time_since_last_reset = millis();

      //perform some tasks

      time_now = millis();

      duration_of_performed_tasks = (time_now – time_since_last_reset);

      Hope these comments help.

    2. @philo mech I am looking for a particular while loop to start at the press of a button… You select different “options” by pressing that same button again within those three seconds. I am attaching a piece of code (there may be a few mistakes) I just need to know where to add the time related functions.

      */This program is intended to listen for a button to be pressed. When it is pressed I need a time-sensitive while loop
      to be triggered. This will act as a time out. If the button is pressed again within the three seconds it will incrment
      an “option” variable. This will be used after the time out in a switch statement and print what option you chose within
      those three seconds.

      int IncrementingVar;//Variable to store “options”

      int Button = 12;//Button on pin twelve with pull-down

      void setup()
      pinMode(Button, INPUT);//Button as input

      Serial.begin(9600);//Serial Communications

      void loop()
      int buttonState = digitalRead(Button);//New variable for “button”

      if(buttonState == 1)//check if button is pressed
      while(time)//This is where I need the time sensitive loop to execute but I can’t seem to get the dang thing to start timing
      { //once the button is pressed. I don’t want it timing once the Arduino boots.
      if(buttonState == 1){//if button is pressed again before the three seocnds pass… increment “options” variable.
      ++ IncrementingVar;
      }else//do nothing
      switch(IncrementingVar)//compare value of “options” variable to option choices
      case 1:
      Serial.println(“Option 1”);

      case 2:
      Serial.println(“Option 2”);

      case 3:
      Serial.println(“Option 3”);

      Serial.println(“No decisions made within three seocnds!”);
      }else//Inform that there were no button presses
      Serial.println(“Listening again in 3 seconds”);
      IncrementingVar = 0;//reset the “options” variable if anything is stored

    3. @Jaren Hudson
      Please see the following code. It’s not the most refined way to accomplish what you seem to be after but it should get us started. I’ve tried to capture the control logic associated with the task. Feel free to refine, modify, etc., it to better fit your application. I included some crude/rough software debouncing . If you’re using hardware to debounce the button then such won’t be needed.

      This is a first pass/draft. If it misses the mark, or you have something else in mind, etc., then just let me know and we can go from there.

      /* (ROUGH VERSION)
      title: time_sensitive_mode_selection
      * global variables *
      const byte button_pin = 12;
      boolean button_value = LOW;

      unsigned long time_since_last_reset = 0;
      int selection_delay = 4000; //adjust as needed

      int previous_mode = 0;
      int current_mode = 0;
      int max_modes = 4; //adjust as needed

      * setup *
      void setup(){
      Serial.begin(9600); delay(150);
      pinMode(button_pin, INPUT);

      } //<--end of setup /**************** * main loop * ****************/ void loop(){ //read button button_value = digitalRead(button_pin); //button pressed? (crude software debouncing) if(button_value == HIGH){ //if so, then delay for a few ms, give button contacts //time to stop bouncing delay(150); //and then read button pin again button_value = digitalRead(button_pin); //if it's still HIGH, then if(button_value == HIGH){ //print message to user Serial.println("\nYou have 4 seconds to make a selection.\n"); delay(500); //give him/her enough time to read it //get current time time_since_last_reset = millis(); //and repeatedly test...has 4 seconds passed?...has 4 seconds passed?... while((millis() - time_since_last_reset) < selection_delay){ //if not, then print message Serial.println("make a selection!"); //and repeatedly check button button_value = digitalRead(button_pin); //crude debounce again if(button_value == HIGH){ delay(150); //if button value goes HIGH if(button_value == HIGH){ //and the value currently assgined to mode //hasn't exceeded the max number of modes if(current_mode < max_modes){ //increment mode value by 1 current_mode++; delay(10); //for stability //print message...the currently selected mode is... Serial.print("\ncurrent_mode = "); Serial.println(current_mode); Serial.println(""); //give user time to read mode delay(500); } //otherwise, current mode value has //exceeded max number of possible modes else{ //reset current mode to 0 current_mode = 0; //and make previous and current mode values match previous_mode = current_mode; } } } } //let user know that the selection window has expired Serial.println("\nselection window expired\n"); delay(2000); } //previous_button_value = current_button_value; } /*if user did happen to change the mode value during the 4 second window, then run new mode value through switch()*/ /*if no change to mode value was made, then stay in whatever mode was previously selected */ if(current_mode != previous_mode){ switch(current_mode){ case 1: Serial.println("\nmode 1 selected\n"); //set previous_mode value to current_mode value previous_mode = current_mode; //do whatever else here delay(2500); break; case 2: Serial.println("\nmode 2 selected\n"); previous_mode = current_mode; delay(2500); break; case 3: Serial.println("\nmode 3 selected\n"); previous_mode = current_mode; delay(2500); break; case 4: Serial.println("\nmode 4 selected\n"); previous_mode = current_mode; delay(2500); break; } } //display current mode Serial.print("--current mode--: "); Serial.println(current_mode); } //<-- end of main loop

    4. @philo mech Thanks much. Very timely replies; I appreciate that. I will optimize it and change a few things around. I am using hardware to debounce the switch, to conserve memory. Thanks again though!

    5. @Jaren Hudson Glad the example code looks helpful. It can definitely be refined and optimized. I didn’t have much time but I wanted to provide you with something that was close to what was needed as quickly as possible. The switch case structure might need to be relocated/tweaked, etc., in order to accomplish precisely what you’re after. But hopefully the example provides some helpful ideas. And removing the crude debounce code would be an immediate improvement, I didn’t have a s-trigger, etc., ready to hand. If there are more questions along the way, please continue to let me know and I will always do my best to help.

  5. Thanks for the tutorial. Most of the time people are running their Arduino for short periods of time, experiments etc., but if planning to put your Arduino in service for longer periods of time, and wish to use this kind of routine for timing critical or semi critical operations, it’s good to remember that the Millis() register rolls over every 50 days, and if using micros() the register rolls over around every 70 minutes. Good coding practices should take this into account when coding the while loop condition.


Your email address will not be published. Required fields are marked *