stm32 基于TIM1定时器的PWM输出

  • Post author:
  • Post category:其他


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%方波



}



版权声明:本文为MyLovelyJay原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。