#include "c8051f300.h"

// Peripheral specific initialization functions,
// Called from the Init_Device() function
void Reset_Sources_Init()
{
    RSTSRC    = 0x02;
}

void PCA_Init()
{
    PCA0MD    &= ~0x40;
    PCA0MD    = 0x04;
    PCA0CPM0  = 0x42;
    PCA0CPL2  = 0x00;
    PCA0MD    |= 0x40;


   // Start PCA counter
    CR = 1;
}

void Timer_Init()
{	TCON      = 0x50;
    TMOD      = 0x12;
    CKCON     = 0x02;
    TH0       = 0x00;
}

void Port_IO_Init()
{   P0MDOUT   = 0x05;
    XBR1      = 0x40;
    XBR2      = 0x40;
}

void Interrupts_Init()
{   IE        = 0x08;
}

// Initialization function for device,
// Call Init_Device() from your main program
void Init_Device(void)
{
    Reset_Sources_Init();
    PCA_Init();
    Timer_Init();
    Port_IO_Init();
    Interrupts_Init();
}


static bit         lamp_state     = 0;
static bit         lamp_up        = 1;
static bit         changed_state  = 1;
static bit         nightlight     = 0;
static unsigned int heldon_time   = 0;
static unsigned int old_heldon_time = 0;
static unsigned int heldoff_time  = 10;
static unsigned int delta_t       = 0;
static unsigned int lamp_bright   = 0;

sbit button_0 = P0^4;
sbit button_1 = P0^3;
sbit led_port = P0^2;



void main (void) 
{
 PCA0MD &= ~0x40; //Turn off watchdog

 Init_Device();
 P0     |= 0x08;  //make sure PB is input mode

 TR0 = 1;         //start timer 0
 TR1 = 1;         //start timer 1
 ET1 = 1;         //timer 1 interrupt
 EA =  1;   
 TF1 = 1;  
 while (1) 
  {  if ((button_1==1) & (heldoff_time=1))   
     {
     if ((changed_state==0) & (delta_t<2)) 
	  {lamp_state=!lamp_state;
	   changed_state=1;
	  }
      else //Button is PRESSED
	  
	   if (button_1==0)
	    {changed_state=0;
        if (heldon_time==1) delta_t=0;
	    old_heldon_time=heldon_time;
	    old_heldon_time++;
        if (delta_t>=2) 
	      {//do lamp brightening
   		    lamp_state=1;
		    if (delta_t==2) lamp_up=1;
            if (lamp_bright==16) lamp_up=0;
		    if (lamp_bright==0) lamp_up=1;
		    if (lamp_up==1) 
		      lamp_bright++;
		     else
		      lamp_bright--; 
            PCA0CPH0 = lamp_bright * 16;
          }
	     while ( (heldon_time<old_heldon_time) & (button_1==0)); 
	     if (button_1==0)
	       delta_t++;	   
	    }//button IS pressed.

     }

  } // end main while loop. 
}   // end main


void timer1_ISR (void) interrupt 3 using 2
{
if (button_1==0)
  {led_port = 0;
   heldon_time++;
   if (heldon_time>0xFFF0) {heldon_time=0xFFF0;}
   heldoff_time=0;}
 else
  {led_port=1;
   heldon_time=0;
   heldoff_time++;
   if (heldoff_time>0xFFF0) {heldoff_time=0xFFF0;}
   }

 if (lamp_state == 1)
   //PWM to last PWM on value- lampbright.
  {PCA0CPM0 |= 0x40;
   led_port= 1;}
 else
  {PCA0CPM0 &= ~0x40;
   led_port=0;}  //PWM to off
 TF1 = 0;
  

}
