Interfacing: AC Line

Sensing and Controlling the AC Line


AC Line Demo Circuit

On September 14, 2008 I gave a talk at the Hacklab in Toronto as the first of what will hopefully be many regular technical workshops by various presenters. The topic I chose was Interfacing Ideas for Microcontrollers. There is a wealth of information available about software programming techniques, which translate fairly well into microcontroller code ideas. So instead of get into too many software and computing details, I decided to focus on a discussion of interfacing hardware only. This time I introduced some concepts related to sensing and controlling the AC line from a microcontroller. My demo circuit was a microcontroller AC lamp dimmer which used a potentiometer to set the brightness level, and a pushbutton to switch between two modes: flashing or steady. Some of my notes and description of my demo circuit are described in this page.

Microcontroller I/O Basics

Apart from some special-purpose hardware available within a microcontroller, there are two main types of I/O pins that are very often used and exist on most types of microcontrollers: digital I/O and analog input. Digital I/O is the most common type and allows the control of either individual pins on a micro, or groups of pins at once from within the microcontroller program. Analog inputs allow the sensing and measuring of voltages using a built-in analog-to-digital converter. (ADC or A/D)

Digital I/O

When we speak of digital I/O, what we mean is that the pin of the device can normally be in one of two states: either off or on. Off usually means 0 volts, and on means 5 volts. (or whatever is the power supply voltage of the microcontroller, perhaps 3.3 volts) In code the off state is represented as a 0, and the on state as a 1. Signals can be input and output from the micro this way. Most micros are even strong enough to drive small loads like LEDs from their digital outputs. But in general, these I/O pins are designed for sending signals and not powering other devices.

Analog Inputs

Some pins on most micros can be set up as analog inputs. This allows the measuring of external voltages and can be very useful for a variety of applications. In my demo circuit I used a potentiometer to set the brightness of the lamp. The pot was connected across the power supply (+5V) and ground (0V) to provide a variable voltage output from 0-5V as the pot was rotated clockwise. The output was connected to the microcontroller and the analog to digital converter in the micro was used to measure this voltage and save the value into a memory location to be used as the lamp brightness.

The Need for Interfaces

Although there are many applications where circuits can be controlled and sensed with a microcontroller directly, there are even more applications where some sort of interface circuit is required. Either the external circuit runs at the wrong voltage, a high voltage, needs some sort of safety isolation, or needs to provide extra current that can’t be provided by the micro. Perhaps the problem is a combination of these things. In this case some sort of intermediate circuit is required to convert the signals (0-5V) to and from the micro and the other circuits.

Interfacing is one of the most fun parts of working with microcontrollers because a little bit of code can cause something really amazing to happen in the real world. It might turn on a bunch of lights, operate a motor, or sense and control a large machine. Interfaces make this possible and safe.

A Word on Safety

The circuit described in this page connects directly to the AC line. If you are going to experiment with AC line-powered circuits, you need to remember this very important fact: The AC Line Can KILL YOU! This is not a maybe or a sometimes. There is enough energy in even a standard household outlet to kill you nearly instantly if you happen to touch it in just the wrong way. So, in the interest of safety please follow these tips when working with the AC line:

  • Never touch a live circuit! This is the best way to avoid accidents. Just don’t touch or get near a live circuit. If something doesn’t work, fix it with the power off and then try again… don’t poke around when the circuit is on.
  • Don’t rely on a switch to turn your circuit off! The safest way to disable an AC device is to physically unplug it from the wall. Preferably put the plug where you can see it while you’re working on the circuit. After plugging and unplugging a circuit a lot of times it’s easy to forget if you’ve unplugged it this time. Have it in plain site so you can be sure at all times.
  • Keep one hand in your pocket! If you really must poke at a live circuit, do it with one hand in your pocket or behind your back. That way if you do end up touching something, your other hand can’t become a path for the current to flow through you. When current passes across your chest this can affect your heart in potentially lethal ways.

The AC Dimmer

The AC dimmer is a wonderfully efficient and simple device which can allow smooth dimming of a line-powered AC lamp or lamps. The parts are inexpensive, and relatively large loads can be controlled with a minimal amount of effort. Although there are dimmer which don’t use microcontrollers, (some cheap household wall dimmers) using a micro can make smoother dimming especially in the low brightness levels. It can also open a whole range of possibilities including special effects, networked or remote-controlled lighting, and so on.

AC Phase Control Basics

