This is an old revision of the document!
Writing code that handles interrupts that come from internal peripherals, for example, timers, is possible, but depends strongly on the hardware. Because this chapter presents an introduction to programming, more advanced techniques can be found in other positions. Here some basic timing functions will be shown.
The simplest solution to make functions work for a certain time is to use the delay() [1] function. delay() function stops program execution for the time specified as the argument.
The previously shown blinking LED code is a simple demonstration of delay functionality:
digitalWrite(LED_BUILTIN, HIGH); //Turn the LED on delay(1000); //Stop program for a second digitalWrite(LED_BUILTIN, LOW); //Turn the LED off delay(1000); //Stop program for a second
Limitations that come with using delay(): most tasks stop, and there can be no sensor reading, calculation, or pin manipulation. Some tasks continue to work, like receiving serial transmissions and outputting set PWM values. The alternative to using delay is to use millis().
millis() [2] returns the number in milliseconds since Arduino began running the current program. The number will reset after approximately 50 days. millis() can be used to replace delay(), but needs some additional coding.
Here is an example code of blinking LED using millis(). Millis is used as a timer. Every new cycle time is calculated since the last LED state change. If the time passed is equal to or greater than the threshold value the LED is switched:
//Unsigned long should be used to store time values as the millis() returns 32-bit unsigned number //Store value of current millis reading unsigned long currentTime = 0; //Store value of time when last time the LED state was switched unsigned long previousTime = 0; bool ledState = LOW; //Variable for setting LED state const int stateChangeTime = 1000; //Time at which switch LED states void setup() { pinMode (LED_BUILTIN, OUTPUT); //LED setup } void loop() { currentTime = millis(); //Read and store current time //Calculate passed time since the last state change //If more time has passed than stateChangeTime, change the state of the LED if (currentTime - previousTime >= stateChangeTime) { previousTime = currentTime; //Store new LED state change time ledState = !ledState; //Change LED state to oposite digitalWrite(LED_BUILTIN, ledState); //Write current state to LED } }
Check Yourself
1. What are the drawbacks of using delay()?
2. What is the difference between delay() and millis()?
3. Explain why millis() timer value resets after about 50 days.