Electronic – PIC18 GPIO switch from input to output(dual mode)

gpiopic

I have always wondered if it is possible to switch the port direction of the PIC GPIO during the course of the program execution. So, for instance I start with a particular port set as an input(digital level). I monitor that pin, and if the level changes, I change the direction of that pin and drive a signal to turn on a LED. Is this too far fetched or is it doable? If so, some pseudo-code to would be very helpful.

Best Answer

Yes, it's completely possible you simply change the relevant bit in the associated TRIS register from 1 to 0 in order to change the pin from input to output.

In general on the PIC18 series you should read pins using the PORT register and write using the LAT register.

So suppose you had a pin like this:

schematic

simulate this circuit – Schematic created using CircuitLab

You could periodically read RA0 as an input and drive the LED the rest of the time. To read the switch state you would set bit 0 in the TRISA register high, wait a bit, then read the PORT pin (bit 0 of PORTA), and then clear bit 0 in the TRISA register.

To avoid contention, only set the pin to output if the LED is to be driven low. The LED will always come on as long as the switch is pressed.