millis()
You can learn about the millis() function in the Arduino reference. You should become familiar with the Arduino reference. You should be able to locate and use the reference for any computer programming language you are using.
Java, also called API: https://docs.oracle.com/javase/8/docs/api/overview-summary.html
Processing : https://processing.org/reference/
HTML and Javascript: https://www.w3schools.com/JSREF/DEFAULT.ASP
HTML, CSS and Javascript: https://developer.mozilla.org/en-US/docs/Web/Reference
The millis() function is a counter that starts counting milliseconds from the start of a program. Millis() can count for about 50 days and then it resets. The cool thing about millis is that it gives a way of timing events in our programs without using the delay() function. When we use delay() the program stalls and nothing else can happen until the delay time is reached. We can set a variable to be equal to millis() and make something happen when millis() reaches a new value. Other code can execute while millis happily counts away the time. We could have an LED on our robot blinking away while we drive the robot around. Delay() is never used and so other commands or lines of code will be executed immediately without having to wait.
/* Blink Using millis()
* Relies on the millis() function to blink an LED
* connected to GPIO 12. By using millis() we
* can add other code to the loop without
* effecting the blink timing.
* Mike Druiven, Mar 8, 2021
*/
int ledPin = 12 ; // the number of the LED pin
long OnTime = 1000; // milliseconds of on-time
long OffTime = 500; // milliseconds of off-time
int ledState; // ledState used to set the LED
unsigned long previousMillis; // will store last time LED was updated
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
// check to see if it's time to change the state of the LED
if((ledState == HIGH) && (millis() - previousMillis >= OnTime))
{
ledState = LOW;
previousMillis = millis(); // Remember the time
digitalWrite(ledPin, ledState); // Turn LED off
}
else if ((ledState == LOW) && (millis() - previousMillis >= OffTime))
{
ledState = HIGH;
previousMillis = millis(); // Remember the time
digitalWrite(ledPin, ledState); // Turn LED on
}
/* You can put more code in the main loop here
* as long as you do not use delay(). This code
* will run and then the main loop will start over.
* If neither if condition is met this code will run again
* and then the main loop will start again until
* one of the if conditions above is met
*/
}