There are two functions for the use of timing in the code of Arduino - delay() and millis(). Although they might look similar, their functionality is different and should be used in different cases.
The delay() function pauses the execution of a program for a determined amount of time that is defined by milliseconds in the brackets. The down side of the delay() function is that none of the other program functions can execute while the time defined in the function is not passed.
The syntax of the function is the following:
delay(ms)
The parameter ms is the number of milliseconds to pause. The type should be unsigned long. The function returns nothing.
The example code:
int ledPin = 13; // LED connected to digital pin 13 void setup() { pinMode(ledPin, OUTPUT); // sets the digital pin as output } void loop() { digitalWrite(ledPin, HIGH); //LED is on delay(1000); //pause for 1000 milliseconds digitalWrite(ledPin, LOW); //LED is off delay(1000); //pause for 1000 milliseconds }
The delay() function also has the version that is using microseconds instead of milliseconds and it is called - delayMicroseconds().
The millis() timing function works a bit differently, because it returns the amount if milliseconds that have passed since the program was started. Millis() function is often used to determine the interval of time and to check if it has passed. One of the benefits of using millis() is that the program is not paused until the time interval will pass and any other functions can still execute. The second benefit is better accuracy in timing than using the delay() function.
The syntax of the function is following:
time = millis()
This function does not have the input parameters in brackets. The return value of the function is the number of milliseconds that has passed since the program was started. The type is unsigned long.
The example of the function in the code:
int period = 1000; //the interval unsigned long time_now = 0; //variable that stores the last timing value void setup() { Serial.begin(9600); } void loop() { if(millis() > time_now + period){ //testing, if the time that has passed exceeds 1000 milliseconds (1 second) time_now = millis(); //the newest time value is stored in the time_now variable Serial.println("1 second"); //Print out the text } //Some other code that executes each time the loop is run }
This function also has the version of using microseconds instead of milliseconds - micros(). The purpose of this is improving the precision by enhancing resolution.