How to drive optoisolator from Mains
This circuit is fairly commonly used: -



Note the values of R1 and R2 - they limit current into the opto's LEDs to a few mA. This is important because you need to "drop" the mains voltage to around 0.7 volts for each LED (one deals with positive half cycles and the other deals with negative half cycles).

One resistor could be used (circa 200 kohm) but its voltage rating may be exceeded by the mains voltage so, a lot of folk choose two resistors with their combined voltage ratings exceeding the peak of the mains AC voltage.

The circuit above is called a zero crossing detector because as the mains waveform passes through zero, the transistor in the opto momoentarily switches open circuit.

An MOC3021 only has a single infra red diode in its emitter section therefore to use it you must put a reverse protection diode across it to prevent excessive reverse voltages damaging it. It only gives "half-wave detection too: -



You also need to consider that the resistor(s) dropping the AC voltage are, in effect power rated as if they were connected across the whole of the mains AC supply.

This link might help with a few extra ideas.