In this guide
Optocouplers Explained: Galvanic Isolation for MCU Projects
Your ESP32 runs fine on the bench. Then you connect the motor driver, the motor spins up — and the microcontroller resets. Or your ADC readings swing wildly the moment the relay coil de-energises. Or worse: something on the high-voltage side of your circuit finds its way back into the 3.3 V logic rail and the board never powers up again.
All three of these are ground and coupling problems. And the classic, cheap, well-understood fix is the optocoupler: a tiny chip that moves a signal across a gap of nothing — light — so that the noisy, dangerous side of your project never shares an electrical connection with the side your microcontroller lives on. This guide explains what an optocoupler actually does, why it matters, how to calculate the one resistor that makes it work, and how to wire it correctly for digital inputs, relay drives, and fast signals.
What an optocoupler actually is
An optocoupler (also called an opto-isolator) is an LED and a light-sensitive detector sealed in one package, facing each other across a small insulating gap. Current through the LED produces light; the detector sees that light and conducts. There is no copper path between input and output — only photons. That is the entire trick, and it is enough to provide galvanic isolation: two circuits that exchange information while sharing no electrical connection at all, not even a common ground.
Open one up on paper and you see two halves:
- The input side (emitter): an infrared LED. Drive a few milliamps through it and it glows. This is a plain diode, with a forward voltage of roughly 1.2 V (a typical datasheet-class value for these infrared LEDs) and a maximum continuous current usually in the 20–50 mA range depending on the part.
- The output side (detector): most commonly a phototransistor — a transistor whose base is activated by incoming light instead of an electrical base current. When the LED is on, the phototransistor conducts between its collector and emitter. When the LED is off, it stays off.
- The barrier: a transparent insulator between them. This is what carries the isolation rating. A common part like the PC817 is rated around 5000 Vrms of isolation voltage (typical datasheet value) — the voltage the barrier can withstand in a type test. More on what that rating does and does not promise later.
The three parts students actually meet
- PC817 — the everyday workhorse. A 4-pin DIP containing one infrared LED and one NPN phototransistor. Cheap, everywhere, and fast enough for buttons, relays, slow sensors, and status signals. Its current transfer ratio (CTR) is commonly specified anywhere from about 50% to 600% depending on the rank of the part, with the most common ranks clustering around 80–400% (typical datasheet-class ranges). Isolation rating around 5000 Vrms. This is the part this guide's examples use.
- 4N25 / 4N35 — the older American equivalent you will find in legacy schematics and lab stockrooms. Electrically similar to the PC817 but generally slower and with a lower guaranteed CTR (minimum around 20%). If your lab drawer has these, the wiring below still applies; just expect lazier switching and design with more CTR margin.
- 6N137 — the high-speed option. Instead of a bare phototransistor it contains a photodiode plus an integrated logic output stage, and it reaches data rates in the 10 Mbit/s class with a typical propagation delay around 50 ns. It needs a 5 V supply on the output side and its output is an open-collector logic gate. When you need to isolate a UART line, a fast PWM feedback signal, or anything at SPI-adjacent speeds, this is the part — not the PC817.
How it works, step by step
Step 1 — Current in, light out (the LED side)
The LED side is a normal diode circuit. You apply your logic voltage (say 5 V from an Arduino pin, or 3.3 V from an ESP32 pin), drop current through a series resistor, and the LED lights. The brightness is roughly proportional to the forward current, and the detector responds to that brightness. Typical forward currents for reliable switching are 5–20 mA — enough to drive the phototransistor hard, low enough to stay comfortable for a microcontroller GPIO.
Step 2 — The current transfer ratio, in plain words
CTR is the one number that makes the output side predictable. It is defined as:
CTR = (collector current of the phototransistor) / (forward current of the LED)
A CTR of 100% means 10 mA of LED current lets the phototransistor sink 10 mA. A CTR of 50% means the same 10 mA of LED current only guarantees 5 mA of collector current. CTR varies with the individual part, with temperature, and with ageing — a part rated 50–600% might measure anywhere in that span, and it drifts downward over years of service.
The design rule that follows: never design at the typical CTR. Use the minimum CTR from the datasheet (or, if you only know the rank range, the bottom of it), and then demand even less than that from the transistor. A comfortable rule of thumb is to keep the collector current you actually need below about one-fifth of (minimum CTR × your LED current). That margin absorbs temperature drift, part-to-part spread, and ageing in one go.
Step 3 — The LED resistor, worked example
Take the most common case: a 5 V logic pin driving a PC817, targeting 10 mA of LED current.
Known values:
- Supply: 5.0 V
- LED forward voltage: ~1.2 V (typical)
- Desired LED current: 10 mA (0.010 A)
Resistor calculation:
R = (5.0 V - 1.2 V) / 0.010 A = 380 ohms
380 ohms is not a standard value, so pick the nearest standard one above it: 390 ohms. The actual LED current is then (5.0 − 1.2) / 390 ≈ 9.7 mA — close enough. Check the resistor's power: 3.8 V × 9.7 mA ≈ 37 mW, comfortably under a quarter-watt resistor's rating.
If the driving pin is a 3.3 V ESP32 output instead: R = (3.3 − 1.2) / 0.010 = 210 ohms → use the standard 220 ohms (≈ 9.5 mA). One caution: keep the LED current at or below what your GPIO pin can source comfortably — most microcontroller pins are happiest at 10 mA or below, so there is rarely a reason to push past 10 mA on the LED side anyway.
Step 4 — The pull-up on the transistor side
The phototransistor is a switch to ground, not a voltage source. By itself it can only pull its collector down; something has to pull it up when the LED is off. That something is a pull-up resistor to the isolated side's supply. A typical value is 10 kΩ, which at 3.3 V asks the transistor to sink only about 0.33 mA when on — trivially within the capability of a PC817 driven at 10 mA LED current even at the worst-case end of the CTR range. The output is therefore inverted: LED on → transistor on → output pin pulled LOW; LED off → pull-up wins → output reads HIGH.
Size the pull-up the same way you would any open-collector output: low enough to switch fast and beat noise, high enough not to demand more collector current than the transistor can deliver at your LED current and worst-case CTR. 4.7 kΩ to 10 kΩ covers nearly every student digital-input case.
Step 5 — Why saturation is slow, and when that matters
For a clean digital signal you want the phototransistor driven fully on — saturated. But a saturated transistor stores charge in its base region, and that charge takes time to clear when the LED turns off. On a PC817-class part, turn-off can take tens of microseconds. For a relay command that changes once a second, or a button press, that is invisible. For a 115200-baud UART line, where each bit lasts about 8.7 microseconds, it is a brick wall: the signal never finishes falling before the next bit starts, and the data turns to mush.
That is not a defect — it is the price of a simple phototransistor. When the signal is fast, you do not push the PC817 harder; you switch to a fast part like the 6N137, whose integrated output stage is designed to snap on and off in tens of nanoseconds.
Wiring a PC817 digital input
The classic use: a switch, a sensor output, or a 12/24 V status signal on the "dirty" side, read safely by a 3.3 V microcontroller. Each side gets its own ground, and the two grounds must never touch — that separation is the isolation.
PC817 pinout (DIP-4, notch up, pins numbered counter-clockwise from top-left): pin 1 = LED anode, pin 2 = LED cathode, pin 3 = phototransistor emitter, pin 4 = phototransistor collector.
MCU side (5 V logic) Isolated side (e.g. 12 V)
-------------------- ------------------------
5V o----+
|
390R
|
GPIO o--[1]
PC817 <-- isolation gap: no copper crosses
GND o--[2]
+12V o----+
|
10k
|
(separate ground!) [4] o-------+-------o OUTPUT
(isolated) PC817 (to MCU input,
ISO_GND o--[3] [3] o--------------+ via nothing
electrical —
that's the point)
In words: the GPIO pin drives pin 1 through the 390 Ω resistor; pin 2 returns to the MCU's ground. On the other side, pin 4 is pulled up to the isolated 12 V rail through 10 kΩ, and pin 3 goes to the isolated ground. The OUTPUT node sits at the collector: HIGH when the LED is dark, pulled LOW when the MCU lights the LED.
On the microcontroller side, the input can simply be a digital pin — and note the inversion: digitalRead() returns LOW when the LED is on. A modest firmware sketch looks like this:
const int ISO_PIN = 4; // wired to the optocoupler's collector
void setup() {
pinMode(ISO_PIN, INPUT_PULLUP); // belt and braces; the 10k does the real work
}
void loop() {
// Output goes LOW when the LED side is driven — the signal is inverted.
bool signalActive = (digitalRead(ISO_PIN) == LOW);
if (signalActive) {
// respond to the isolated input
}
delay(50);
}
Two things to double-check before powering up: the resistor value matches your actual logic voltage (5 V → 390 Ω; 3.3 V → 220 Ω), and the two grounds are genuinely separate — one stray jumper between MCU GND and ISO_GND silently deletes the isolation you just built.
Isolating a relay drive
Relays are where students meet isolation first, because relay coils are electrically rude: when a coil de-energises, its collapsing magnetic field kicks a voltage spike back down the drive wiring, and that spike loves to travel into shared ground traces and reset nearby microcontrollers.
One honest warning about scope: a PC817's phototransistor can sink only a few milliamps reliably — nowhere near the 60–90 mA a typical small relay coil draws. The optocoupler does not replace the drive transistor; it precedes it. The standard chain is:
MCU pin → optocoupler LED → phototransistor (isolated side)
→ NPN transistor or MOSFET gate → relay coil → relay supply
The optocoupler sits between the MCU and the coil-driving transistor, so the coil's supply and its ground stay on the isolated side while the MCU stays on the clean side. And yes — the coil still needs its flyback diode across it. Isolation blocks conducted noise and ground bounce; it does nothing about the inductive spike at the coil itself, which the diode clamps locally.
A practical shortcut: many ready-made relay modules already include a PC817 (or equivalent) on board. Before adding your own optocoupler stage, look at the module: if it has an opto-isolator with separate VCC/JD-VCC style power pins, adding a second isolation stage in front of it gains you nothing except another inversion to keep track of.
Fast signals with the 6N137
When the signal outruns a phototransistor — UART at 115200 baud, fast PWM feedback, encoder pulses above a few kilohertz — reach for the 6N137 instead of fighting the PC817. The wiring differs in one important way: the output side is active logic and needs its own 5 V supply.
- Pins 2 and 3 are the LED (cathode, anode); drive the anode through a resistor from the transmitting side exactly as before (around 10 mA is typical).
- Pin 8 is the output-side supply (Vcc, 5 V), pin 5 is the output-side ground — this ground belongs to the receiving side and must be separate from the transmitting side's ground.
- Pin 6 is the open-collector logic output; pull it up (a few kΩ) to the receiving side's logic rail.
- Pin 7 is an enable input; tie it high (to Vcc) if you do not need to gate the output.
With a typical propagation delay around 50 ns and data-rate capability in the 10 Mbit/s class (typical datasheet-class figures), the 6N137 passes 115200-baud UART with the timing essentially untouched — each bit is about 8.7 µs wide, and a 50 ns delay is a rounding error. The one cost is power: the output side draws a few milliamps continuously from its supply, and you must actually provide that isolated 5 V rail.
A useful rule of thumb for choosing between them: if your signal changes slower than about 1 kHz, the PC817 is simpler and cheaper; if it changes faster than about 10 kHz, or it is a serial protocol of any kind, use the 6N137 (or a similar high-speed optocoupler).
Component-selection recipe
Work through these four questions in order and you will land on the right part nearly every time:
- How fast is the signal? Below ~1 kHz digital: PC817 / 4N25 class. Serial data, fast encoders, anything above ~10 kHz: 6N137 class. In between: calculate the bit time, compare it against the phototransistor's tens-of-microseconds turn-off, and do not gamble.
- How much LED current can the driver spare? A microcontroller GPIO at 5–10 mA is plenty for any of these parts. If your driver is weaker (some sensor outputs, 3.3 V logic with tight current budgets), check the minimum CTR at your actual LED current — CTR is specified at a particular forward current, and it is lower at very small currents.
- What isolation rating do you need? For low-voltage student projects (motors, relay coils, 12/24 V industrial-ish signals), the ~5000 Vrms class rating of a PC817 is far more than the circuit needs. For anything touching mains voltage, the barrier rating is only the beginning — creepage distances on your PCB, the enclosure, and fusing matter more than the chip. See the limitations section.
- What does the output side look like? If the receiving side can provide its own 5 V supply, the 6N137's clean logic output is a pleasure to work with. If the output side is just a pull-up to an existing rail, the PC817's bare phototransistor is the simpler fit.
Common wiring mistakes
| Mistake | What actually happens | Fix |
|---|---|---|
| LED driven with no series resistor | The LED sees the full logic voltage, draws destructive current, and dies — sometimes taking the GPIO pin with it. | Always size the resistor: (Vlogic − 1.2 V) / I_LED. 390 Ω at 5 V, 220 Ω at 3.3 V for ~10 mA. |
| Phototransistor with no pull-up | The collector floats; the output drifts, picks up noise, and reads randomly. | Add a 4.7–10 kΩ pull-up to the isolated side's supply. |
| Grounds joined "just for reference" | The isolation barrier is bypassed by a copper wire. You now have an expensive non-isolated level shifter. | Keep the two grounds separate — separate supplies ideally, or at minimum separate ground nets that never meet. |
| Designing at typical CTR | Half your boards work; the rest have a phototransistor that cannot pull the output low at temperature extremes or after ageing. | Use minimum CTR, then demand less than a fifth of it. |
| PC817 on a UART line | Turn-off lag smears bits together; communication fails intermittently or totally at 115200 baud. | Use a 6N137-class fast optocoupler for serial data. |
| Expecting the opto to drive a relay coil | A few milliamps of collector current against a 70 mA coil: the transistor saturates, overheats, and the relay chatters or never pulls in. | Opto → drive transistor → coil. The opto is the signal path, not the power path. |
| Forgetting the signal inverts | Firmware waits for HIGH that never comes, or triggers on the wrong edge. | Remember: LED on = output LOW. Handle it in code or with a second inversion. |
FAQ
Do I need an optocoupler if my relay module already has one?
Probably not another one. Many common relay modules include a PC817-class opto with the coil supply separable from the logic supply. Check the module's schematic or PCB: if the opto is present and you power the coil side separately, your isolation is already in place. Stacking a second optocoupler in front of it just adds an inversion and another part to debug.
Can an optocoupler isolate mains-voltage sensing?
The barrier inside the chip can withstand kilovolts in a type test, but a safe mains-sensing circuit needs much more than the chip: correct creepage and clearance on the PCB, proper input resistors rated for mains voltage, fusing, and an enclosure. The optocoupler is one component of a safe design, not the whole design. If you are unsure about any of those, treat mains as out of scope for the project.
Can I drive the LED directly from an ESP32 or Arduino pin?
Yes — through the series resistor. At 5–10 mA of LED current you are well within what a GPIO pin can source, and the resistor calculation above gives you the value. Do not skip the resistor, and do not parallel the LED across the pin without one "because it is only 3.3 V": the LED's forward voltage is ~1.2 V, so the pin would see nearly a short.
Why is my PC817 output slow to turn off?
That is saturation doing its job. You are driving the phototransistor hard on for a clean digital level, and a saturated transistor needs tens of microseconds to clear stored charge when the LED goes dark. It is the correct behaviour for a slow signal. If the signal needs to be fast, the answer is a fast part (6N137), not a smaller resistor.
Do the two sides need separate power supplies?
Strictly, they need separate grounds; the isolation is between the ground references. In practice, separate supplies (or a small isolated DC-DC module) are the clean way to guarantee it. Powering both sides from the same supply's rails with "separate" ground wires that meet at the supply is a common half-measure — it works against ground bounce but it is not true galvanic isolation.
PC817, 4N25, or 6N137 — which do I actually buy?
For buttons, relays, slow sensors, and on/off status: the PC817 (or whatever your lab stocks between it and the 4N25). For UART, fast PWM, or encoder signals: the 6N137. Buy a strip of PC817s for the parts box regardless — they are the component you will reach for most often, and having them on hand removes the temptation to wire something unisolated "just for testing".
Limitations — what isolation does not do
- The voltage rating is a type-test number, not a safety certificate. A ~5000 Vrms barrier rating means the package survived that voltage in a controlled test. Real-world safety against high voltage depends on creepage and clearance distances on your PCB, the quality of the solder mask, humidity, contamination, and the enclosure. Cheap modules and hand-soldered boards routinely achieve far less than the chip's rating. Never treat the optocoupler as your only mains-safety measure.
- CTR is a moving target. It varies part to part, falls with temperature, and degrades with LED ageing — a heavily-driven LED run hot for years can lose a large fraction of its original CTR. The margin rule (design to a fifth of minimum CTR) exists precisely because of this. In a project that must work for years, keep LED current modest rather than maxing it out.
- Speed has a hard ceiling per part. A phototransistor optocoupler will not do serial data, no matter how you bias it. Match the part to the signal's speed at selection time; there is no component-value trick that makes a PC817 fast.
- The LED side draws continuous current. Unlike a MOSFET gate, the LED needs its ~10 mA for as long as the signal is active. In battery-powered designs with always-on isolated signals, that current matters — budget it.
- Isolation does not fix the coil spike. The flyback diode across a relay coil is still mandatory. Isolation stops noise from travelling between ground domains; it does not clamp the inductive kick at its source.
- One shared ground voids everything. Isolation is a property of the wiring, not the chip. A single ground jumper, a shared USB shield, or a scope probe ground clip connecting the two sides collapses the barrier instantly. When debugging an isolated circuit, remember that your oscilloscope's ground lead is itself a connection — measure each side against its own ground, never across the barrier with one probe.