Most AC dimmers use the phase control technique to dim a lamp with very minimal energy lost. Small dimmers nearly all use TRIACs as the actual power control device. TRIACs are inexpensive and can control surprisingly large loads for their size. Part of the efficiency of these devices is due to the fact that they are controlling relatively high voltages. (compared with low-voltage DC circuits) The other part of the efficiency is that nearly all of the energy used goes into the lamp. By dimming the lamp this way the unwanted energy is simply never used. Old-fashioned dimmers used to divert the unwanted energy away from the lamp and waste it as heat.

First we must understand the TRIAC and how it works. Observe the diagram showing the TRIAC connected to a lamp. Normally the TRIAC does not conduct current. Just like a light switch that is off, the TRIAC is open and no current flows to the lamp. But if a small current is applied to the gate pin on the TRIAC, it will turn on and current will flow to the lamp just as if a light switch was closed. (a small voltage appears across the TRIAC while it is on) It only takes a tiny current on the gate to trigger the TRIAC with the gate input. The word trigger is very important, because the gate pin is not simply an on/off control. Once the TRIAC is triggered it will stay on forever, even after the trigger current is removed. It only turns off once the voltage across the TRIAC is zero.

What good is a circuit that we can turn on, but not turn off? At first this kind of setup seems unable to solve our problem until we look at what happens on the AC line. Because the line is AC, the voltage on the line keeps changing in a sinusoidal pattern. It goes positive for half cycle and negative for the other half cycle. This whole cycle lasts 1/60th (in North America) of a second. The beauty of this is that 120 times every second (after every half cycle) the voltage on the line (and thus across the lamp and TRIAC) will drop to zero. And thus the TRIAC will turn off! This means that if we want to keep the lamp on all the time, we have to keep triggering the TRIAC so that it conducts current for each half cycle.

But what if we want to dim the lamp? We need some way of controlling how much energy reaches the lamp. We could alternately turn the lamp on and off really fast. But once we trigger the lamp we’re stuck with it for up to 120th of a second. Unless we somehow know what’s happening on the AC line, we can’t dim the lamp properly. But if we know exactly when each half cycle starts, we can accurately control the TRIAC in a way that can dim the lamp. This is called: phase control. The following diagram explains how this works.

Since we can’t easily change the voltage of the AC line, the only way to change the brightness of the lamp is to have it receive less total energy from the line. This means that we need it connected to the line less than 100% of the time. One way would be to flash the lamp on and off, once every second. Technically this would cause it to use 50% of the power compared with it being on all the time. But we would likely see it as a blinking lamp instead of a dim lamp. But if we speed up this effect so that we turn on and off the lamp every half cycle of the AC waveform, we can achieve the same effect only much faster. In the diagram above you can see that for various brightnesses we simply wait some amount of time before triggering the TRIAC. For 50% we wait until the peak of the voltage, for 100% we turn on the TRIAC for the entire half cycle. Any brightness between off and fully on can be had using this method. The only challenge is to know exactly when to trigger the TRIAC during each half cycle. It must be the same point every time or the brightness of the lamp will not be stable.

AC Load Control Using a TRIAC

So suppose that the first thing we want to do is simply turn on and off the lamp, but not dim it. There are many applications where this might be all that is required. Traffic lights, warning indicators or light chasers on a marquee are all examples. If you want to control an AC load such as a light bulb from a micro, you need a safe way to control the AC line with the low-voltage digital signals on the micro. You need to both interface the 5V/0V signal with the high voltage of the AC line. But you also need to make sure that your micro is isolated from the line for safety reasons. If you decide to connect your micro to a computer, switches, or other circuits you definitely don’t want any part of the circuit having 120VAC on it.

For this we can use the circuit shown here. This is an optically-coupled AC load control circuit. That means that there is a physical barrier (using light) to interface between the low and high voltage sides of the circuit. By using an opto-coupler as shown here you can be assured of having several thousand volts of isolation between the control side (containing the micro) and the line side. (containing the lethal voltages) The circuit works as follows:

The opto-coupler (a MOC3010) contains an LED and a small photo-sensitive TRIAC. Both of these parts exist within the opto-coupler, which is sold as a small 6 pin DIP part. When the LED is on, the TRIAC is triggered. We use this small TRIAC to trigger a larger TRIAC which actually connects to the AC lamp. A resistor limits the current into the gate of the larger TRIAC. So now with this circuit, all that is required is to put a small current through the LED on the opto-coupler, and a potentially very large AC load can be controlled!

That takes care of half of the circuit.

AC Line Sensing – Zero-Crossing Detector

