SDK版本:15.20
代碼
#include <stdbool.h>
#include <stdint.h>
#include "nrf_delay.h"
#include "boards.h"
#include "nrf_drv_timer.h"
//驅動程序實例的ID對應Timer的ID
const nrfx_timer_t TIMER_LED = NRFX_TIMER_INSTANCE(0);
//Timer事件回調函數
void timer_led_event_handler(nrf_timer_event_t event_type, void *p_context)
{
switch(event_type)
{
//CC[0]的比較匹配事件
case NRF_TIMER_EVENT_COMPARE0:
//翻轉指示燈D1狀態
nrf_gpio_pin_toggle(LED_1);
break;
}
}
//定時器初始化
void timer_init(void)
{
uint32_t err_code = NRF_SUCCESS;
uint32_t time_ms = 200; //定時時間為200ms
uint32_t time_ticks;
//定義定時器配置結構體,並使用默認配置參數初始化結構體
nrfx_timer_config_t timer_cfg = NRFX_TIMER_DEFAULT_CONFIG;
//初始化定時器,初始化時會注冊timer_led_event_handler事件回調函數
err_code = nrfx_timer_init(&TIMER_LED,&timer_cfg,timer_led_event_handler);
APP_ERROR_CHECK(err_code);
//定時時間(單位ms)轉換為ticks
time_ticks = nrfx_timer_ms_to_ticks(&TIMER_LED,time_ms);
//設置定時器捕獲/比較通道及該通道的比較值,使能通道的比較中斷
nrfx_timer_extended_compare(
&TIMER_LED,NRF_TIMER_CC_CHANNEL0,time_ticks,NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK,
true);
}
int main()
{
//初始化開發板上的4個LED,即將驅動LED的GPIO配置為輸出
bsp_board_init(BSP_INIT_LEDS);
timer_init(); //初始化定時器
nrfx_timer_enable(&TIMER_LED); //啟動定時器
while(true)
{
}
return 0;
}