/*
 * File:   main.c
 * Author: boos
 *
 * Created on July 31, 2019, 11:22 PM
 */

// CONFIG
#pragma config FOSC = INTOSCCLK // Oscillator Selection bits (INTOSC oscillator: CLKOUT function on RA6/OSC2/CLKOUT pin, I/O function on RA7/OSC1/CLKIN)
#pragma config WDTE = ON        // Watchdog Timer Enable bit (WDT enabled)
#pragma config PWRTE = OFF      // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = ON       // RA5/MCLR/VPP Pin Function Select bit (RA5/MCLR/VPP pin function is MCLR)
#pragma config BOREN = ON       // Brown-out Detect Enable bit (BOD enabled)
#pragma config LVP = ON         // Low-Voltage Programming Enable bit (RB4/PGM pin has PGM function, low-voltage programming enabled)
#pragma config CPD = OFF        // Data EE Memory Code Protection bit (Data memory code protection off)
#pragma config CP = OFF         // Flash Program Memory Code Protection bit (Code protection off)

#include <xc.h>

#define _XTAL_FREQ 4000000

void main(void) {

    // PORT RB3 is an output
    TRISB3 = 0;
    
    // start PWM module
    CCP1CON = 0b1100;
    
    // set upper limit of TIMER2 (sets the PWM frequency)
    PR2 = 0xff;

    // set the prescaler of TIMER2 to 1:1 (bits no. 0 and 1)
    // (00 = 1:1, 01 = 1:4, 1x = 1:16)
    // and activate TIMER2 (bit no. 2)
    T2CON = 0b100;
    
    // our duty cycle value
    int DC = 0;
    
    while (1) {
        
        // set the 10-bit duty cycle value
        CCPR1L = DC >> 2;
        CCP1X = DC & 1;
        CCP1Y = (DC >> 1) & 1; 
        
        // increase the brightness by one
        DC += 1;
        if (DC >= 1024) {
            DC = 0;
        }
    
        // wait a bit
        __delay_ms(1);
        
    }
    
    return;
    
}
