本文实例说明:
这里是使用 TIM3_CH2输出 一个频率为50kHz; 占空比为50% 的PWM信号。
1先配置STM32CubeMX 参数,如图:
重点说明:
PWM 频率 = APB1 Timer clocks (MHz) / [(Prescaler+1) * (Counter Period+1)]
APB1 Timer clocks (MHz) :64MHz
Counter Period : 20
Prescaler :设置为64-1 那么此时PWM时钟设置为:
f = 64000000 / 64 /20 = 50KHz
Pulse :设置为10 ,也就是占比为:10/20 = 50%
Fast Mode:如果频率太高可以使能快速模式。可以大大提高PWM反应时间;同时将IO口输出速度调高。
2代码分析:
static void MX_TIM3_Init(void)
{
/* USER CODE BEGIN TIM3_Init 0 */
/* USER CODE END TIM3_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM3_Init 1 */
/* USER CODE END TIM3_Init 1 */
htim3.Instance = TIM3;
htim3.Init.Prescaler = 64-1;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 20-1;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 10;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM3_Init 2 */
HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2); //启动PWM输出函数
__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_2, 10);//这个函数可以设置占空比
/* USER CODE END TIM3_Init 2 */
HAL_TIM_MspPostInit(&htim3);
}
3实验现象: