2016年2月3日 星期三

nRF51x22 Simple Timer Code

1. 定義一個固定時間觸發的Timer.


2. 只需要Timer Init 和 Timer Handler這兩個function就可以用了.

Timer Init:
-------------------------------------------------------------------------------------------------------------------------
void Timer_Init(int32_t deltatime)  
{
    
    NRF_TIMER2->BITMODE     = TIMER_BITMODE_BITMODE_16Bit; //Set counter to 16 bit resolution
    NRF_TIMER2->MODE        = TIMER_MODE_MODE_Timer;
    NRF_TIMER2->PRESCALER   = 9;               //16MHz/(2^9) = 16MHz/512 = 31250Hz = 32usec
    NRF_TIMER2->CC[2]       = (deltatime/32);            //250 = 8msec , 500 = 16msec
    NRF_TIMER2->INTENSET    = TIMER_INTENSET_COMPARE2_Enabled << TIMER_INTENSET_COMPARE2_Pos;
    NRF_TIMER2->SHORTS      = (TIMER_SHORTS_COMPARE1_CLEAR_Enabled << TIMER_SHORTS_COMPARE1_CLEAR_Pos);
                
    NVIC_ClearPendingIRQ(TIMER2_IRQn);
    NVIC_SetPriority(TIMER2_IRQn,3);
    NVIC_EnableIRQ(TIMER2_IRQn);  
    NRF_TIMER2->TASKS_START = 1; 
}



Timer Handler:
-------------------------------------------------------------------------------------------------------------------------

void TIMER2_IRQHandler(void)  
{
    if((NRF_TIMER2->EVENTS_COMPARE[2] == 1) && (NRF_TIMER2->INTENSET & TIMER_INTENSET_COMPARE2_Msk))
    {
 NRF_TIMER2->EVENTS_COMPARE[2] = 0;
   
 //nrf_gpio_pin_toggle(20);      //debug gpio
       
 NRF_TIMER2->TASKS_CLEAR = 1; 
    }
}

3. 假設需要定義一個固定每10msec會觸發的Timer, 可以在Init的時候帶入這樣的參數.     Timer_Init(10000);

沒有留言:

張貼留言