不磨叽,简单单直接上代码
因为关于PWM的寄存器讲解一大把,这边直接上代码,新手copy后就能用。
这边用的TIM1的CH3,对应的GPIO是PE13(这个口需要做管脚复用哦)
单片机时钟配置的是72M,那么,PWM频率:1Khz
// 1.配置GPIO
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE , ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOE,&GPIO_InitStructure);
GPIO_PinRemapConfig(GPIO_FullRemap_TIM1, ENABLE);
// 2.打开TIM1的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
//3.配置TIM1的基础时钟
//(1+TIM_Prescaler )/72M)*(1+TIM_Period )
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_DeInit(TIM1);
//TIMER1 作为PWM输出 1khz
TIM_TimeBaseStructure.TIM_Period = 1000-1;
TIM_TimeBaseStructure.TIM_Prescaler = 72-1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
//4.配置pwm
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCStructInit(&TIM_OCInitStructure);
//TIM1_OCx模块设置(设置1通道占空比)
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//TIM脉冲宽度调制模式1
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性 低
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High; //互补输出极性 高
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; //在空闲时输出 高
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Reset; //在空闲时互补输出 低
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //PWM输出使能
TIM_OCInitStructure.TIM_Pulse = 500;//待装入捕获比较寄存器的脉冲值(0~1000,这里500就是占空比50%)
TIM_OC3Init(TIM1, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);
//5.输出
TIM_ARRPreloadConfig(TIM1, ENABLE);
TIM_Cmd(TIM1, ENABLE);//TIM1开启
TIM_CtrlPWMOutputs(TIM1, ENABLE);