STM32通用定时器PWM库函数操作

GPIO_InitTypeDef GPIO_InitStrue;//GPIO初始化结构体
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitSture;//定时器初始化结构体
	TIM_OCInitTypeDef TIM_OCInitStrue;//PWM初始化结构体
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_TIM1, ENABLE);//使能GPIOA、TIM1时钟
	
	GPIO_InitStrue.GPIO_Pin = GPIO_Pin_8;//pin8
	GPIO_InitStrue.GPIO_Speed = GPIO_Speed_50MHz;//速度
	GPIO_InitStrue.GPIO_Mode = GPIO_Mode_AF_PP;//复用推挽
	GPIO_Init(GPIOA, &GPIO_InitStrue);//初始化GPIOA pin8 50MHZ 复用推挽
	
	TIM_TimeBaseInitSture.TIM_Prescaler = psc;//预分频系数
	TIM_TimeBaseInitSture.TIM_CounterMode = TIM_CounterMode_Up;//向上计数模式
	TIM_TimeBaseInitSture.TIM_Period = arr;//重装载值
	TIM_TimeBaseInitSture.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitSture);//初始化定时器1
	
	TIM_OCInitStrue.TIM_OCMode = TIM_OCMode_PWM2;//PWM2模式
	TIM_OCInitStrue.TIM_OutputState = TIM_OutputState_Enable;//输出模式开启
	TIM_OCInitStrue.TIM_OCPolarity = TIM_OCPolarity_High;//高电平有效
	TIM_OC1Init(TIM1, &TIM_OCInitStrue);//初始化PWM
	
	TIM_CtrlPWMOutputs(TIM1, ENABLE);//主输出使能
	
	TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);//使能输出比较预装载
	
	TIM_ARRPreloadConfig(TIM1, ENABLE);//使能TIMx在ARR上的预装载寄存器
	
	TIM_Cmd(TIM1, ENABLE);//使能定时器1

主函数:

 u16 led0pwmvalue = 0;
	 u8 dir = 1;
	 delay_init();
	 LED_Init();
	 while(1){
		 delay_ms(5);
		 if(dir)	led0pwmvalue++;
		 else	    led0pwmvalue--;
		 if(led0pwmvalue > 300) dir = 0;
		 if(led0pwmvalue == 0)		dir = 1;
		 TIM_SetCompare1(TIM1, led0pwmvalue);
	 }

上一篇:STM32的PWM波动态调频和调占空比


下一篇:[无人机学习]无人机学习概论