stm32可以使用定时器输出PWM,每一个定时器都有对应的通道,下面是使用hal库产生PWM的步骤:
1、配置系统时钟
2、选择定时器及对应的通道
3、配置定时器及通道
4、业务代码
(1)启动PWM:HAL库里面只有这么一个函数知道调用了这个函数就可以产生PWM
/**
* @brief Starts the PWM signal generation.
* @param htim TIM handle
* @param Channel TIM Channels to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @arg TIM_CHANNEL_4: TIM Channel 4 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
/* Enable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
{
/* Enable the main output */
__HAL_TIM_MOE_ENABLE(htim);
}
/* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
另外像CH1N、CH2N、CH3N、CH4N这种互补通道,在生成工程之后还要修改其里面的一个函数:
TIM_OCx_SetConfig(); //(x = 1, 2, 3, 4)
把那一行换成
tmpccer |= TIM_CCER_CC1NE;
(2)设置占空比的函数(其实是一个宏):
__HAL_TIM_SET_COMPARE(__HANDLE__, __CHANNEL__, __COMPARE__)
如:
__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_2, 80); //设置TIM_CHANNEL_2N占空比为80
__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_3, 50); //设置TIM_CHANNEL_3N占空比为60
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_2); //开始
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3);