Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversFall ResetAmazon USFall reset deals: check better picks before checkoutAmazon US: today's deals, useful picks and quick comparisons.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
Blog

How to Build an Isolated Digital AC Dimmer Using Arduino

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Important: This project switches lethal mains voltage. It is an educational design concept for people competent to design, assemble, measure, and enclose mains-powered equipment—not a beginner wiring project or a certified household dimmer. Optical isolation protects the Arduino’s signal paths; it does not make the load circuit safe to touch. For permanent household use, choose a properly rated, certified enclosed dimmer.

An Arduino phase-angle dimmer uses an isolated zero-cross detector to time each AC half-cycle, then drives a random-phase optotriac such as the MOC3021 to trigger a power triac after a controlled delay. A suitable resistive load is the best first test. Component values, PCB spacing, thermal design, enclosure, and protection must all be engineered for the actual mains supply and load.

What this dimmer does

This is a phase-angle AC dimmer, not ordinary low-voltage PWM. A triac switches an AC load for part of each half-cycle. The later it is triggered after the waveform crosses zero, the smaller the portion of the half-cycle delivered to a resistive load.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. The AC voltage passes through zero.
  2. An isolated detector signals the Arduino.
  3. The Arduino waits for a selected delay.
  4. A pulse through the optotriac triggers the power triac.
  5. The power triac conducts for the remainder of that half-cycle, then turns off naturally when load current falls below its holding current near the next current zero.

A shorter delay generally means more conduction and more power for a resistive load. Neither electrical power nor perceived brightness changes linearly with a knob value: “50%” on a control is not necessarily 50% power or half perceived brightness. A calibrated curve or lookup table is more useful than mapping a control setting directly to half-cycle delay.

#1 Best Overall
ELEGOO Mega 2560 R3 Project The Most Complete Starter Kit with Tutorial
  • 35+ Guided Electronics Projects: Progress from LEDs and buttons to RFID access, real-time clocks, motion and distance sensing, environmental monitoring, motor control and interactive displays for STEM learning, coding clubs and maker projects
  • More I/O and Memory for Larger Builds: The MEGA 2560 R3 provides 54 digital I/O pins, including 15 PWM outputs, 16 analog inputs, 4 hardware serial ports and 256 KB flash for projects that combine more sensors, controls and displays
  • 200+ Components for Prototyping: Includes LCD1602, RC522 RFID, RTC, DHT11, HC-SR501 PIR, ultrasonic and water-level sensors, GY-521, MAX7219, keypad, joystick, rotary encoder, relay, SG90 servo, stepper motor, DC motor, breadboard and more
  • Learn, Modify and Create: Follow 35+ guided lessons with example code, then adjust sensor thresholds, timing, display text, motor behavior and control logic to turn structured exercises into access systems, monitors, alarms and interactive projects
  • Organized for Repeatable Learning: Pre-soldered modules, a solderless breadboard, storage case and small-parts box reduce setup time and keep sensors, LEDs, ICs, wires and other components easy to find between projects

Functional layout and isolation boundary

                 ISOLATION BARRIER
  LOW-VOLTAGE SIDE             MAINS SIDE
  Arduino Nano  <── detector ── zero-cross network ── AC line/neutral
       │                                                  │
       └── optotriac LED ──||── random-phase output ── power triac ── load
                                                        │
                                                      snubber

The zero-cross detector and optotriac provide two separate optical signal paths across the barrier. The Arduino, its USB connection, and its control wiring belong on the low-voltage side. The detector input network, optotriac output, power triac, snubber, fuse, terminals, and load wiring are mains-side circuitry. The load remains electrically connected to mains; isolation does not make its terminals or the assembled device touch-safe.

The published project concept uses a TLP521-1 phototransistor optocoupler for zero-cross sensing, a MOC3021 random-phase optotriac, a BT138 power triac, and an Arduino Nano. The example assigns digital pin 2 to the detector signal and pin 10 to the optotriac LED drive. These are example choices, not universal requirements. See the project description and sketch; independently inspect any supplied PCB or Gerber files before considering them.

Why zero-cross detection matters

The detector gives the controller a repeatable timing reference. Mains frequency determines the available half-cycle:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Supply frequency Full cycle Half-cycle
50 Hz 20 ms 10 ms
60 Hz about 16.67 ms about 8.33 ms

The reference design uses a mains-side resistor/rectifier network and TLP521-1. Its output is not necessarily a razor-thin pulse at the mathematical zero: detector threshold, optocoupler behavior, resistor tolerance, and signal conditioning influence when the Arduino sees a transition. The firmware must act on a single event, not repeatedly while the detector output stays HIGH.

