STM32 PWM输出配置步骤(自用)

1.使能定时器3和相关IO口时钟
使能定时器3时钟:RCC_APB1PeriphClockCmd();
使能GPIOB时钟:RCC_APB2PeriphClockCmd();

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);//使能TIMER3时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);//使能GPIOB时钟

2.初始化IO口为复用功能输出。函数:GPIO_Init();
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;

	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_5;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_Init(GPIOB,&GPIO_InitStruct);//初始化IO复用功能输出

3.把PB5用作定时器的PWM输出引脚,所以要重映射配置,所以需要开启AFIO时钟。同时设置重映射。
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3, ENABLE);

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);//开启AFIO时钟
	GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3,ENABLE);//部分重映射

4.初始化定时器:ARR,PSC等:TIM_TimeBaseInit();

	TIM_TimeBaseInitStruct.TIM_Prescaler = psc;//预分频
	TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStruct.TIM_Period = arr;//周期
	TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStruct);

5.初始化输出比较参数:TIM_OC2Init();

	TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM2;
	TIM_OCInitStruct.TIM_OutputState=TIM_OutputState_Enable;
	TIM_OCInitStruct.TIM_OCPolarity=TIM_OCPolarity_High;
	TIM_OC2Init(TIM3,&TIM_OCInitStruct);//初始化输出比较参数

6.使能预装载寄存器: TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);

	TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);//使能预装载寄存器

7.使能定时器。TIM_Cmd();

TIM_Cmd(TIM3,ENABLE);//使能定时器

main

 int main(void)
 {	
	 u16 led0pwm = 0;
	 u8 dir = 1;
	delay_init();
	LED_Init();
	TIM_PWM_Init(7199,0);//72000000/7200=10KHz
  while(1)
	{
		delay_ms(10);
		if(dir)led0pwm++;
		else led0pwm--;
		
		if(led0pwm > 300)dir = 0;
		if(led0pwm == 0)dir = 1;
		TIM_SetCompare2(TIM3, led0pwm);
	}
 }

你可能感兴趣的:(STM32,stm32,单片机,arm)