TRISx, PORTx, LATx dumb it down for me!

Are you new to MPLAB? Do you want to work with PIC microcontrollers? You feel setting up the project is too complicated? So let’s dumb it down for ourselves.

GPIO

First thing you set out to do when you get your hands on a new microcontroller is right the HelloWorld of our world, the blinky code. In the blinky project, an LED connected to microcontrollers GPIO pins. GPIO or General Purpose Input Output pins are used as an input or output pins. In the blinky project case, we use it as output.

Configuring GPIO pin as an output

Now if you have worked with Arduino it’s quite simple. You simply use the pinMode() command to set any pin to OUTPUT or INPUT. But as you start working with more advanced controllers and have a deeper access to the controller there are few other things that have to be configured to be able to use a pin as INPUT or OUTPUT.

Setting up GPIO pins for PIC microcontrollers

There are three registers that you need to familiarize yourself when working with PIC microcontrollers specifically, others may be the same or different.

  • TRISx
  • PORTx
  • LATx

TRISx

TRIS means TriState or three different settings. Now, this particular register corresponding to a GPIO pin is used to select whether the pin is being used as an input or an output. But you may ask what’s the third state as the name suggest? It’s a high impedance state. This is the input state where due to high impedance no current flows into the microcontroller. The other two states are 0 and 1 for the output pin.

This is how tristate can be visualized. B is the tristate switch (in our case a register) and C is the pin.

Fun fact

Tristate is listed as a trade mark thus microchip uses TRIS as shortform meaning the same thing.

https://trademarks.justia.com/876/18/tristate-87618512.html

PORTx

The PORT register corresponding to each pin is used to OUTPUT to the pin. Whatever you want on the pin, you set the pin as OUTPUT using TRISx register and then write the value to PORTx.

LATx

The LAT register corresponding to a GPIO pin is used to read the value on the pin. Remember to use a GPIO as INPUT corresponding TRISx register should be set accordingly.

Hope this helps. Happy coding!