/*
* @brief Simple calulate square number.
* @param1 Base number
* @param2 Exponent number
* @retval Number of base^number
* @author: icerol
*/
unsigned long pow(uint base , uint exponent)
{
uint temp = 1;
for(uint i=0; i< exponent; i++)
{
temp *= base;
}
return temp;
}
#define TIM2_CH1 0x01
#define TIM2_CH2 0x02
#define TIM2_CH3 0x04
#define F_MASTER 16000000UL
/*
* @brief Initial timer2 for pwm output.
* @param1 PWM output channal, TIM2_CH1 | TIM2_CH2 | TIM2_CH3
* @param2 PWM putput frequency, Unit: Hz
* @param3-5 PWM duty for CH1-3, range:0-100
* @retval None
* @author: icerol
*/
void timer2_pwm_Init(unsigned char channal, unsigned long hz,unsigned char pwm1, unsigned char pwm2,unsigned char pwm3)
{
unsigned char pscr=0;
double tim2_clk;
for(pscr=0;pscr<0x10;pscr++)
{
tim2_clk = F_MASTER/(pow(2,pscr));
if((tim2_clk/hz)<0xffff)
{
break;
}
}
double basecycle = 1000000000/tim2_clk;//us
double hzcycle=1000000000/hz;
double arr = hzcycle/basecycle;
TIM2_ARRH = (unsigned int)(arr)/256;
TIM2_ARRL = (unsigned int)(arr)%256;
if(channal & TIM2_CH1)
{
TIM2_CCMR1 |= 0x70;
TIM2_CCER1 |= 0x03; //通道1使能,低电平有效,配置为输出
TIM2_CCR1H = ((arr*pwm1)/100)/256;
TIM2_CCR1L = ((arr*pwm1)/100)%256;
}
if(channal & TIM2_CH2)
{
TIM2_CCMR2 |= 0x70;
TIM2_CCER1 |= 0x30; //通道2
TIM2_CCR2H = ((arr*pwm2)/100)/256;
TIM2_CCR2L = ((arr*pwm2)/100)%256;
}
if((channal & TIM2_CH3))
{
TIM2_CCMR3 |= 0x70; //01110000
TIM2_CCER2 |= 0x03; //通道3
TIM2_CCR3H = ((arr*pwm3)/100)/256;
TIM2_CCR3L = ((arr*pwm3)/100)%256;
}
TIM2_PSCR = pscr;
TIM2_CR1 = TIM2_CR1 | 0x01;
CLK_PCKENR1 = 0x20;
}