STM32的PWM设置4路相差90度的输出信号

void TIM_Encoder_Config(u16 PPS)//设置编码器的4路相差90度的PWM信号 { double temp = 4000; /* Time Base configuration */ TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; TIM_BDTRInitTypeDef TIM_BDTRInitStructure; temp = temp*72/PPS -1; TIM_TimeBaseStructure.TIM_Period = (u16)temp - 1; //总周期长度 TIM_TimeBaseStructure.TIM_Prescaler = 124; // TIMCLK TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up ; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;//输出比较模式 TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; TIM_OCInitStructure.TIM_Pulse = 0; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High; TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset; TIM_OC1Init(TIM4, &TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable); //TIM4_OC2模块设置(设置2通道相位) TIM_OCInitStructure.TIM_Pulse = (u16)(temp/2-1);//1/4总周期长度 TIM_OC2Init(TIM4, &TIM_OCInitStructure); TIM_OC2PreloadConfig(TIM4, TIM_OCPreload_Enable); //TIM4_OC3模块设置(设置3通道相位) TIM_OCInitStructure.TIM_Pulse = (u16)(temp-1);//1/2总周期长度 TIM_OC3Init(TIM4, &TIM_OCInitStructure); TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable); //TIM4_OC4模块设置(设置4通道相位) TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;//输出极性:TIM输出比较极性高 TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low; TIM_OCInitStructure.TIM_Pulse = (u16)(temp/2-1);//3/4总周期长度 TIM_OC4Init(TIM4, &TIM_OCInitStructure); TIM_OC4PreloadConfig(TIM4, TIM_OCPreload_Enable); //死区设置 TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable; TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Enable; TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_1; TIM_BDTRInitStructure.TIM_DeadTime = 70; //这里调整死区大小0-0xff TIM_BDTRInitStructure.TIM_Break = TIM_Break_Enable; TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_Low; TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable; TIM_BDTRConfig(TIM4, &TIM_BDTRInitStructure); /* TIM4 counter enable */ TIM_Cmd(TIM4, ENABLE); /* TIM4 Main Output Enable */ TIM_CtrlPWMOutputs(TIM4, ENABLE); }

经验分享 程序员 微信小程序 职场和发展