Datasheet

PICkit™ 3 Debug Express Lessons
© 2009 Microchip Technology Inc. DS41370C-page 17
FIGURE 3-8: LESSON 1 “HELLO LED” SOURCE CODE
When this code is built, programmed into the PIC18F45K20 microcontroller and
executed, it will turn on the LED connected to I/O pin RD7 by driving the pin high. Let’s
discuss the elements of the code that makes this happen:
/** C O N F I G U R A T I O N B I T S ******************************/
#pragma config FOSC = INTIO67
#pragma config WDTEN = OFF, LVP = OFF
/** I N C L U D E S **************************************************/
#include "p18f45K20.h"
/** D E C L A R A T I O N S *******************************************/
void main (void)
{
TRISD = 0b01111111;// PORTD bit 7 to output (0); bits 6:0 are inputs (1)
LATDbits.LATD7 = 1;// Set LAT register bit 7 to turn on LED
while (1)
;
}
#pragma config Pragma is a directive that has meaning for a specific compiler.
It is used in MPLAB C with attributes to convey
implementation-dependent information to the compiler. Here it
is used with the config directive, which defines the states of
the PIC18FXXXX Configuration bits. This will be discussed in
more detail in Lesson 2.
#include The p18f45k20.h file is included as this device-specific
header file contains definitions for the variables used to
access the Special Function Registers (SFRs) of the
microcontroller. Some useful macros such as Nop() and
ClrWdt() are also defined in this header.
TRISD This variable is used to access the SFR of the same name,
and is defined in the included microcontroller header file
p18f45k20.h. The TRIS (tri-state) registers are used to set
the directions of the pins in the associated I/O port, in this
case pins RD0 to RD7. A TRISD bit value of ‘0’ sets the pin to
an output. A value of ‘1’ sets a pin to be an input. With the
binary value of 0b01111111 we set RD7 to an output and
RD6-RD0 to inputs.
LATDbits.LATD7 The LATDbits struct is also defined in p18f45k20.h and
gives access to the individual bits in the LATD SFR. (There is
also a TRISDbits struct for accessing bits of TRISD, and a
LATD variable defined to access the entire byte-wide register.)
The LATD (latch) register is used to set the output state of the
RD7-RD0 pins. A bit value of ‘1’ sets an output pin to a high
state. Bits for pins defined in the TRIS register as inputs do not
have an effect. Setting LATDbits.LATD7 = 1 will output a
high level on RD7, turning on LED 7 on the demo board.
while(1) In this case of code running on an embedded microcontroller,
there is no operating system to return to when the code
finished executing. Therefore, an infinite C while loop is
used to keep the microcontroller running and prevent it from
exiting main() and trying to execute undefined memory
locations.