본문 바로가기
공부/프로그래밍

아두이노에서도 타이머 사용하기(setInterval, setTimeout)

by demonic_ 2015. 8. 24.
반응형

아두이노에서 setInterval,  setTimeout 을 사용하고 싶어서 찾아보던 찰나 

SimpleTimer 라이브러리를 발견.

링크 => http://playground.arduino.cc/Code/SimpleTimer



여기선 setInterval, setTimeout 뿐만 아니라

지금 실행되고 있는 setInterval, setTimeout 를 종료시키거나 리셋시키는 것도 있다.


다만 라이브러리를 코드를 복사해서 파일로 만든다음에 추가해야 하므로 귀찮은 작업이다. 

그러므로 여기다가 그 파일들을 압축해서 올려놓는다.

(다운로드)

SimpleTimer.zip



아래는 간단한 샘플이다. 

#include <SimpleTimer.h>


// the timer object

SimpleTimer timer;            // timer 를 쓰겠다고 선언하고


// a function to be executed periodically

void repeatMe() {            // 이건 일정 시간마다 실행할 function 을 만든것

    Serial.print("Uptime (s): ");

    Serial.println(millis() / 1000);

}


void setup() {               

    Serial.begin(9600);

    timer.setInterval(1000, repeatMe);        // 이와같이 타이머를 설정할 수 있다. 파라미터는 '시간(밀리초)', 'function이름' 2개다

}


void loop() {

    timer.run();                    // loop 부분에 이와같이 run()을 실행해줘야한다.

}



실행중인 타이머를 종료시키기 위해서라도 변수에 담아두는게 좋다. 

int timerId = timer.setTimeout(1000, callMeLater);


이렇게 선언해두면 restartTimer(int timerId), deleteTimer(int timerId) 두개의 function으로 종료하거나 리셋시킬수 있다. 

물론 이게 아니어도 getNumTimers() 라는 변수를 통해 timedId 를 가져올 수 있다.


#include <SimpleTimer.h>


// the timer object

SimpleTimer timer;            // timer 를 쓰겠다고 선언하고


void setup() {

    wd_timer_id = timer.setInterval(10000, wdCallback);          // 이런식으로 설정을 하면

}


void loop(){

timer.restartTimer(wd_timer_id);            // timer_id 를 통해서 리셋시킬 수 있다. 

}





다음은 기능들에 대한 문서정리다.

Functions

SimpleTimer()

The constructor. You usually need only one SimpleTimer object in a sketch.

SimpleTimer timer;

int setInterval(long d, timer_callback f)

Call function f every d milliseconds. The callback function must be declared as void f().

void repeatMe() {
    // do something
}

timerId = timer.setInterval(1000, repeatMe);

int setTimeout(long d, timer_callback f)

Call function f once after d milliseconds. The callback function must be declared as void f(). After f has been called, the interval is deleted, therefore the value timerId is no longer valid.

void callMeLater() {
    // do something
}

timerId = timer.setTimeout(1000, callMeLater);

int setTimer(long d, timer_callback f, int n)

Call function f every d milliseconds for n times. The callback function must be declared asvoid f(). After f has been called the specified number of times, the interval is deleted, therefore the value timerId is no longer valid.

void repeatMeFiveTimes() {
    // do something
}

timerId = timer.setTimer(1000, repeatMeFiveTimes, 5);

boolean isEnabled(int timerId)

Returns true if the specified timer is enabled

if(timer.isEnabled(timerId) {
    // do domething
}

void enable(int timerId)

Enables the specified timer.

timer.enable(timerId);

void disable(int timerId)

Disables the specified timer.

timer.disable(timerId);

void toggle(int timerId)

Enables the specified timer if it's currently disabled, and vice-versa.

timer.toggle(timerId);

void restartTimer(int timerId)

Causes the specified timer to start counting from "now", i.e. the instant when restartTimer is called. The timer callback is not fired. A use case for this function is for example the implementation of a watchdog timer (pseudocode follows).

void wdCallback() {
    alert user or perform action to restore
    program state (e.g. reset the microprocessor)
}

wd_timer_id;

void setup() {
    wd_timer_id = timer.setInterval(10000, wdCallback);
}

void loop() {
    timer.run();

    big complex critical code

    timer.restartTimer(wd_timer_id);
}

void deleteTimer(int timerId)

Free the specified timerId slot. You should need to call this only if you have interval slots that you don't need anymore. The other timer types are automatically deleted once the specified number of repetitions have been executed.

void getNumTimers()

Return the number of used slots in a timer object.

n = timer.getNumTimers();





반응형

댓글