millis()
Description
Renvoie le nombre de millisecondes depuis que la carte Arduino a commencé à exécuter le programme courant. Ce nombre débordera (càd sera remis à zéro) après 50 jours approximativement.
Syntaxe
variable_unsigned_long=millis();
Paramètres
- Aucun
Valeurs Renvoyées
- Le nombre de millisecondes depuis que le programme courant a démarré. Renvoie une variable long non signée.
Exemple
Exemple 1
unsigned long time;
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.print("Time: ");
time = millis();
//affiche sur le PC le temps depuis que le programme a démarré
Serial.println(time);
// pause d'une seconde afin de ne pas envoyer trop de données au PC
delay(1000);
}
The result on Serial Monitor:
COM6
Time: 0
Time: 999
Time: 1999
Time: 3000
Time: 4000
Time: 5000
Time: 6000
Time: 7001
Time: 8001
Time: 9001
Autoscroll
Clear output
9600 baud
Newline
Exemple 2
Print a text one time per second without blocking other codes
const unsigned long TIME_INTERVAL = 1000;
unsigned long previousMillis;
void setup() {
Serial.begin(9600);
previousMillis = millis();
}
void loop() {
if (millis() - previousMillis >= TIME_INTERVAL) {
previousMillis = millis();
Serial.println("Arduino References");
}
}
※ Remarque:
- Bien remarquer que la valeur retournée par millis() est un long non signé : des erreurs pourront avoir lieu si le programmeur essaie de faire des opérations mathématiques avec d'autres types de données tels que des int.
- The return value of millis() function rolls over back to zero after roughly 50 days. If the sketch is intended to run for longer than that, It needs to make sure the rollover does not make the sketch fail. To solve it, write rollover-safe code. Let's compare the two following inequations:
- millis() >= (previousMillis + TIME_INTERVAL)
- (millis() - previousMillis) >= TIME_INTERVAL
- Mathematically, they are equivalent to each other. However, in programming, they are not. That is because the size of storage is unlimited in mathematics while it is limited to 4 bytes in Arduino programming. In programming, when the rollover happens, the first inequation makes the sketch fail while the second inequation does NOT. Therefore:
- Do NOT use if (millis() >= (previousMillis + TIME_INTERVAL)),
- Use if(millis() - previousMillis >= TIME_INTERVAL) instead
※ ARDUINO BUY RECOMMENDATION
Arduino UNO R3 | |
Arduino Starter Kit |
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.
Additionally, some links direct to products from our own brand, DIYables.