why does the microcontroller pin driving optocoupler is giving 2V even if it is set?
The input side of an optocoupler is essentially an LED (or sometimes two LEDs arranged in anti-parallel). Consider this schematic:







simulate this circuit &ndash; Schematic created using CircuitLab

Now, depending on how much output current the microcontroller can provide on an output pin, or conversely what the output impedance of the output pin is, the load (i.e. the LED in this case) will pull down the output voltage of the microcontroller pin, with the difference being dissipated as heat in the internal output impedance or current limiting mechanism of the microcontroller. 

The MOC3041 datasheet indicates the input LED has a forward voltage of 1.3 Volts (typical), and can be operated at up to 60 mA current. Thus, if the microcontroller output pin voltage is found to be dropping down to 2 Volts, the 220 Ohm resistor is dropping the remaining 2.0 - 1.3 = 0.7 Volts. This would happen at a current of ~3.2 mA, not quite suitable for turning on the optocoupler's output. 

This also indicates that the microcontroller apparently has nearly a 1 kOhm output impedance on the pin concerned, to be dropping 3 Volts on a 3.2 mA load: That seems rather high / unlikely, so it is possible that there is some additional load on the output pin. A schematic would help figure it out. 

Any which way, no microcontroller output pin will have a fixed 5 Volt output independent of load current. An output voltage drop is expected, the magnitude being driven by the current drawn from the output pin.