Attached is a bi-directional optically isolated I/O circuit.
I used as an example gate-to-gate optocouplers but fill free to modify this circuit to your needs ..
For each I/O you will need 2 pins from your microcontroller: one for data and one for direction ..