/*
*****************************************************************************
 *  Brightness control making use of PWM module
 *  Use ILITEK ILI9320 LCD
 *  Hardware TY320T_240320_BO (Rev 2C) stack on PIC24-Eval-B2 Rev A
 *  Brightness control pin EN on LCD module wired to OC2/RD1 pin
 *****************************************************************************
 * FileName:        pwm.c
 * Dependencies:    pwm.h
 * Processor:       PIC24FJ128GA010
 * Compiler:       	MPLAB C30
 * Linker:          MPLAB LINK30
 * Company:         TechToys Company
 * Web presence:	www.TechToys.com.hk
 * Date:			15th Jan 2008
 * Version:			1.0a
******************************************************************************
*/
#include "pwm.h"

void pwmSetBrightness(char intensity){

	int OC2RS_Val;

	switch(intensity)
		{
			case OFF:
					OC2RS_Val=0xFFFF;		//Set 100% Duty Cycle because it is a p-channel mosfet in version 2C
					break;					//of the LCD module
			case FULL:
					OC2RS_Val=0x0000;		//set 0% Duty Cycle
					break;					
			case QUARTER:					//set 75% Duty Cycle for 1/4 brightness
					OC2RS_Val=0x0039;
					break;
			case HALF:						//set 50% Duty Cycle
					OC2RS_Val=0x0026;
					break;
			case THREE_QUARTER:				//Set 25% Duty Cycle
					OC2RS_Val=0x0013;
					break;
			default:
					OC2RS_Val=0x0000;
		};
	OC2RS = OC2RS_Val;
}


void pwmInit(void){
	OC2CON 	= 0x0000;	//Turn off Output Compare 2 (OC2) module to define OC2R
	OC2R	= 0x0026;	//Initialize Compare Register2 with 0x0026
						//If OC2R loaded with 0x0000, OC2 remains low (i.e. full brightness)
						//If OC2R > PR2, th pin OC2 remains high (100% duty cycle), i.e. backlight OFF
	OC2RS	= 0x0000;	//Set duty cycle for full brightness (i.e. set brightness here)
						//it is eq. to set 0% Duty Cycle
	OC2CON 	= 0x2006;	//OCSIDL =1 for OC2 halt in cpu idle
						//TMR2 as the clock source for OC2, and PWM mode on OC2, w/o fault pin enabled
	PR2		= 0x004C;	//set period here : PWM period =[(PR2)+1]*Tcy*(Timer Prescale Value)
	IPC1bits.T2IP  = 1; 	//set Interrupt Priority for Timer 2
	IFS0bits.T2IF  = 0;		//clear Timer 2 Interrupt Flag
	IEC0bits.T2IE  = 1;		//Enable Timer 2 Interrupt
	T2CONbits.TON  = 1;		//Start Timer 2 interrupt
}
