编写初始化代码如下:- void TIM_Init(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
- TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
- TIM_OCInitTypeDef TIM_OCInitStructure;
-
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
- RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB,ENABLE);
-
- GPIO_InitStructure.GPIO_Pin=GPIO_Pin_3;
- GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
- GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
- GPIO_Init(GPIOB,&GPIO_InitStructure);
-
- GPIO_PinAFConfig(GPIOB,GPIO_PinSource3,GPIO_AF_2);
-
- TIM_TimeBaseInitStructure.TIM_ClockDivision = 0;
- TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Down;
- TIM_TimeBaseInitStructure.TIM_Period = 1000-1;
- TIM_TimeBaseInitStructure.TIM_Prescaler = 48-1;
- TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
-
- TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2;
- TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
- TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_Low;
- TIM_OCInitStructure.TIM_Pulse = 0;
- TIM_OC2Init(TIM2,&TIM_OCInitStructure);
- TIM_CtrlPWMOutputs (TIM2,ENABLE);
-
- TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable); //CH2
- TIM_ARRPreloadConfig(TIM2, ENABLE);
-
- TIM_Cmd(TIM2,ENABLE);
- }
然后编写呼吸灯相关代码- i=0;
- while(i+=5)
- {
- TIM_SetCompare2(TIM2,i);
- delay_ms(10);
- if(i>=1000)
- break;
- }
- i=1000;
- while(i-=5)
- {
- TIM_SetCompare2(TIM2,i);
- delay_ms(10);
- if(i<=0)
- break;
- }
- delay_ms(1000);
- delay_ms(1000);
|