micros()

설명

아두이노 보드가 현재 프로그램을 돌리기 시작한 후의 마이크로 초 수를 반환한다. 이 수는 약 70분 후 오버플로우(0으로 돌아감)된다. 16MHz 아두이노 보드(e.g. Duemilanove 및 Nano)에서, 이 함수는 4 마이크로 초 분해능(즉 반환값은 언제나 4의 배수)을 갖는다. 8MHz 아두이노 보드(e.g. LilyPad)에서, 이 함수는 8 마이크로 초 분해능을 갖는다.

문법

time_us = micros()

매개변수

  • 없음

반환값

  • 아두이노 보드가 현재 프로그램을 돌리기 시작한 후 지난 마이크로 초 수를 반환. (unsigned long)

예제 코드

예제 코드 1

아두이노 보드가 시작한 후의 마이크로 초 수를 반환한다.

unsigned long time_us; void setup() { Serial.begin(9600); } void loop() { Serial.print("Time: "); time_us = micros(); Serial.println(time_us); // 프로그램 시작후 지난 시간 delay(1000); // 1초 기다림 }

시리얼 모니터에 결과:

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  

예제 코드 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"); } }

※ 주의 및 경고:

  • 1 밀리초는 1천 초, 1초는 1백만 초.
  • 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 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.