Using Time and Dates
12.0 Introduction
Managing time is a fundamental element of interactive computing. This chapter covers built-in Arduino functions and introduces many additional techniques for handling time delays, time measurement, and real-world times and dates. You’ll learn about Arduino’s built-in function for introducing delays into your sketch, as well as more advanced techniques for intermittently performing operations. Other recipes in this chapter cover how to measure time as it passes, and even how to use an external real-time clock for tracking time and dates.
12.1 Using millis to Determine Duration
Problem
You want to know how much time has elapsed since an event happened; for example, how long a switch has been held down.
Solution
The following sketch uses the millis() function to print how long a button was pressed (see Recipe 5.2 for details on how to connect the switch):
/*millisDuration sketchreturns the number of milliseconds that a button has been pressed*/constintswitchPin=2;// the number of the input pinunsignedlongstartTime;// the value of millis when the switch is pressedunsignedlongduration;// variable to store the durationvoidsetup(){pinMode(switchPin,INPUT_PULLUP);Serial.begin(9600);}voidloop(){if(digitalRead(switchPin)==LOW){// here if the switch is pressedstartTime=millis();while(digitalRead(switchPin)==LOW);// wait while the switch is still pressedunsignedlongduration=millis()-startTime