Rank #2
ELEGOO UNO R3 Project Super Starter Kit with PDF Tutorial for Beginners
  • TURN CODE INTO REAL-WORLD RESULTS — Follow 22+ guided lessons to make LEDs blink, read temperature and distance, move servo and stepper motors, control an LCD and respond to joystick or IR input; ideal for a family weekend build, homeschool unit, coding club or STEM classroom
  • MORE PROJECT VARIETY IN ONE ORGANIZED KIT — Includes the UNO R3 controller, LCD1602 with pre-soldered header, breadboard power module, ultrasonic and DHT11 sensors, joystick, IR receiver and remote, SG90 servo, stepper motor, relay, DC motor, fan blade, displays, LEDs, buttons, resistors and jumper wires
  • START WITHOUT SOLDERING — Plug-in modules, a solderless breadboard and the pre-soldered LCD help beginners focus on wiring, code and testing; the illustrated component list makes it easier to find each part and move from one lesson to the next
  • LEARN THE LOGIC, THEN CREATE YOUR OWN — Use Arduino IDE and the included example code to understand digital input and output, analog sensing, timing, motor control and display functions, then change thresholds, speeds and sequences for alarms, environmental monitors, reaction games and motion projects
  • CLEAR SETUP SUPPORT FOR FIRST-TIME BUILDERS — Download the latest tutorial and code, select the UNO board and correct computer port, check component polarity and breadboard rows, and keep power-module input at 9V or below; younger learners should work with an experienced adult

The original project reports visible flicker from timing jitter in some circumstances and uses polling instead of an interrupt. That is a report about that implementation, not a general rule: a carefully edge-detected interrupt or timer-driven state machine can provide deterministic timing. The important requirements are bounded jitter, one scheduling event per half-cycle, and a defined response when crossings stop. The EDN explanation also discusses timing and flicker concerns.

Choosing the switching parts

Zero-cross optocoupler

The TLP521-1 is the example detector optocoupler. Do not copy its mains-side resistor network blindly. Calculate resistor voltage stress, power, pulse capability, detector LED current, target mains voltage and frequency, and isolation requirements. Use the exact manufacturer datasheet for the chosen part and verify its pinout and ratings.

Random-phase optotriac

The example MOC3021 is a random-phase optotriac: it can trigger when commanded during a half-cycle, which is what phase-angle dimming needs. A zero-cross optotriac waits for the mains voltage to approach zero before switching. That is useful for on/off or burst switching with reduced switching noise, but it cannot provide arbitrary firing-angle control. These parts are not interchangeable for this purpose; see the project discussion of optotriac selection.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Power triac

The reference uses a BT138. Select a triac by more than its headline current rating. Check repetitive off-state voltage with margin for the local supply and transients, RMS and surge current, gate trigger current in the relevant quadrants, latching and holding current, on-state loss, thermal resistance, and immunity to rapid voltage and current changes. BT138 ratings, pinout, and package details depend on the exact maker and suffix; consult that part’s datasheet. Its mounting tab may be electrically connected to a triac terminal, so do not assume a heatsink is safe to touch or can be bonded to a metal enclosure.

Rank #3
Sale
ELEGOO UNO R3 Project Most Complete Starter Kit, Compatible with Arduino
  • 30+ Guided Electronics Projects: Start with LEDs and build toward LCD1602 displays, RFID access, motion detection, distance sensing, motor control and environmental monitoring for STEM learning, coding clubs, classrooms and hobby projects
  • 200+ Components Across 63 Types: Includes an ELEGOO UNO R3 controller, LCD1602, RC522 RFID, RTC, HC-SR501 PIR sensor, ultrasonic sensor, DHT11, GY-521, MAX7219, keypad, joystick, relay, SG90 servo, stepper motor, breadboard and more
  • Begin Without Soldering: Pre-soldered modules, a solderless breadboard, organized storage case and small-parts box reduce setup time and help beginners move from lesson to lesson while keeping LEDs, ICs, wires and sensors easy to find
  • Learn, Modify and Create: Program the ELEGOO UNO R3 board with Arduino IDE using the included PDF tutorial and example code, then adjust sensor thresholds, timing, display text and motor behavior to turn guided lessons into original projects
  • Flexible Power and Project Setup: Includes a 9 V, 1 A power supply, breadboard power module, 9 V battery and USB cable to support controller, breadboard and module experiments without sourcing basic setup accessories separately

Resistors, capacitors, snubber, and protection

The design includes RC snubber components to help control false triggering from rapid voltage changes and improve operation with some difficult loads. There is no universally correct snubber value: the triac, load inductance, wiring, voltage, leakage-current tolerance, and emissions requirements all matter. Validate the network with the intended load and consult the triac maker’s application guidance.

For any capacitor connected across or from mains, use the appropriate approved safety class for its actual connection and purpose. A voltage marking alone, even a 400 V rating, does not establish that a capacitor is suitable as a mains safety component. Likewise, resistor wattage alone does not establish suitability: check working voltage, pulse rating, fault behavior, and spacing. Provide appropriately rated overcurrent protection and terminals as part of the complete design.

