/*
 * pwm.c
 *
 * Created: 04/06/2018 13:45:02
 *  Author: Ledo
 */ 
#include "asf.h"


//Global Variables
pwm_channel_t pwmChannel0;

//Initialize MCU Peripherals
void Pwm_init(void)
{

	
	// disable the PIO (peripheral controls the pin)
	PIOD->PIO_PDR = PIO_PDR_P20 |   PIO_PDR_P24;
	// select alternate function A (PWML0) for pin PD20 and PD24
	PIOD->PIO_ABCDSR[0] &= ~(PIO_ABCDSR_P20 | PIO_ABCDSR_P24);
	PIOD->PIO_ABCDSR[1] &= ~(PIO_ABCDSR_P20 | PIO_ABCDSR_P24);
	// Enable the PWM peripheral from the Power Manger
	PMC->PMC_PCER1 = (1 << (ID_PWM - 32));

	// PWM Channel 0
	// Select the Clock to run at the MCK/2 (60MHz)
	PWM->PWM_CH_NUM[0].PWM_CMR = PWM_CMR_CPRE_MCK_DIV_2;
	// select the period
	PWM->PWM_CH_NUM[0].PWM_CPRD = 2000;
	// select the duty cycle
	PWM->PWM_CH_NUM[0].PWM_CDTY = 1000;

	// PWM Channel 1
	// Select the Clock to run at the MCK/4 (30MHz)
	PWM->PWM_CH_NUM[1].PWM_CMR = PWM_CMR_CPRE_MCK_DIV_4;
	// select the period
	PWM->PWM_CH_NUM[1].PWM_CPRD = 2000;
	// select the duty cycle
	PWM->PWM_CH_NUM[1].PWM_CDTY = 1000;
	
	PWM->PWM_CH_NUM[0].PWM_CMR |= (1<<16);
	PWM->PWM_CH_NUM[0].PWM_DT = 0 | (0<<16);//4095 | (4095<<16);
	//PWM->PWM_CH_NUM[0].PWM_DTUPD = 65000 | (65000<<16);

	// enable the PWM channels
	PWM->PWM_ENA = PWM_ENA_CHID0 ;//| PWM_ENA_CHID1;
	
	
}


void pwm_update(uint16_t period, uint16_t duty)
{
	PWM->PWM_CH_NUM[0].PWM_CPRDUPD = period;
	PWM->PWM_CH_NUM[0].PWM_CDTYUPD = duty;
	//PWM->PWM_CH_NUM[0].PWM_DTUPD = dt | (dt << 16);
}