2.2 Bare Metal Code
The necessary code and functions to implement the example are analyzed in this section.
The first step is to configure the microcontroller to disable the Watchdog Timer and enable the Master Clear external pin.
#pragma config WDTE = OFF /* disable Watchdog */
#pragma config LVP = ON /* Low voltage programming enabled */
The main clock of the microcontroller must be initialized. The following function initializes the system clock to have as input clock the HFINTOSC oscillator and to run at 1 MHz:
static void CLK_Initialize(void) { /* set HFINTOSC Oscillator */ OSCCON1bits.NOSC = 6; /* set HFFRQ to 1 MHz */ OSCFRQbits.HFFRQ = 0; }
The peripheral initialization must be added to the project. The PORT registers allow the user to configure a pin as input or output, enable the weak pull-up and enable the digital input buffer for the desired pins.
The RE0 pin is configured as output and the RE2 pin is configured as digital input, with weak pull-up enabled. The desired configuration for this example translates to the following code:
static void PORT_Initialize(void)
{
/* Set RE0 (LED) pin as output */
TRISEbits.TRISE0 = 0;
/* Set RE2 (button) pin as input*/
TRISEbits.TRISE2 = 1;
/* Enable weak pull-up for pin RE2 (button) */
WPUEbits.WPUE2 = 1;
/* Enable digital input buffer for pin RE2 (button) */
ANSELEbits.ANSELE2 = 0;
}
0
’ (the button is pressed), the microcontroller will turn on the
LED by driving the output pin low. Otherwise, if the pin value is ‘1
’
(the button is released), the microcontroller will turn off the LED by driving the
output pin high. This translates to the following code:
while (1)
{
if(PORTEbits.RE2) /* Read the input pin value */
{
LATEbits.LATE0 = 1; /* Turn off LED */
}
else
{
LATEbits.LATE0 = 0; /* Turn on LED */
}
}