stm32f103 pwm学习

void PWM_Init(u32 Freq, u32 Duty_Cycle)
{		
	//TIM5 counter clock
	uwPeriodValue = (uint32_t) ((SystemCoreClock / 2 / Freq) - 1);	
	PWMHandle.Instance = TIM5;    //TIM5_CH4²úÉúPWM
	PWMHandle.Init.Prescaler     = 0;
	PWMHandle.Init.Period        = uwPeriodValue;
	PWMHandle.Init.ClockDivision = 0;
	PWMHandle.Init.CounterMode   = TIM_COUNTERMODE_UP;
	PWMHandle.Init.RepetitionCounter = 0;
	
	if(HAL_TIM_PWM_Init(&PWMHandle) != HAL_OK)
	{
		while(1);
	}

	sConfig.OCMode     = TIM_OCMODE_PWM1;        //PWM1ģʽ
	sConfig.OCPolarity = TIM_OCPOLARITY_LOW;     //Êä³ö¼«ÐԵ͵çƽ
	sConfig.OCFastMode = TIM_OCFAST_DISABLE;     //Êä³ö±È½Ï¿ìËÙʹÄܽûÖ¹
	sConfig.OCNPolarity  = TIM_OCNPOLARITY_HIGH;
	sConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET;
	sConfig.OCIdleState  = TIM_OCIDLESTATE_SET;

	sConfig.Pulse = (Duty_Cycle * (uwPeriodValue - 1)) / 100;     //ÉèÖÃÕ¼¿Õ±È
	
	if(HAL_TIM_PWM_ConfigChannel(&PWMHandle, &sConfig, TIM_CHANNEL_4) != HAL_OK)
	{
		while(1);
	}

	if(HAL_TIM_PWM_Start(&PWMHandle, TIM_CHANNEL_4) != HAL_OK)  //PWMÆô¶¯
	{
		while(1);
	}
}

main.c中

PWM_Init(10000,duty);   //10KHz
10000表示频率。
duty表示占空比。

duty等于50%时,频率为10000,那么高电平为0.05ms,低电平为0.05ms。
那么就要设置周期寄存器的时间为0.1ms。
如果原来pwm 的时钟频率是SystemCoreClock / 2 ,那么数多少次,可以占用0.1ms?
SystemCoreClock / 2/10000
那么如何设置值呢?  SystemCoreClock / 2/10000-1
uwPeriodValue = (uint32_t) ((SystemCoreClock / 2 / Freq) - 1);	
设置比较寄存器
sConfig.Pulse = (Duty_Cycle * (uwPeriodValue - 1)) / 100; 

你可能感兴趣的:(stm32f746ng,例程学习)