芯片:STM32F103C8T6
应用管脚:
输出:PA0、PA1
TIM2 CH2通道
实现PA1管脚50HZ(20ms)可调PWM输出,系统TIMx_CNT=8MHZ=8000 000HZ,设置TIMx_PSC=800-1,那么TIMx_ARR=(TIMx_CNT/TIMx_PSC)*定时器时间=(8000000/800)*0.02=200,TIMx_ARR=200-1。
配置界面
TIM2配置
开启NVIC中断配置
程序中增加PWM可调占空比应用函数
/* USER CODE BEGIN 4 */
/**
* @brief 调整PWM占空比
* @param value为占空比 value=50 即占空比为50%
* @retval None
*/
void USER_PWM_SetDutyRatio(TIM_HandleTypeDef *htim,uint32_t Channel,uint8_t value)
{
TIM_OC_InitTypeDef sConfigOC;
uint32_t period=htim->Init.Period+1;
uint32_t pluse=(value * period)/100;
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = pluse;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
HAL_TIM_PWM_ConfigChannel(htim, &sConfigOC, Channel);
HAL_TIM_PWM_Start(htim, Channel);
}
/* USER CODE END 4 */
启动PWM并调整
TIM2 CH2占空比
/* USER CODE BEGIN 2 */
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
USER_PWM_SetDutyRatio(&htim2,TIM_CHANNEL_2,n);
HAL_Delay(20);
n++;
if(n>100)
{
n=0;
}
}
/* USER CODE END 3 */