millis()

Descripción

Devuelve el número de milisegundos desde que la placa Arduino empezó a ejecutar el programa actual. Este número se desbordará (volverá a cero), después de aproximadamente 50 días.

Sintaxis

time_ms = millis()

Parámetros

  • Ninguno

Retornos

  • Número de milisegundos desde que el programa se inició (unsigned long)

Ejemplo

Ejemplo 1

unsigned long time_ms; void setup() { Serial.begin(9600); } void loop() { Serial.print("Time: "); time_ms = millis(); Serial.println(time_ms); // prints time since program started delay(1000); // wait a second so as not to send massive amounts of data }

The result on Serial Monitor:

COM6
Send
Time: 0 Time: 999 Time: 1999 Time: 3000 Time: 4000 Time: 5000 Time: 6000 Time: 7001 Time: 8001 Time: 9001
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Ejemplo 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"); } }

※ Nota:

  • Tenga en cuenta que el valor de retorno para millis() es un long sin signo, pueden producirse errores lógicos si un programador intenta hacer operaciones aritméticas con tipos de datos más pequeños, como de tipo int. Incluso los log con signo pueden producir errores como que su valor máximo sea la mitad que la de su contraparte sin signo.
  • 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

Ver También

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are affiliate links. If you buy the components through these links, We may get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES

  • We are AVAILABLE for HIRE. See how to hire us to build your project
  • Any suggestion, correction, and translation? please email us at ArduinoGetStarted@gmail.com, We appreciate it
  • We mainly keep improving the references in English. See English version of this page for the latest update.