1.在sdk_config.h中加入宏
// TIMER_ENABLED - nrf_drv_timer - TIMER periperal driver - legacy layer //========================================================== #ifndef TIMER_ENABLED #define TIMER_ENABLED 1 #endif // TIMER_DEFAULT_CONFIG_FREQUENCY - Timer frequency if in Timer mode // 16 MHz // 8 MHz // 4 MHz // 2 MHz // 1 MHz // 500 kHz // 250 kHz // 125 kHz // 62.5 kHz // 31.25 kHz
#ifndef TIMER_DEFAULT_CONFIG_FREQUENCY #define TIMER_DEFAULT_CONFIG_FREQUENCY 4 #endif
// TIMER_DEFAULT_CONFIG_MODE - Timer mode or operation // Timer // Counter
#ifndef TIMER_DEFAULT_CONFIG_MODE #define TIMER_DEFAULT_CONFIG_MODE 0 #endif
// TIMER_DEFAULT_CONFIG_BIT_WIDTH - Timer counter bit width // 16 bit // 8 bit // 24 bit // 32 bit
#ifndef TIMER_DEFAULT_CONFIG_BIT_WIDTH #define TIMER_DEFAULT_CONFIG_BIT_WIDTH 3 #endif
// TIMER_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority
// Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // 0 (highest) // 1 // 2 // 3 // 4 // 5 // 6 // 7
#ifndef TIMER_DEFAULT_CONFIG_IRQ_PRIORITY #define TIMER_DEFAULT_CONFIG_IRQ_PRIORITY 6 #endif
#ifndef TIMER0_ENABLED #define TIMER0_ENABLED 1 #endif
// TIMER1_ENABLED - Enable TIMER1 instance
#ifndef TIMER1_ENABLED #define TIMER1_ENABLED 1 #endif
// TIMER2_ENABLED - Enable TIMER2 instance
#ifndef TIMER2_ENABLED #define TIMER2_ENABLED 1 #endif
// TIMER3_ENABLED - Enable TIMER3 instance
#ifndef TIMER3_ENABLED #define TIMER3_ENABLED 0 #endif
// TIMER4_ENABLED - Enable TIMER4 instance
#ifndef TIMER4_ENABLED #define TIMER4_ENABLED 0 #endif
2.导入文件nrfx_timer.c到工程中
3.引入头文件
#include "nrf_drv_timer.h"
4.定义定时器0实例 const nrf_drv_timer_t TIMER_LED = NRF_DRV_TIMER_INSTANCE(0); 5.定时事件处理函数
/** * @brief Handler for timer events. */ void timer_led_event_handler(nrf_timer_event_t event_type, void* p_context) { static uint32_t i; i ^= 1; switch (event_type) { case NRF_TIMER_EVENT_COMPARE0: printf("LED pin =%d\n",i); break;
default: //Do nothing. break; } }
6.在主函数中的处理
uint32_t time_ms = 1000; //Time(in miliseconds) between consecutive compare events. uint32_t time_ticks;
//Configure TIMER_LED for generating simple light effect - leds on board will invert his state one after the other. nrf_drv_timer_config_t timer_cfg = NRF_DRV_TIMER_DEFAULT_CONFIG; err_code = nrf_drv_timer_init(&TIMER_LED, &timer_cfg, timer_led_event_handler); APP_ERROR_CHECK(err_code);
time_ticks = nrf_drv_timer_ms_to_ticks(&TIMER_LED, time_ms); //转换成ms
nrf_drv_timer_extended_compare( &TIMER_LED, NRF_TIMER_CC_CHANNEL0, time_ticks, NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK, true);
nrf_drv_timer_enable(&TIMER_LED); //启动定时器