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
The result on Serial Monitor:
Ejemplo 2
Print a text one time per second without blocking other codes
※ 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 |