1 概述
定时器能够被配置为两种模式:定时模式和计数模式,nrf52832有五个定时器,timer0--timer4 。因为SDK已经使用了timer0,所以如果使用了SDK,就不能再使用timer0,只能使用timer1--timer4。
2 常用的函数
函数功能:初始化定时器
ret_code_t nrf_drv_timer_init (
nrf_drv_timer_t const *const p_instance, //Pointer to the driver instance structure.
nrf_drv_timer_config_t const * p_config, //Initial configuration. If NULL, the default configuration is used.
nrf_timer_event_handler_t timer_event_handler //Event handler provided by the user. Must not be NULL.
)
函数功能:Function for converting time in milliseconds to timer ticks.
__STATIC_INLINE uint32_t nrf_drv_timer_ms_to_ticks (
nrf_drv_timer_t const *const p_instance,
uint32_t time_ms
)
函数功能:Function for setting the timer channel in extended compare mode
void nrf_drv_timer_extended_compare (
nrf_drv_timer_t const *const p_instance, //Pointer to the driver instance structure.
nrf_timer_cc_channel_t cc_channel, //Compare channel number.
uint32_t cc_value, //Compare value.
nrf_timer_short_mask_t timer_short_mask, //Shortcut between the compare event on the channel and the timer task (STOP or CLEAR).
bool enable_int //Enable or disable the interrupt for the compare channel.
)
函数功能:开启定时器
void nrf_drv_timer_enable ( nrf_drv_timer_t const *const p_instance )
注意
在nrf_driver_config.c中修改timer的定义
#define TIMER1_ENABLED 0
#if (TIMER1_ENABLED == 1)
#define TIMER1_CONFIG_FREQUENCY NRF_TIMER_FREQ_16MHz //Timer frequency 16 MHz.
#define TIMER1_CONFIG_MODE TIMER_MODE_MODE_Timer //选择定时器模式
#define TIMER1_CONFIG_BIT_WIDTH TIMER_BITMODE_BITMODE_16Bit //16bit的定时器宽度
#define TIMER1_CONFIG_IRQ_PRIORITY APP_IRQ_PRIORITY_LOW
#define TIMER1_INSTANCE_INDEX (TIMER0_ENABLED)
#endif
比如在实验中要开启Timer1,则要把TIMER1_ENABLED宏置为1
3 DEMO
const nrf_drv_timer_t mytimer = NRF_DRV_TIMER_INSTANCE(0);
void timer_led_handler(nrf_timer_event_t event_type, void* p_context)
{
switch(event_type)
{
case NRF_TIMER_EVENT_COMPARE0:
//LED翻转
nrf_gpio_pin_toggle(LED_2);
break;
default:break;
}
}
int main(void)
{
uint32_t err_code = NRF_SUCCESS;
uint32_t time_ms=100; //100ms
uint32_t tick;
//配置用于控制LED灯的管脚
nrf_gpio_cfg_output(LED_2);
nrf_gpio_pin_set(LED_2);
//初始化定时器
err_code=nrf_drv_timer_init(&mytimer,NULL,timer_led_handler);
//转化时间
tick=nrf_drv_timer_ms_to_ticks(&mytimer,time_ms);
//配置
nrf_drv_timer_extended_compare(&mytimer,NRF_TIMER_CC_CHANNEL0,tick,NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK,true);
//启动定时器
nrf_drv_timer_enable(&mytimer);
while (true)
{
}
}
参考资料
1 nRF52832 API
2 艾克姆科技资料