micros()

Descripción

Devuelve el número de microsegundos desde la que placa Arduino empezó a ejecutar el programa actual. Este número se desbordará (volverá a cero), después de aproximadamente 70 minutos. En placas Arduino de 16 MHz (por ejemplo Duemilanove y Nano), esta función tiene una resolución de cuatro microsegundos (es decir, el valor devuelto es siempre un múltiplo de cuatro). En las placas Arduino 8 MHz (por ejemplo, la LilyPad), esta función tiene una resolución de ocho microsegundos.

Sintaxis

time_us = micros()

Parámetros

  • Ninguno

Retornos

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

Ejemplo

Ejemplo 1

unsigned long time_us; void setup() { Serial.begin(9600); } void loop() { Serial.print("Time: "); time_us = micros(); Serial.println(time_us); // 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: 52 Time: 1000220 Time: 2000612 Time: 3001008 Time: 4001404 Time: 5001788 Time: 6002180 Time: 7002568
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 = 1000000; // 1000000us = 1s unsigned long previousMicros; void setup() { Serial.begin(9600); previousMicros = micros(); } void loop() { if (micros() - previousMicros >= TIME_INTERVAL) { previousMicros = micros(); Serial.println("Arduino References"); } }

※ Nota:

  • Hay 1.000 microsegundos en un milisegundo y 1.000.000 microsegundos en un segundo.
  • Please note that the return value for micros() is of type unsigned long, logic errors may occur if a programmer tries to do arithmetic with smaller data types such as int. Even signed long may encounter errors as its maximum value is half that of its unsigned counterpart.
  • The return value of micros() function rolls over back to zero after roughly 71 minutes. 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:
    • micros() >= (previousMicros + TIME_INTERVAL)
    • (micros() - previousMicros) >= 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 (micros() >= (previousMicros + TIME_INTERVAL)),
    • Use if(micros() - previousMicros >= TIME_INTERVAL) instead

ARDUINO BUY RECOMMENDATION

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

※ OUR MESSAGES