MCU Examples.com
PIC Microcontroller Project Examples, free source codes and resources collection.
Relay coil's current requirement is usually more than 100mA (for small relay about 100mA) and microcontroller cant supply this much of current to relay by it self. So as shown in following schematic diagram, we have to use transistor to handle this current requirement. Base pin of NPN transistor used here is connected to ground pin via resistor to make sure that relay will stay off when microcontroller does not output +5V to transistors base. This will make sure only logic 1 on microcontroller pin will activate relay. It is better to use Darlington transistor to handle current requirement for relay, because darlington transistor can handle more current than single transistor.
It is essential to connect a diode across relay coil in reverse bias to protect transistor form back EMF created when relay is released from energized or ON state. If this diode is not used, transistor and/or microcontroller which is driving relay may be damaged upon releasing energized relay. The diode will short out the back EMF produced by coil when it turned OFF from ON state.

Following example shows schematic diagram and source code written in Mplab C18 to operate a bulb connected to AC power line. Program will blink the AC bulb.
MPLAB project source available here and OrCAD project is available upon request. (USE forum)

// // 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; //Make PORTC out put while (1) { LATCbits.LATC0=0; //Set all pins of portC to logic high delay_ms(500); // delay 500mS LATCbits.LATC0=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 } }