MCU Examples.com
PIC Microcontroller Project Examples, free source codes and resources collection.
As Name implies, LED is diode and hence should be connected in correct polarity to operate correctly and lit up. Usually polarity of each lead can be identified easily. The cathode is the shorter lead and the LEDs "bulb" part usually has a cut or "flat" on the cathode side. Regular LED needs about 2V to operate and therefore we usually need resistor connected in series with LED before connect it to electronic circuit. Resistor value is calculated using Ohms law, V=IR. for example 5V MCU based project, like PIC18F2520 used here, when we activate pin on MCU that pin is measured 5V. So in series connection with LED, resistor should take care of 3V (5V - 2V). If LED consumes 10mA of current, that same current flows through resister since LED and resister are in series. Now, by Ohms law, 3V=10mA x R, which gives R=3V/0.01A. i.e. R should be around 300 Ohms. So we use standard available resistor of 330 Ohms with this regular LED.
If you are going to use big or high power LEDs, this resister should be chosen according to that. Also remember that most of microcontrollers has less than 10mA current source or sink capability per one pin. Therefore only small regular LEDs can be connected directly to MCU using series resistor. According to datasheets most of PIC microcontrollers can source or sink up to 25mA current per pin. If you connect high power LED directly to PIC or other MCU, most likely outcome is fried out MCU chip.
Following example schematic uses PIC18F2520 MCU and has eight LEDs connected to it. We are going to blink these LEDs in different ways using PIC MCU.

Source code for LED blinking.
This source code is compiled using Microchip C18 tool suite. Since Microchip C18 is ANSI compatible, you can port this source code to any C compiler for PICs easily.
This code will blink all LEDs together.
MPLAB project source available at end of the page and OrCAD project is available upon request. (USE forum)
You can downlaod MPLAB project files here.
// // Designed by www.MCUExamples.com // rasika0612@gmail.com // #include <p18f2520.h> #pragma config OSC = XT // 4MHz Crystal, (XT oscillator) #pragma config PBADEN = OFF // PORTB<4:0> pins are configured as digital I/O on Reset) void delay_ms(unsigned int duration); void main() { TRISC=0; while (1) { LATC=0xff; //Set all pins of portC to logic high delay_ms(500); // delay 500mS LATC=0; //Set all pins of portC to logic low delay_ms(500); // delay 500mS } } void delay_ms(unsigned int duration) // delay in miliseconds for 4.0MHZ crystal { unsigned int i; for(;duration!=0;duration--) { for(i=0;i<=50;i++) { _asm nop nop nop _endasm } _asm nop nop _endasm } }