本帖最后由 sky86530430 于 2020-10-30 11:42 编辑
我目前做一个项目需要使用TIM8 通道2,3输出两路PWM 20khz 占空比30%的波形,目前情况是波形是有了,但是波形不是连贯的,示波器上是一会有20kz的pwm波形,一会又没有,把时间分辨率调大,发现有跟没有的波形恰好又是一个 30%占空比的波形,STM32通用定时器做PWM我也是做过的,但没用过TIM8做,调了2天了真是要疯!
这是源代码:
/*
******************************************************************************
* Function Name : TIM_PWM_Init
* Description :
*
* Input : None
* Output : None
* Return :
******************************************************************************
*/
static void TIM_PWM_Init (void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
/* PWM IO Init */
/* GPIOC Configuration:TIM8 Channel 2, 3 as alternate function push-pull */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitStructure.GPIO_Pin = BSP_GPIOC_PUMP1_PWM | BSP_GPIOC_PUMP2_PWM;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/* TIM8 clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8, ENABLE);
/* Time base configuration */
TIM_TimeBaseStructure.TIM_Period = 3599; // ʱÖÓÆÀÂÊÊÇ72000000£¬20KHz£¬Ê±ÖÓÎÞÐè·ÖƵ£¬ÉèÖÃΪ3600 - 1
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM8, &TIM_TimeBaseStructure);
/* PWM2 Mode configuration: Channel2 */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OCInitStructure.TIM_Pulse = (3600 * 0.3); // 30%
TIM_OC2Init(TIM8, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM8, TIM_OCPreload_Enable);
/* PWM2 Mode configuration: Channel3 */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OCInitStructure.TIM_Pulse = (3600 * 0.3); // 30%
TIM_OC3Init(TIM8, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM8, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM8, ENABLE);
/* TIM1 Main Output Enable */
TIM_CtrlPWMOutputs(TIM8,ENABLE);
/* TIM8 enable counter */
TIM_Cmd(TIM8, ENABLE);
}
|