Timing and firmware approach

The project’s demonstration sketch uses pin 2 as the zero-cross input, pin 10 as the control output, and a 5,000-microsecond delay. At 50 Hz, 5 ms is approximately the midpoint of a 10 ms half-cycle; it is not a universal 50% power setting. It is also beyond the 4.17 ms half-cycle at 60 Hz, so it cannot be used unchanged there.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Its basic loop waits for a HIGH detector input, delays, then drives the optotriac output HIGH. That illustrates the idea, but it is not production firmware: it can react repeatedly during one HIGH interval, does not create a finite gate pulse, and has no explicit timeout or fault state. A more robust design follows this sequence:

Rank #4
SunFounder Elite Explorer Kit with Original Arduino Uno R4 WiFi, RoHS Compliant, Bluetooth IoT ESP32 IIC LCD1602 OLED, Super Starter Kit, Online Tutorials & Video Courses for Beginners & Engineers
  • All-in-One Starter Kit for Arduino Beginners: The Kit features the original Arduino Uno R4 WiFi board, 300+ high-quality components, and 60+ free video lessons co-created with educator Paul McWhorter. With over 50 projects (30 basic, 13 fun, and 8 IoT), it's perfect for beginners aged 8+ to explore Arduino. Certified RoHS compliant, it ensures safety and quality for all learners.
  • Powerful Arduino Uno R4 WiFi Board: Upgraded from the Arduino Uno R3, the Arduino Uno R4 WiFi features a 32-bit processor, more memory, and built-in WiFi and Bluetooth, enabling connection to third-party apps for more interactive and practical projects.
  • 300+ Components for Endless Possibilities: With 300+ components and sensors, this kit is perfect for portable projects. It features step-by-step tutorials, open-source code, and compatibility with other Arduino boards like Uno R3 and Nano, offering endless customization and learning opportunities.
  • Engaging Projects for Every Skill Level: Featuring 50 projects (30 basic, 13 fun, 8 IoT) with IoT app integration like Arduino IoT Cloud , this kit supports Arduino C++ programming, making it perfect for students, teachers, and engineers to learn, code, and create at any skill level.
  • Dedicated Support for Beginners: Alongside online resources and video tutorials, SunFounder provides technical support and troubleshooting forums to help beginners solve programming challenges with ease.
on a qualified zero-cross event:
    cancel any pending gate event
    if requested level is zero:
        keep optotriac off
    else:
        calculate and clamp delay for this half-cycle
        schedule a short gate pulse
when pulse width expires:
    turn optotriac output off
if no valid crossing arrives before timeout:
    cancel events and turn output off

Implement this with an edge-detected input and timer scheduling appropriate to the selected Arduino board. Avoid blocking delays in a design that must also service timing or fault logic. Set the pulse width and the earliest/latest firing angles from the optotriac and triac datasheets and validate them in the circuit. Clamp delay against the configured 50 or 60 Hz half-cycle. Make zero output an explicit off state; define startup, reset, and lost-crossing behavior so the gate is not left asserted. The published project is useful as a conceptual reference, not a certified design or drop-in firmware solution.

Load compatibility

Load type Practical guidance
Incandescent or other resistive lamp Best initial test class, provided the lamp and switching components are properly rated.
Mains LED bulb Use only if explicitly marked dimmable and compatible with leading-edge triac dimming. Capacitive input circuits may flicker, fail to start, or react to triac leakage.
Universal motor May operate, but can produce EMI, acoustic noise, and commutation transients; validate the specific motor and control method.
Induction motor Generally a poor match for a simple phase-angle dimmer; reduced voltage can cause stalling or overheating.
Transformer Not a casual substitution: phase cutting can cause saturation and damaging current. Use a compatible control method.
Electronic power supply or low-wattage load May require trailing-edge control, may not start reliably, or may draw too little current to keep the triac latched.

Large inrush current can exceed the triac’s surge rating even when steady-state load wattage appears modest. Test one known-compatible load first; do not infer that a controller supports every AC load because it switches mains.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Thermal and mechanical design

A conducting triac dissipates heat. Estimate losses using expected RMS load current and the device’s on-state characteristics, then assess junction temperature against ambient temperature, enclosure airflow, thermal interface, and heatsink thermal resistance. Include a conservative margin and verify temperature under sustained operation with the actual load. The project notes its small heatsink was suitable only for short testing and that longer operation needs more heatsinking (project notes). If the package tab is live, use an appropriate insulating mounting arrangement and verify the complete assembly’s insulation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Lay out the PCB with distinct mains and low-voltage zones. Creepage and clearance depend on working voltage, pollution environment, material group, and applicable local standards; there is no single spacing value that is safe in every context. Keep copper, vias, mounting hardware, and other conductive features from compromising the isolation barrier. Slots or cutouts may help increase creepage, but do not replace a standards-based layout review. Use mains-rated wire and terminal blocks, strain relief, a flame-retardant enclosure, secure insulated test points, and clear line, neutral, load, and low-voltage markings. Protect users from exposed solder joints and live heatsinks. Wider reinforced tracks and extra vias can address current capacity, but track width alone does not make a board safe; the layout discussion is not a substitute for electrical safety design.

