Bare Metal Code

The functions and code necessary to implement the example discussed are analyzed in this section.

The first step will be to configure the microcontroller to disable the Watchdog Timer and to enable Low-Voltage Programming (LVP).

#pragma config WDTE = OFF /* WDT operating mode->WDT Disabled */
#pragma config LVP = ON /* Low voltage programming enabled, RE3 pin is MCLR */ 

As described in the example functionality, an initialization of peripherals must be added to the project: TMR1, the system clock and the GPIO pin.

The system clock was configured to use the HFINTOSC oscillator with an internal frequency of 32 MHz and the clock divided by 32, so the actual system frequency is 1 MHz. The following function is used:

/* Clock initialization function */
static void CLK_Initialize(void)
{
    /* set HFINTOSC as new oscillator source */
    OSCCON1bits.NOSC = 0x6;

    /* set Clock Div by 32 */
    OSCCON1bits.NDIV = 0x5;      
    
    /* set HFFRQ to 32MHz */
    OSCFRQbits.HFFRQ = 0x6; 
}

The GPIO peripheral was configured to use PINB0 as output for the event triggered by CCP. The following function is used:

/* PPS initialization function */
static void PPS_Initialize(void)
{
    /* Configure RB0 for CCP1 output */
    RB0PPS = 0x05;
}

/* Port initialization function */
static void PORT_Initialize(void)
{
    /* Set RB0 as output */
    TRISBbits.TRISB0 = 0;
}

The TMR1 peripheral was configured as a normal counter. The following function is used:

/* TMR1 initialization function */
static void TMR1_Initialize(void)
{
    /* Set timer Source Clock to FOSC/4 */
    T1CLKbits.CS = 0x1;

    /* Enable timer */
    T1CONbits.ON = 1;
}

The CCP1 peripheral was configured to toggle a GPIO pin when the TMR1 counted value is equal with the CCP value. The following function is used:

/* CCP1 initialization function */
static void CCP1_Initialize(void)
{
    /* Select TMR1 as input for CCP1*/
    CCPTMRSbits.C1TSEL = 0x1;

    /* Set the high value for compare */
    CCPR1H = 0x0F;

    /* Set the low value for compare */
    CCPR1L = 0xFF;

    /* Compare mode with toggle*/
    CCP1CONbits.CCP1MODE = 0x2;

    /* Enable CCP1 */
    CCP1CONbits.EN = 1;             
}
Note: In this example, the event will be strictly handled by the hardware peripheral without any software and load on the core.