Difference between PORT and LATCH on PIC 18F

acemtp picture acemtp · Apr 12, 2010 · Viewed 76.2k times · Source

I already read the datasheet and google but I still don't understand something.

In my case, I set PIN RC6 of a PIC18F26K20 in INPUT mode:

TRISCbits.TRISC6 = 1;

Then I read the value with PORT and LATCH and I have different value!

v1 = LATCbits.LATC6;

v2 = PORTCbits.RC6;

v1 gives me 0 where v2 gives 1.

Is it normal? In which case we have to use PORT and in which case LATCH?

Answer

Mark Rushakoff picture Mark Rushakoff · Apr 12, 2010

The latch is the output latch onto which values are written. The port is the voltage at the actual pin.

There are a few situations where they can be different. The one that I've encountered most frequently is if you have a pin (accidentally) shorted to ground. If you set the latch high, the latch will read high, but the port will read low because the voltage on the pin is still approximately ground.

Another situation leading to what you've described is when the port pin hasn't been configured correctly. I (and everyone I work with) have spent many hours trying to figure out why our PIC isn't working to expectations, to eventually find out that we glossed over turning off the analog modules, for instance. Make sure you go over the section I/O Ports -> PORT?, TRIS?, and LAT? registers in the datasheet. You can get more info in the Microchip wiki page which explains about reading the wrong value immediately after you write an output on a pin connected to a capacitive load.

That wiki page also explains:

A read of the port latch register returns the settings of the output drivers, whilst a read of the port register returns the logic levels seen on the pins.

Also, here's a snippet from the I/O Ports section on the 18F14K50 (which ought to be the same as the rest of the 18F series):

Each port has three registers for its operation. These registers are:

  • TRIS register (data direction register)
  • PORT register (reads the levels on the pins of the device)
  • LAT register (output latch)

So in most situations, you will write to the latch and read from the port.