Electronic – How to drive LED when sinking current to MCU

gpioledpic

Hopefully a simple one. Should I always control by writing to the GPIO digital output? Or should I always leave it low and then tri-state the output?

LED turns on when MCU pin sinks current:

enter image description here

In code, I mean the difference between the following for the given schematic:

// Control entirely via GPIO    
TRISBbits.TRISB5 = 0; // configure as digital output
LATBbits.LATB5 = 0; // turn on the LED
LATBbits.LATB5 = 1; // turn off the LED

// Tri-state output to always just enable/disable
LATBbits.LATB5 = 0; // drive output low
TRISBbits.TRISB5 = 0; // turn on by configuring as digital output
TRISBbits.TRISB5 = 1; // turn off by configuring as digital input

Best Answer

In the case you've shown, it doesn't really matter too much. I'd leave the output as an output and control the LED from the LAT bit. If the input is not a Schmitt Trigger input, you could get unnecessary power consumption from having an input floating around, and having inputs floating around is just not good practice in any case.

Where it could matter more is if you're using an older PIC that does not have a separate LAT register (or are directly writing to the port register on a PIC that has a LAT register, in which case, don't do that).

In such a case, you could run into a read-modify-write issue where an instruction to modify a different (unrelated) bit in the same port register could flip the LED port bit into a high state, so the next time you set the TRIS bit low the LED does not turn on. It might not happen reliably one way or the other since the pin is floating around.

Related Topic