#include "pwm.h"


void pwm_init(void)
{
	//PWM时钟为系统时钟八分频
	PWM0CON = 0xF2; //P54
	PWM1CON = 0xF2; //P12
	PWM2CON = 0xF2; //P13
	PWM3CON = 0xF2; //P23
	GPIO_OUTPUT(P1, 2, 0);
	GPIO_OUTPUT(P1, 3, 0);
	GPIO_OUTPUT(P2, 3, 0);
  P5CR = 0x10;
	P5ODR = 0x00;
	ALFSEL0 |= 0x60;
	ALFSEL1 |= 0x80;
	
	
}

void pwm_ch(uint8_t ch, uint8_t per, uint8_t duty)
{
	uint16_t dut;
	dut = (uint8_t)(per * ((float)duty / 100));
	switch(ch)
		{
			case 0:
				PWM0P = per;
			  PWM0D = dut;
				break;
			case 1: 
				PWM1P = per;
			  PWM1D = dut;
				break;
			case 2: 
				PWM2P = per;
			  PWM2D = dut;
				break;
			case 3: 	
				PWM3P = per;
			  PWM3D = dut;
				break;
			default:
				break;				
		}
}

/*
fre: 频率 表示 fre kHz,0不改变频率  系统时钟默认2分频2Mhz
ch :PWM通道 0,1,2,3
duty : 占空比 整数 如：10表示占空比10%
*/
void pwm_set(uint16_t fre,uint8_t ch, uint8_t duty)
{
	uint8_t temp;
	uint16_t per;
	if(fre != 0)
	{
		temp = SYSCON & 0xC0;
		switch(temp)
		{
			case 0x80: //2Mhz
				per = (uint8_t)(250000 / fre);
				pwm_ch(ch, per, duty);
				break;
			case 0x00: //333Khz
        per = (uint8_t)(20833 / fre);
				pwm_ch(ch, per, duty);
				break;
			case 0x40: //1Mhz
        per = (uint8_t)(125000 / fre);
				pwm_ch(ch, per, duty);
				break;
			case 0xC0: //4Mhz
				per = (uint8_t)(500000 / fre);
				pwm_ch(ch, per, duty);
				break;

			default:
				break;				
		}
	}
}

void PWM_Test(void)
{
	pwm_init();
  pwm_set(38000, 1, 33);
	while(1);
}
