stm32 的定时器4产生PWM

利用PB9产生PWM信号


一、引脚初始化

        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

二、定时器初始化

void TIM4_Config(void)
{ 
 // GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_OCInitTypeDef  TIM_OCInitStructure;

	TIM_DeInit(TIM4);
	 // ƵÂÊ30K
	//Õ¼¿Õ±È50%
 // TIM_TimeBaseStructure.TIM_Period = 100-1; 
	//TIM_TimeBaseStructure.TIM_Prescaler =24-1;
	
	 // ƵÂÊ20K
	//Õ¼¿Õ±È50%
//	TIM_TimeBaseStructure.TIM_Period = 100-1; 
//	TIM_TimeBaseStructure.TIM_Prescaler =36-1;
	
	// ƵÂÊ10K
	//Õ¼¿Õ±È50%
	//TIM_TimeBaseStructure.TIM_Period = 100-1; 
	//TIM_TimeBaseStructure.TIM_Prescaler =72-1;
	
	// ƵÂÊ1K

	TIM_TimeBaseStructure.TIM_Period = 1000-1; 
	TIM_TimeBaseStructure.TIM_Prescaler =72-1;
	
	TIM_TimeBaseStructure.TIM_ClockDivision = 0;

	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

	TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);


	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;

	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;

	TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Disable;


	//TIM_OCInitStructure.TIM_Pulse = 100;
	TIM_OCInitStructure.TIM_Pulse = Optical_Source_Duty;


//	
//	TIM_OC3Init(TIM4, &TIM_OCInitStructure);

//	TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable);
	TIM_OC4Init(TIM4, &TIM_OCInitStructure);

	TIM_OC4PreloadConfig(TIM4, TIM_OCPreload_Enable);

	TIM_CtrlPWMOutputs(TIM4,ENABLE);

	TIM_ARRPreloadConfig(TIM4, ENABLE);

	TIM_Cmd(TIM4, ENABLE);


}

你可能感兴趣的:(STM32)