论坛元老
- 积分
- 4584
- 金钱
- 4584
- 注册时间
- 2015-1-10
- 在线时间
- 573 小时
|
发表于 2024-10-28 11:14:34
|
显示全部楼层
void TIM9_Config(uint32_t freq, uint8_t duty)
{
TIM_OC_InitTypeDef TIM_OC_InitStructure;
__HAL_RCC_TIM9_CLK_ENABLE();
TIM9_Handler.Instance = TIM9;
uint32_t arr = 0;
uint16_t psc = 0;
do {
arr=(SystemCoreClock/(psc+1))/freq;
if (arr > 65500) {
psc++;
} else {
break;
}
} while(1);
TIM9_Handler.Init.Prescaler = psc;
TIM9_Handler.Init.Period = arr - 1;
TIM9_Handler.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
TIM9_Handler.Init.CounterMode = TIM_COUNTERMODE_UP;
HAL_TIM_Base_Init(&TIM9_Handler);
HAL_TIM_OC_Init(&TIM9_Handler);
if (duty != 0) {
TIM_OC_InitStructure.OCPolarity = TIM_OCPOLARITY_LOW;
} else {
TIM_OC_InitStructure.OCPolarity = TIM_OCPOLARITY_HIGH;
}
TIM_OC_InitStructure.OCMode = TIM_OCMODE_PWM1;
TIM_OC_InitStructure.OCFastMode = TIM_OCFAST_DISABLE;
TIM_OC_InitStructure.Pulse = (uint32_t)(TIM9_Handler.Init.Period + 1)*duty/100 - 1;
HAL_TIM_OC_ConfigChannel(&TIM9_Handler, &TIM_OC_InitStructure, TIM_CHANNEL_2);
HAL_TIM_OC_Start(&TIM9_Handler, TIM_CHANNEL_2);
}
之前写过一个,频率和占空比可调,你参考参考吧 |
|