So, if all we need to do is turn on and off a light, the first circuit is really all we need. Just like lighting up a normal LED with a microcontroller pin, we can light up the opto-coupler’s LED (which is not actually visible to us) and the lamp will turn on. But if we want to dim the lamp we’ve already discovered that we need to have some idea of what’s happening on the AC line so that we can decide precisely when to trigger the TRIAC to create the phase control we want. This requires a zero-crossing detector. This is a fancy term which just means: “tell me when the voltage on the AC line is zero.” Check out the circuit here to see how this works.

The circuit I came up with is very inexpensive and works as follows. The AC line goes through some resistors to limit the current. The resistors are shown as two parts in parallel, but this is just to split the power between them since they may get a bit warm. The AC voltage goes into a bridge rectifier. This makes an AC wave into a pulsating DC wave where each half cycle is positive. This ingenious circuit works as an automatic switch by reconfiguring itself to flip over the negative part of an AC wave and making it positive. I didn’t invent it, but thank whoever did. Next the pulsating DC goes into another opto-coupler. This time the opto is going the other way, with the LED on the high voltage side. We need each half cycle to be positive otherwise the LED will only light half the time. This LED is turned on by the AC line. Whenever the voltage on the line comes close to approaching zero, the LED will fade out and go off. As the voltage rises during the next half cycle, the LED starts lighting up again. Once again this LED is not visible to us because it’s inside the opto-coupler. So now we have an LED that is nearly always on, except during the beginning and end of each half-cycle.

On the other side of the opto-coupler is a photo-transistor. This is just like a normal NPN transistor except that the base of the transistor is controlled not by current (like in a normal transistor) but by the light from the LED inside the opto. When the LED is on, the transistor conducts current. When the LED is off, the transistor turns off and looks like an open-circuit. We have one side of the transistor (the emitter) connected to ground (0V) and the other side (the collector) is “pulled up” with a resistor to +5V. We connect the collector/resistor junction to our microcontroller. The resistor ensures that when the transistor is off, the voltage seen by the microcontroller is about 5V. When the transistor is on, it draws a small current down through the resistor and pulls the microcontroller pin close to 0V.

This circuit outputs a signal that is 0V most of the time (when the LED and transistor are on) and close to 5V when the AC line drops near zero. (when the LED and transistor turn off) By adjusting the values of both the current-limiting resistor in the AC line side, and the pull-up resistor on the microcontroller side we can tweak how this circuit responds to the AC line. But the values shown here seem to work well for 120VAC.

You might find a use for this circuit by itself. For instance, it can detect when there is power on an AC line. You could use it to detect if AC power is applied to a circuit and use this data somehow in your program, send it to a computer, show an indicator LED, and so on. It won’t measure the voltage on the AC line, but will detect if it is active or not.

So now our microcontroller can trigger the TRIAC controlling the AC lamp, and it can also detect when the AC line voltage crosses through zero. Now comes the part where we make the actual phase control dimming. This is all done in software!

Phase Control Dimming in Software

To create phase control dimming in a micro, we don’t need particularly great CPU speed, but we do need quite accurate timing. Bad timing will result in flickery or uneven dimming. The dimming code needs to be synchronized to the AC line using the zero crossing detector. For my demo I used a hardware interrupt which goes off during the fall edge of the zero crossing wave. This signals the beginning of a half cycle and lets us prepare the dimming code. To prepare for dimming, a counter variable is set to 127 when the zero crossing is detected.

The dimming is accomplished by setting up a timer that runs at 256 times the rate of a half wave. Each time the timer goes off, the dimming counter is decremented and then checked to see if the desired dimming value is greater or equal to the dimming counter. If the desired dimming value is greater than or equal to the current counter, trigger the TRIAC. Leave the trigger pin on until the counter reaches zero. And make sure the dimming counter runs out before the end of the half cycle so there is no chance of triggering the TRIAC by accident at the beginning of the next half cycle.

You might notice that by moving linearly across the sinusoidal waveform using 256 steps like this, the dimming won’t be linear. Most lamps aren’t linear either so you likely won’t notice this as a problem. However, there is a fairly simple way to correct this if you prefer a different linearity to the dimming. By using a formula or a lookup table to map desired values to the actual phase control level you can correct the brightness curve to suite your needs.

For my demo I chose to use only 128 dimming steps, and this is what is shown in the example code below. This is more than smooth enough for a normal lamp, but you can make the resolution different depending on your needs. Try a more coarse control resolution to see what happens. Anything more than about 64 steps should be as smooth as you can detect with your eye.

Conclusion

Hopefully you learned something from this tutorial and I hope that you use and improve these circuits. If you find any errors or have ideas that I didn’t post here, please let me know.

Downloads

Below you will find the schematic and code for the AC dimmer demo circuit. Please email me with questions or comments.