注:STM32F407VGT6 with STM32F4 DSP and standard peripherals library v1.8.0
以下内容以TIM9为例进行。
pwm.c
内容:
void TIM9_PWM_Init(u32 arr,u32 psc) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; TIM_OCInitTypeDef TIM_OCInitStructure; //1、使能GPIO和TIM的时钟,切记在GPIO初始化时将相应引脚配置为复位选择功能输出 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM9,ENABLE); GPIO_PinAFConfig(GPIOE,GPIO_PinSource5,GPIO_AF_TIM9); GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5; GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF; //将PE5(TIM9的输出通道CH1)配置为复位选择功能输出 GPIO_InitStructure.GPIO_OType=GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed=GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP; GPIO_Init(GPIOE,&GPIO_InitStructure); //2、初始化TIM9,配置TIM9的ARR、PSC等参数 TIM_TimeBaseInitStructure.TIM_Prescaler=psc; TIM_TimeBaseInitStructure.TIM_Period=arr; TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM9,&TIM_TimeBaseInitStructure); //3、配置TIM19_CH1为PWM模式,使能TIM9的CH1输出 TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_Low; TIM_OC1Init(TIM9,&TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM9,TIM_OCPreload_Enable); TIM_ARRPreloadConfig(TIM9,ENABLE); //4、使能TIM9 TIM_Cmd(TIM9,ENABLE); }
main.c
内容:
int main(void) { u16 led0pwmval=0; u8 dir=1; delay_init(168); TIM9_PWM_Init(500-1,84-1); while(1) { delay_ms(20); if(dir) led0pwmval++; else led0pwmval--; if(led0pwmval>300) dir=0; if(led0pwmval==0) dir=1; //5、修改TIM9_CCR1来控制占空比 TIM_SetCompare1(TIM9,led0pwmval); } }
中断时间:Tout=((ARR+1)*(PSC+1))/Tclk
其中:
·ARR为自动重载值
·PSC为分频系数
·Tclk为定时器的时钟频率
又有:除非APB1的分频系数是1,否则通用定时器的时钟等于APB1时钟的2倍。
通常调用SystemInit函数情况下:
·SYSCLK=168MHz
·AHB时钟=168MHz
·APB1时钟=42MHz
·APB1的分频系数=AHB/APB1时钟=4
·所以,通用定时器时钟CK_INT=2*42M=84M
若定时500ms,可以如此设置:
Tout=((5000)*(8400))/84
这里定时器定时时长 500ms是这样计算出来的,定时器的时钟为 84MHz,分频系数PSC为8400(为自己设定值),
所以分频后的计数频率为84MHz/8400=10KHz,然后计数到5000,所以时长为 5000/10000=0.5s,
也就是500ms。