Best Value
REXQualis Super Starter Kit Based on Arduino UNO R3 with Tutorial and Controller Board Compatible with Arduino IDE
  • The most economical kit comes with everything compatible with Arduino to starting programming for beginners .
  • This is the upgraded starter kits come with a 9V 1A Power Adapter (At least $5.99 on amazon) to replace a 9V Battery , and the Lcd1602 module come with pin header(not need to be soldered by yourself).
  • Include High Quality Base Board base on Arduino UNO R3 compatible with Arduino IED and Sensors, Servo, Motor, ULN2003 driver board, lcds, etc.
  • Free PDF Tutorial and Datasheet are available to download from our official website or you can contact our customer service.
  • All of the Components and Integrated Circuits are individually packaged and labeled, and packing in a plastic box which is bigger enough for you.

Commissioning and measurement

Do not connect a conventional grounded oscilloscope probe’s ground clip to a mains conductor. The scope ground is typically connected to protective earth; the resulting connection can create a short, destroy equipment, or cause fatal shock. The project explicitly warns against this practice (measurement warning). Use a properly rated differential probe or professionally designed isolated measurement setup, and understand the measurement equipment’s ratings and procedure. Never treat Arduino USB ground as a safe reference for mains measurements.

  1. With power disconnected, inspect polarity, soldering, clearances, component orientation, and mechanical security.
  2. Check for shorts and verify separation between mains and low-voltage sections with suitable equipment and procedures.
  3. Exercise Arduino-side timing logic without mains connected.
  4. Use an appropriately isolated, current-limited test arrangement only if competent to do so; isolation equipment does not make exposed conductors safe.
  5. Test first with a low-power, known resistive load, with the circuit enclosed before applying normal mains power.
  6. Monitor for abnormal heat, flicker, fuse operation, resets, noise, or smell; disconnect power immediately if anything is unexplained.

Troubleshooting by symptom

  • Flicker: Check for repeated actions during the detector HIGH interval, threshold or timing jitter, a delay too near the end of the half-cycle, insufficient gate current, low load current, or an incompatible LED load. Also investigate electrical noise.
  • No output: Verify zero-cross events and timing first on the low-voltage side. Then, with power disconnected, verify optotriac polarity, LED current, triac pinout, gate resistor design, trigger quadrant requirements, and whether the load reaches the latching current.
  • Load stays on or triac misfires: Check whether the optotriac output is being held on too long, wiring is incorrect, dv/dt is excessive, or an inductive load is commutating poorly. Review snubber suitability and leakage.
  • Arduino resets: Investigate conducted or radiated transients, poor high-current/logic layout separation, decoupling, low-voltage supply quality, and unsafe USB or enclosure current paths.
  • Excessive heat: Recheck RMS current, inrush, thermal interface, heatsink, airflow, ambient temperature, and triac losses. Stop use until thermal design is corrected.
  • Fuse opens or audible noise appears: Disconnect and inspect for shorts, unsuitable loads, excessive inrush, or EMI. Do not increase fuse rating without a fault and conductor protection analysis.

When another approach is better

A random-phase optotriac plus triac is appropriate for learning phase-angle control and some compatible lamps. A zero-cross optotriac or solid-state relay is generally better for isolated on/off or burst switching, not arbitrary dimming. Some electronic LED loads work better with a compatible trailing-edge MOSFET/IGBT dimmer. If the goal is an installed household control rather than an experiment, use a certified, enclosed dimmer specified for the exact load class and local electrical requirements.

This architecture follows a project published in June 2019 and mirrored across electronics sites. Its component examples and layout files are not evidence of certification or universal suitability. Treat them as a starting point for understanding the blocks, not a build-ready appliance design.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Before applying mains: final checklist

  • Confirm the exact voltage, frequency, load type, and maximum steady and surge current.
  • Verify every optocoupler, triac, resistor, capacitor, terminal, wire, fuse, and heatsink against its actual datasheet and use conditions.
  • Review the isolation barrier, creepage, clearance, enclosure, strain relief, and touch protection for the applicable standards.
  • Confirm defined firmware behavior at startup, zero command, reset, and loss of zero-cross detection.
  • Use a known compatible resistive load first and a safe, correctly rated measurement method.
  • Do not use the device as a permanent mains appliance unless the complete product has been appropriately designed, tested, and certified.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.