Datasheet

PICkit™ 3 Debug Express
DS41370C-page 28 © 2009 Microchip Technology Inc.
FIGURE 3-19: LESSON 3 “ROTATE LED” SOURCE CODE
Here is the basic flow of our Rotate LED program:
3.3.4 Build and Program the Lesson 3 Code
In the MPLAB IDE, build the Lesson 3 project and program the code into the demo
board using the PICkit 3 Programmer.
The demo board LEDs will rotate from LED 0 up to LED 7 and then back to LED 0.
/** V A R I A B L E S *************************************************/
#pragma udata // declare statically allocated uninitialized variables
unsigned char LED_Number; // 8-bit variable
/** D E C L A R A T I O N S *******************************************/
// declare constant data in program memory starting at address 0x180
#pragma romdata Lesson3_Table = 0x180
const rom unsigned char LED_LookupTable[8] = {0x01, 0x02, 0x04, 0x08,
0x10, 0x20, 0x40, 0x80};
#pragma code// declare executable instructions
void main (void)
{
LED_Number = 0;// initialize
TRISD = 0b00000000;// PORTD bits 7:0 are all outputs (0)
while (1)
{
// use lookup table to output one LED on based on LED_Number value
LATD = LED_LookupTable[LED_Number];
LED_Number++;// rotate display by 1
if (LED_Number == 8)
LED_Number = 0;// go back to LED 0.
Delay1KTCYx(50);// Delay 50 x 1000 = 50,000 cycles; 200ms @ 1MHz
}
}
Initialize Variables and I/O Port
The global variable LED_Number, which holds the number of the LED we cur-
rently want on, is set to ‘0’ for the first LED.
The TRISD register bits are all set to ‘0’, so that all 8 port D pins RD0-RD7 are
outputs.
Loop Forever with the while(1) statement:
Set the I/O Port to turn on an LED.
The number of the LED to turn on, LED_Number, is used an index
to the array LED_LookupTable which returns a value with a bit set
corresponding to the LED to be turned on. This value is written to
the LATD register to turn on the one LED.
Rotate the LED number
The LED number is incremented to the next LED. The if state-
ment checks to see if it has been incremented past the last LED. If
so, it is reset to the first LED, number 0.
Delay
200ms
As in Lesson 2, a “delays” library function is used to create a time
delay.
(Loop End)