高级定时器TIM1的通道4控制led灯组作为呼吸灯代码实现

使用GPIOE,高级定时器TIM1的通道4控制D4作为呼吸灯。

pwm.c

#include 
#include 
 
void timer1_pwm_init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
	TIM_OCInitTypeDef TIM_OCInitStruct;
	
	//1.开启GPIOE和TIM1时钟
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
	
	//2.初始化PE14为复用功能
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;//复用模式
	GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;//推挽输出
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;//高速
	GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;//无上下拉
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_14;//PE14
	GPIO_Init(GPIOF,&GPIO_InitStruct);
	
	//3.将PE14复用映射到TIM1
	GPIO_PinAFConfig(GPIOE,GPIO_PinSource14,GPIO_AF_TIM1);
	
	//4.初始化定时器1 168M / 168 = 1MHz 1M ------ 1000 ----- 1ms
	TIM_TimeBaseInitStruct.TIM_Prescaler = 168-1;//预分频系数
	TIM_TimeBaseInitStruct.TIM_Period = 1000-1;//初始计数值
	TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Down;//向下计数
	TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;//时钟因子
	TIM_TimeBaseInit(TIM1,&TIM_TimeBaseInitStruct);
	
	//5.PWM初始化
	TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;//PWM模式1
	TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_Low;//低电平有效
	TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;//使能
	TIM_OCInitStruct.TIM_Pulse = 800;//比较计数值
	TIM_OC4Init(TIM14,&TIM_OCInitStruct);
	
	//6.使能PWM的预装载和重装载功能
	TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable);
	TIM_ARRPreloadConfig(TIM1, ENABLE);
	
	//7.使能定时器1
	TIM_Cmd(TIM1,ENABLE);
    TIM_CtrlPWMOutputs(TIM1,ENABLE);
}

main.c

#include 
#include 
 
int main()
{	
	u32 comp = 0;
	
	//1.中断优先级分组 2:2
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	//初始化
	//led_init();
	//key_init();
	beep_init();
	exti_init();
	mq2_init();
	delay_init();
	//timer2_init();
	//timer10_init();
	timer14_pwm_init();
    timer1_pwm_init();
	
	//D1为呼吸灯
	while(1){
		//1s从最暗到最亮
		while(comp<1000){
            TIM_SetCompare1(TIM14,comp);
			TIM_SetCompare1(TIM4,comp);
			comp++;
			delay_ms(1);
		}
		
		//1s从最亮到最暗
		while(comp>0){
			TIM_SetCompare1(TIM14,comp);
            TIM_SetCompare1(TIM4,comp);
			comp--;
			delay_ms(1);
		}
		
		delay_ms(200);
	}
	
}

其他模块函数的实现看其他章

PWM具体内容看:第六篇,STM32脉冲宽度调制(PWM)编程_stm32 pwm-CSDN博客

你可能感兴趣的:(STM32编程,单片机,嵌入式硬件)