一、實驗內容:
配置NRF51822 的RTC0 的TICK 頻率為8Hz,COMPARE0 匹配事件觸發周期為3 秒,並使能了TICK 和COMPARE0 中斷。
- TICK 中斷中驅動指示燈D1 翻轉狀態, 即指示燈D1 以8Hz 的速率翻轉狀態
- COMPARE0 中斷中點亮指示燈D2
二、nRF51822的內部RTC結構:
NRF51822 有兩個RTC 時鍾:RTC0,RTC1。兩個RTC 均為24 位,使用LFCLK 低頻時鍾,並帶有12 位分頻器,可產生TICK、compare 和溢出事件。RTC 原理框圖如下圖所示:
三、計數器遞增頻率的計算:
fRTC[KHz]=32.768/(PRESCALER+1)
由上式可以看出,設置遞增頻率也就是設置相應的PRESCALER,如設置遞增頻率為8Hz。那么,PRESCALER 值如下:
PRESCALER = round(四舍五入) (32.768 kHz / 8 Hz) – 1 = 4095
此時,遞增周期是:125ms。
四、核心源碼解析:
main:
1 int main(void) 2 { 3 leds_config(); 4 lfclk_config(); 5 rtc_config(); 6 7 while (true) 8 { 9 __SEV(); 10 __WFE(); 11 __WFE(); 12 } 13 }
RTC初始化:
1 static void rtc_config(void) 2 { 3 uint32_t err_code; 4 5 //Initialize RTC instance 6 err_code = nrf_drv_rtc_init(&rtc, NULL, rtc_handler);//初始化RTC 7 APP_ERROR_CHECK(err_code); 8 9 //Enable tick event & interrupt 10 nrf_drv_rtc_tick_enable(&rtc, true);//使能tick事件 11 12 //Set compare channel to trigger interrupt after COMPARE_COUNTERTIME seconds 13 err_code = nrf_drv_rtc_cc_set(&rtc, 0, COMPARE_COUNTERTIME * RTC0_CONFIG_FREQUENCY, true); 14 APP_ERROR_CHECK(err_code); 15 16 //Power on RTC instance 17 nrf_drv_rtc_enable(&rtc); 18 }
RTC中斷回調函數:
1 /** @brief: Function for handling the RTC0 interrupts. 2 * Triggered on TICK and COMPARE0 match. 3 */ 4 static void rtc_handler(nrf_drv_rtc_int_type_t int_type) 5 { 6 if (int_type == NRF_DRV_RTC_INT_COMPARE0) 7 { 8 nrf_gpio_pin_toggle(COMPARE_EVENT_OUTPUT); 9 } 10 else if (int_type == NRF_DRV_RTC_INT_TICK) 11 { 12 nrf_gpio_pin_toggle(TICK_EVENT_OUTPUT); 13 } 14 }
@nRF51822基礎實驗系列:
[nRF51822] 8、基礎實驗代碼解析大全 · 實驗11 - PPI
[nRF51822] 9、基礎實驗代碼解析大全 · 實驗12 - ADC
@beautifulzzzz - 物聯網&普適計算實踐者
e-mail:beautifulzzzz@qq.com
i-blog:blog.beautifulzzzz.com