Programming for LED blinking in PIC18F4550

Topic Progress:

The control of the LED circuit is through the port registers. In OpenLab default ports used for LED blinking is PORTD and PORTB. PORTD is 8bit bidirectional port. Each port has 3 registers for its operation. These registers are

  • TRIS Register: TRISD is the corresponding data direction register. Setting TRISDbits(=1) will make corresponding PORTD pin as an input. Clearing a TRISD bit (= 0) will make the corresponding PORTD pin an output.
  • PORT Register: Reads the levels on the pins of the device. Setting PORTDbits(=1) will make the corresponding pin as HIGH and setting PORTDbits(=0) will make the pin as LOW.
  • LAT Register: The Data Latch register (LATD) is also memory mapped. Read-modify-write operations on the LATD register read and write the latched output value for PORTD.

The IO pins are categorized under a set of ports. Eg: To set the direction of ‘PIN 0’ of ‘PORT D’ as OUTPUT, the following operation must be done.

TRISDbits.TRISD0 = 0; // More about these operations will be discussed in the next section

IMPORTANT TIPS:

There is an important point to be remembered while writing data onto a register. Each of the registers will have a maximum of 8 bits and there is a manner in which these registers must be handled.
1. Assume that we are setting the direction of pin 0 of port D as OUTPUT. (Pin naming starts from 0 and ends at 7).
TRISDbits.TRISD0 = 0; //This will set the direction of the desired pin as output
or
TRISD=0; //To set complete pin of PORTD as output

2. Setting the pin 0 as HIGH and LOW to blink the LED.

PORTDbits.RD0 = 1; //This will make the desired pin as HIGH
delay_ms( );
PORTDbits.RD1 = 0; //This will make the desired pin as LOW

or
To set the complete pin of PORTD as HIGH
PORTD=1;

3. Toggle the port bit and give a delay in between the operation to give a blinking effect.

Code Snippet:

Blink an LED using PIN 0 of PORTD.

#include<xc.h>

int main()
{
     TRISDbits.TRISD0 = 0;
     do{
          PORTDbits.RD0=1;
          delay_ms(); 
          PORTDbits.RD0=0;
          delay_ms();
     } while(1);
}

void delay_ms(void)
{
     int i,j;
     for(i=0;i<1000;i++)
          for(j=0;j<1000;j++);
}