stm32 基于TIM1定时器的PWM输出

时间:2024-10-08 07:03:06
void PWM_TIM1(uint16_t arr,uint16_t psc)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);	//定时器TIM1时钟使能
    TIM_DeInit(TIM1);
    
   //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
	 TIM_TimeBaseStructure.TIM_Period =arr;		
	//设置用来作为TIMx时钟频率出书的预分频值
	 TIM_TimeBaseStructure.TIM_Prescaler =psc;				
	//设置时钟分割
	 TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	//设置计数模式	
	 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
	 //初始化参数
	 TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);			   
     
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_2);   //TIM1channel2
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_2);  //TIM1channel3
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA,ENABLE);
//PA9
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; 
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; 
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; 
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; 
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; 
    GPIO_Init(GPIOA, &GPIO_InitStructure); 

//PA10
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; 
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; 
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; 
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; 
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; 
    GPIO_Init(GPIOA, &GPIO_InitStructure); 
  
     
    //TIM1的channel2	 
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; 
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; 
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; 
    TIM_OC2Init(TIM1, &TIM_OCInitStructure);  

      //TIM1的channel3
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; 
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; 
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; 
    TIM_OC3Init(TIM1, &TIM_OCInitStructure);
    
    TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable);  
 	TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);      
 
	 TIM_Cmd(TIM1, ENABLE);  //使能TIM1


}



int main()
{
        PWM_TIM1(999,1);//频率为:48MHZ/(999+1)/(1+1)=24KHZ
        TIM_SetCompare2(TIM1,499);  //占空比为50%方波
        PWM_TIM1(399,1);//频率为:48MHZ/(399+1)/(1+1)=
        TIM_SetCompare3(TIM1,199);  //占空比为50%方波



}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68