我使用的是STM32的HAL库,STM32F103ZET6,主频为72MHz。这里使用的定时器是TIM3。定时器的预分频系数我设置为了72,即定时器以1MHz运作,即计一个数要用1us。在使用定时器实现微秒延时函数时,我在调试时发现,我想延时1000us时,实际上延时了7000us左右,为什么会这样呢?
//TIM3初始化
TIM_HandleTypeDef htim3;
void MX_TIM3_Init(void){
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
htim3.Instance = TIM3;
htim3.Init.Prescaler = 71;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 65535;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim3) != HAL_OK){
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK){
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK){
Error_Handler();
}
}
//TIM3 msp初始化
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle){
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(tim_baseHandle->Instance == TIM3){
__HAL_RCC_TIM3_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
HAL_NVIC_SetPriority(TIM3_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(TIM3_IRQn);
}
}
//微秒延时函数
void HAL_Delay_us(uint16_t us){
__HAL_TIM_SET_COUNTER(&htim3, 0); //设置计数器的值为0
__HAL_TIM_ENABLE(&htim3); //使能TIM3
while (__HAL_TIM_GET_COUNTER(&htim3) < us);
__HAL_TIM_DISABLE(&htim3); //失能TIM3
}
|