void TIM4_Init(u16 arr,u16 psc) { GPIO_InitTypeDef GPIO_Initstructure; TIM_TimeBaseInitTypeDef TIM_TimeBasestructure; TIM_ocInitTypeDef TIM_OCInitStructure; //TIM4/GPIOA/AFIO CLK enable RCC_APB1PeriphclockCmd (RCC_APBlPeriph_TIM4,ENABLE); Rcc_APB2PeriphclockCmd(Rcc_APB2Periph_GPIOB , ENABLE); Rcc_APB2PeriphClockCmd (RCC_APB2Periph_AFIO ,ENABLE); //set PB6(TIM4_CHl) PB7(TIM4_CH2) as AF output mode for PRM output GPIO_Initstructure.GPIO_Pin = GPIO_Pin_6 l GPIO_Pin_7; GPIO_Initstructure.GPIO_Mode = GPIo_Mode_AF_PP; GPIO_Initstructure.GPIo_Speed = GPIo_Speed_5OMHz; GPIO_Init(GPIOB,&GPIO_Initstructure); //TIM4 base config TIM_TimeBasestructure.TIM_Period = arr; TIM_TimeBasestructure.TIM_Prescaler = psc; TIM_TimeBasestructure.TIM_C1ockDivision = 0; TIM_TimeBasestructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit (TIM4,&TIM_TimeBasestructure) ; //PWM of TIM4_CHl config TIM_OCInitstructure.TIM_OCMode = TIM_OcMode_PWM1; TIM_OCInitstructure.TIM_Outputstate = TIM_Outputstate_Enable; TIM_OcInitstructure.TIM_Pulse = 0; TIM_OCInitstructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC1Init (TIM4,&TIM_OCInitStructure) ; TIM_OClpreloadConfig(TIM4,TIM_OCPreload_Enable); // PWM of TIM4_CH2 config TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWMl; TIM_OCInitstructure.TIM_Outputstate = TIM_Outputstate_Enable; TIM_OCInitStructure.TIM_Pulse =0; TIM_OCInitstructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC2Init (TIM4,&TIM_OCInitStructure) ; TIM_OC2PreloadConfig(TIM4,TIM_OCPreload_Enable) ; //TIM4 preload enable TIM_ARRPreloadconfig (TIM4,ENABLE); //MOE enable for advanced TIMl or TIM8 TIM_Ctr1PWMOutputs (TIM4,ENABLE); //TIM4 enable TIM_Cmd (TIM4,ENABLE);
时间: 2023-09-11 20:09:43 浏览: 226
TIM_test.rar_STM32 TIM_STM32 定时器_TIM_Test
这是一段STM32的代码,用于初始化TIM4定时器和PWM输出。其中,通过GPIO_InitTypeDef结构体初始化GPIOB的PB6和PB7引脚,将它们设置为复用推挽输出模式(AF_PP)。通过TIM_TimeBaseInitTypeDef结构体初始化TIM4的时基参数,包括周期(arr)、预分频器(psc)、时钟分频等。接下来通过TIM_ocInitTypeDef结构体初始化TIM4的PWM输出参数,包括输出模式(TIM_OcMode_PWM1)、输出使能(TIM_Outputstate_Enable)、PWM脉宽(TIM_Pulse)、极性(TIM_OCPolarity_High)等。最后通过TIM_Cmd函数使能TIM4定时器,并通过TIM_Ctr1PWMOutputs函数使能定时器的PWM输出。
阅读全文