Thursday, March 20, 2014

PWM Code:

#if defined(__XC)
    #include <xc.h>         /* XC8 General Include File */
#elif defined(HI_TECH_C)
    #include <htc.h>        /* HiTech General Include File */
#endif

#include <stdint.h>        /* For uint8_t definition */
#include <stdlib.h>

//#fuses NOMCLR,NOPROTECT,NOWDT,INTRC
#pragma config MCLRE=OFF,CP=OFF,WDTE=OFF,FOSC=INTOSCIO
#define _XTAL_FREQ 8000000

void init()
{
    //Configure GPIO Port
    ANSEL =  0b00000000;  //Configure all GPIO pins as digital
    TRISIO = 0b11101100;  //Set GP0, GP1, GP2, GP4 as outputs (0) and the rest as inputs (1)
    WPU = 0x00;           //Disable weak pullups
    //Configuer AD Convertor
    ADCON0 = 0x00;        //AD disabled
    ADRESH = 0x00;        //Init the AD Register
    //Configure Comparator
    CMCON0 = 0xFF;   // Comparator is turned off
    CMCON1 = 0x00;   // Comparator is turned off
    //Interrupt configuration
    //INTCON = 0x00;   //Disable all interrupts
}

void main()
{
 uint8_t db_cnt, sPIR1,i; // ADC_result2;
 init();

 TRISIO = 0b11101100;  //Disable IO2
 PR2 = 0xF5;
 CCP1CON = 0b00111100;
 CCPR1L =  1; // 1,4,16
 sPIR1 = PIR1 & 0b11111101; //Clear TMR2IF
 PIR1 = sPIR1;
 T2CON = 0b00000101;

 while(1)
  {
   for (i=0;i<250;i++)
    {
     if (PIR1bits.TMR2IF == 1)
      {
       TRISIO = 0b11101000;
       PR2 = i;
      }
     __delay_us(2000);
   }
  }
}