Electronic – On PIC18 series, when should I use LAT register and when PORT


I'm programming a PIC18F4680 using mikroElektronika's mikroC PRO compiler and I've set the LCD library to use following ports to communicate with LCD:

// LCD module connections
sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;

sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
// End LCD module connections

and the LCD is sometimes displaying garbage. I was told to LATB instead of PORTB registers and after reading the I/O Ports section of the datasheet, it's still not clear to me when I should use PORT and when LAT registers.

Best Answer

Use PORT to read from a pin, and LAT to write to a pin (and TRIS to change the direction).

Some PICs do not have a LAT register, in those case you are forced to use the PORT register to write to a pin, which exposes you to the dreaded Read-Modify-Write (it's not a bug, it's a feature!). Check my explanation in Interfacing a keypad with a microcontroller