以timer3为例,周期1KHz,1ms
void time3_init(void) { TIM_TimeBaseInitTypeDef TIM_INIT; NVIC_InitTypeDef NVIC_INIT; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); // TIM_Period =(时钟频率 / 周期) - 1 TIM_INIT.TIM_Period = (42000000 / 1000) - 1; TIM_INIT.TIM_Prescaler = 0; TIM_INIT.TIM_CounterMode = TIM_CounterMode_Up; TIM_INIT.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInit(TIM3,&TIM_INIT); TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); NVIC_INIT.NVIC_IRQChannel=TIM3_IRQn; NVIC_INIT.NVIC_IRQChannelPreemptionPriority=1; NVIC_INIT.NVIC_IRQChannelSubPriority=1; NVIC_INIT.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&NVIC_INIT); TIM_Cmd(TIM3,ENABLE); } void TIM3_IRQHandler(void) { if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET) //溢出中断 { LED5=!LED5;//led5 } TIM_ClearITPendingBit(TIM3,TIM_IT_Update); //清除中断标志位 }
PWM
void pwm12_ch1_init(u32 arr,u32 psc) { GPIO_InitTypeDef GPIO_init; TIM_TimeBaseInitTypeDef TIM_INIT; TIM_OCInitTypeDef timoc_init; //使能相应时钟 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM12,ENABLE); GPIO_PinAFConfig(GPIOB,GPIO_PinSource14,GPIO_AF_TIM12); //初始化GPIO参数 GPIO_init.GPIO_Mode=GPIO_Mode_AF; GPIO_init.GPIO_Pin=GPIO_Pin_14; GPIO_init.GPIO_OType=GPIO_OType_PP; GPIO_init.GPIO_PuPd=GPIO_PuPd_DOWN; GPIO_init.GPIO_Speed=GPIO_Speed_100MHz; GPIO_Init(GPIOB,&GPIO_init); //位置在stm32f4xx.gpio.h //设置timer12的ARR和PSC参数,用于控制PWM的周期 TIM_INIT.TIM_Period=arr; TIM_INIT.TIM_Prescaler=psc; TIM_INIT.TIM_CounterMode=TIM_CounterMode_Up; TIM_INIT.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM12,&TIM_INIT); //设置PWM通道 timoc_init.TIM_OCMode=TIM_OCMode_PWM1; timoc_init.TIM_OutputState=TIM_OutputState_Enable; timoc_init.TIM_OCPolarity=TIM_OCPolarity_High;//TIM_OCPolarity_Low; TIM_OC1Init(TIM12,&timoc_init); //使能预装载寄存器 TIM_OC1PreloadConfig(TIM12,TIM_OCPreload_Enable); //使能ARPE TIM_ARRPreloadConfig(TIM12,ENABLE); TIM_Cmd(TIM12,ENABLE); }
来源:https://www.cnblogs.com/longxi/p/12031407.html