前言
使用通用定时器2作为芯片时基。
实现
启动步骤:
- 打开外设时钟;
- 配置定时器参数;
- 开启中断;
- 开启定时器;
/* main.c */
void TIM2_Init( void )
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure = {0};
// 打开定时器外设的时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
// 配置定时器参数:分频和计数
TIM_TimeBaseStructure.TIM_Period = SystemCoreClock / 10000 - 1;
TIM_TimeBaseStructure.TIM_Prescaler = 10 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Down;
TIM_TimeBaseInit( TIM2, &TIM_TimeBaseStructure );
// 清空一次标志
TIM_ClearFlag( TIM2, TIM_FLAG_Update );
// 使能中断标志
TIM_ITConfig( TIM2, TIM_IT_Update, ENABLE );
// 使能中断
NVIC_SetPriority( TIM2_IRQn, 15 );
NVIC_EnableIRQ( TIM2_IRQn );
// 启动定时器
TIM_Cmd( TIM2, ENABLE );
}
注意:TIM_Period 和 TIM_Prescaler 都是 16bits,赋值不能超过 UINT16_MAX。
中断配置
volatile uint32_t uwtick = 0;
void TIM2_IRQHandler( void )__attribute__((interrupt("WCH-Interrupt-fast")));
void TIM2_IRQHandler( void )
{
TIM_ClearFlag(TIM2, TIM_IT_Update);
uwtick++;
}
应用配置
uint32_t HAL_GetTick(void)
{
return uwtick;
}
void HAL_Delay(uint32_t Delay)
{
uint32_t tickstart = HAL_GetTick();
while ((HAL_GetTick() - tickstart) < (Delay - 1))
{
}
}