//配置时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO|RCC_APB2Periph_TIM1,ENABLE); //设置IO为复用输出 GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 ; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); //定时器1配置 void TIM_Configuration(void) { TIM1_TimeBaseInitTypeDef TIM1_BaseInitStructure; TIM1_OCInitTypeDef TIM1_OCInitStructure; TIM1_BDTRInitTypeDef TIM1_BDTRInitStructure; //TIM1基本计数器设置(设置PWM频率) //频率=TIM1_CLK/(ARR+1) TIM1_BaseInitStructure.TIM1_Period = 1000-1; TIM1_BaseInitStructure.TIM1_Prescaler = 72-1; TIM1_BaseInitStructure.TIM1_ClockDivision = 0; TIM1_BaseInitStructure.TIM1_CounterMode = TIM1_CounterMode_Up; TIM1_BaseInitStructure.TIM1_RepetitionCounter = 0; TIM1_TimeBaseInit(&TIM1_BaseInitStructure); //启用ARR的影子寄存器(直到产生更新事件才更改设置) TIM1_ARRPreloadConfig(ENABLE); //TIM1_OC1模块设置(设置1通道占空比) TIM1_OCInitStructure.TIM1_OCMode = TIM1_OCMode_PWM1; TIM1_OCInitStructure.TIM1_OutputState = TIM1_OutputState_Enable; TIM1_OCInitStructure.TIM1_OutputNState = TIM1_OutputNState_Enable; TIM1_OCInitStructure.TIM1_OCPolarity = TIM1_OCPolarity_High; TIM1_OCInitStructure.TIM1_OCNPolarity = TIM1_OCNPolarity_High; TIM1_OCInitStructure.TIM1_Pulse = 120; TIM1_OC1Init(&TIM1_OCInitStructure); //启用CCR1寄存器的影子寄存器(直到产生更新事件才更改设置) TIM1_OC1PreloadConfig(TIM1_OCPreload_Enable); //TIM2_OC2模块设置(设置2通道占空比) TIM1_OCInitStructure.TIM1_OutputState = TIM1_OutputState_Enable; TIM1_OCInitStructure.TIM1_OutputNState = TIM1_OutputNState_Enable; TIM1_OCInitStructure.TIM1_Pulse = 680; TIM1_OC2Init(&TIM1_OCInitStructure); //启用CCR2寄存器的影子寄存器(直到产生更新事件才更改设置) TIM1_OC2PreloadConfig(TIM1_OCPreload_Enable); //死区设置 TIM1_BDTRInitStructure.TIM1_OSSRState = TIM1_OSSRState_Enable; TIM1_BDTRInitStructure.TIM1_OSSIState = TIM1_OSSIState_Enable; TIM1_BDTRInitStructure.TIM1_LOCKLevel = TIM1_LOCKLevel_OFF; TIM1_BDTRInitStructure.TIM1_DeadTime = 0x90; //这里调整死区大小0-0xff TIM1_BDTRInitStructure.TIM1_Break = TIM1_Break_Disable; TIM1_BDTRInitStructure.TIM1_BreakPolarity = TIM1_BreakPolarity_High; TIM1_BDTRInitStructure.TIM1_AutomaticOutput = TIM1_AutomaticOutput_Enable; TIM1_BDTRConfig(&TIM1_BDTRInitStructure); //TIM1开启 TIM1_Cmd(ENABLE); //TIM1_OC通道输出PWM(一定要加) TIM1_CtrlPWMOutputs(ENABLE); }