I want to hook up an LED to a port of microcontroller to be used for some sort of indication by a user. However, this LED ties up one pin of a port. How can you hook up both LED and let the pin be used for both input and output if there is a need for it? Thanks
In the case of using a pin as both an input and an output, for the most part, you can’t. There are cases where with proper planning you could coordinate it properly but there will be limitations to what you will be able to do. You can look at RS485 tranceivers or 1-wire devices to get ideas.
In an output only case, you can do things like multiplexing which is common on multiple 7-segment displays and similar devices. While this takes more than one I/O pin, the pin requirement is lower than the number of discrete elements to be driven. Limitations to this is you need to spend more mcu cycles processing the loop where in a discrete approach you can simply turn an element on and forget about it. Brightness also suffers in this arrangement since it will be running at less than 100% duty cycle.
Now that lots of microcontrollers have analog inputs, it is very easy to put multiple inputs (like multiple buttons) onto a single pin by using voltage dividers. If you don’t have an A/D, matrix keypads let you have more buttons than I/O pins. The limitations to this is you can not process multiple key presses at the same time.
If you want true independant control of your discrete I/O and you don’t have enough pins on your controller, you will need to look at a larger controller or some flavor of I/O expander. They make SPI and I2C expanders that give you full bidirectional control over additional I/O pins all through a serial link. You could also do some clever work with shifters, muxes, latches, and the like to make a truely discrete approach.