本人采用Cube 进行的STM32库函数编程,PWM波的输出配置以及代码如下所示:(经过实际实验证明非常好用)
以下为定时器PWM输出函数,注意:使用时一定要把原来输出函数注释掉。
注释代码如下:
// sConfigOC.OCMode = TIM_OCMODE_PWM1;
// sConfigOC.Pulse = 0;
// sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
// sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
// if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
// {
// _Error_Handler(FILE, LINE);
// }
// if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
// {
// _Error_Handler(FILE, LINE);
// }
// if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
// {
// _Error_Handler(FILE, LINE);
// }
// if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
// {
// _Error_Handler(FILE, LINE);
// }
void PWM_Change_Duty(float x,float y,float z,float w)
{
TIM_OC_InitTypeDef sConfigOC;
sConfigOC.OCMode = TIM_OCMODE_PWM1;//pwm输出模式配置
sConfigOC.Pulse = x;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
//pwm输出停止函数
if(HAL_TIM_PWM_Stop(&htim4,TIM_CHANNEL_1) != HAL_OK)
{
_Error_Handler(FILE, LINE);//错误等待函数
}
//pwm输出配置函数
if(HAL_TIM_PWM_ConfigChannel(&htim4,&sConfigOC,TIM_CHANNEL_1) != HAL_OK)
{
_Error_Handler(FILE,LINE);
}
//pwm输出开始函数
if(HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_1)!= HAL_OK)
{
_Error_Handler(FILE,LINE);
}
sConfigOC.Pulse = y;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
//pwm输出停止函数
if(HAL_TIM_PWM_Stop(&htim4,TIM_CHANNEL_2) != HAL_OK)
{
_Error_Handler(FILE, LINE);//错误等待函数
}
//pwm输出配置函数
if(HAL_TIM_PWM_ConfigChannel(&htim4,&sConfigOC,TIM_CHANNEL_2) != HAL_OK)
{
_Error_Handler(FILE,LINE);
}
//pwm输出开始函数
if(HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_2)!= HAL_OK)
{
_Error_Handler(FILE,LINE);
}
sConfigOC.Pulse = z;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
//pwm输出停止函数
if(HAL_TIM_PWM_Stop(&htim4,TIM_CHANNEL_3) != HAL_OK)
{
_Error_Handler(FILE, LINE);//错误等待函数
}
//pwm输出配置函数
if(HAL_TIM_PWM_ConfigChannel(&htim4,&sConfigOC,TIM_CHANNEL_3) != HAL_OK)
{
_Error_Handler(FILE,LINE);
}
//pwm输出开始函数
if(HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_3)!= HAL_OK)
{
_Error_Handler(FILE,LINE);
}
sConfigOC.Pulse = w;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
//pwm输出停止函数
if(HAL_TIM_PWM_Stop(&htim4,TIM_CHANNEL_4) != HAL_OK)
{
_Error_Handler(FILE, LINE);//错误等待函数
}
//pwm输出配置函数
if(HAL_TIM_PWM_ConfigChannel(&htim4,&sConfigOC,TIM_CHANNEL_4) != HAL_OK)
{
_Error_Handler(FILE,LINE);
}
//pwm输出开始函数
if(HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_4)!= HAL_OK)
{
_Error_Handler(FILE,LINE);
}
}