picture of me inespot.net.
photos | career | travels | links | email | self | feed | rss feed
21625
  

Using the Computer to Switch Power

27 Comments: ( add comment )

Here, I'm describing an overview of my attempt to turn on and off an external AC-powered device (anything, from lights, to appliances) using the computer instead of unplugging the goddamn thing by hand. There are commercially available (and expensive) solutions for this kind of thing, but it's way cooler to do it yourself if you have a dedicated computer at home. I'm writing this from the point of view of a programmer with very limited EE experience (i.e. most CS students out there). By very little, I mean: you know what voltage, current, power, transistors and resistors are, but you've never actually used them in practice before, and want to know how in a very simple way (and may have even forgotten what they mean).

My motivation behind completing this little project started as the result of necessity (being the mother of invention)... My home DSL modem would periodically reset itself each day, and sometimes the router behind it would fail to acquire a new address, rendering my internet connection dead until I reached back there and unplugged the power-jack by hand.

Well, I quickly got tired of that crap.

First, on a high-level, here's the idea:

  1. Using a C program, you drive a signal high on the parallel port. (You can use the serial port if you want, but the parallel port has more data/ground signals on it just in case you want to expand this project into something bigger)
  2. The signal talks to a *very* simple circuit.
  3. The circuit activates a relay.
  4. The relay is connected to an extension cord.
  5. You plugin whatever you want to the extension cord for power.
  6. The light/appliance/device goes on (or off) based on whatever you send to the parallel port.

You'll need several tools for this job (all of them are available at radio-shack or a local electronics store). If you've never done this before, you're gonna end up getting all these things, because you're gonna want to test what you're doing several times along the way. If you don't get them, you'll end up driving back to the store a couple times unless you already know what you're doing:

  1. A multimeter
  2. "Hook-up wire" (skinny, red, solid wire. Frayed == bad.)
  3. A small bread-board (to help you test)
  4. A NPN switching transistor (radio shack type 2N2222A)
  5. A 4.7K ohm resistor
  6. Two diodes (radio shack type IN4003)
  7. A relay (which I'll talk about later)
  8. A DB-25 female connector (it comes with pins. get extras)
  9. Male-Male parallel cable
  10. A control board for mounting the circuit
  11. Soldering iron & solder
  12. A housing for the control board (to package your finished product)
  13. An extension cord
  14. Alligator clips
  15. Needle-nose pliers would be helpful.
  16. Electrical tape
  17. Assortment of wire-connectors
  18. Wire-cutters
  19. A changeable-voltage AC adapter or a 9-volt battery. (I prefer the adapter because I don't wanna have to worry about the battery dying, if you plan on using this over the long-term. The adapter has a little switch that allows you to change the voltage).
  20. Female power-connector for the adapter.
  21. Some patience

If you've ever spliced two wires together before, you probably already have many of the aforementioned tools lying around for random reasons (adapters, soldering irons and various kinds of cables and such).

So, now for some background information. I will describe these things in this order:

  1. First I'll give a *basic* refresher on power, current and voltage.
  2. Then, I'll talk about relays.
  3. Then, we'll describe the parallel-port / circuit operation
  4. Then, we'll go through a 5-step process.

Power, current, and voltage: Power = voltage * amplitutde (DC only).

DC power: the simplest kind. Comes out of batteries. Runs at a constant voltage. This is what comes out of the other end of your AC adapter.

AC power: runs at varying voltage. This is what the electric company sends you. Easier for them to get you power that way and let you convert to DC. Lights and AC adapters take this directly from the wall. Your computer's power-supply converts this into DC for the rest of the computer to use, resulting in DC coming out of the various ports in your system. Your household AC-power usually runs at 120 Volts and 15 amps.

Relays

As far as our goals are concerned: We want to use a DC-signal from the computer to switch on or off an AC-based extension cord, and anything plugged into it. This is what Relays do. Relays are mechanical - they having a moving part inside (called an armature). Cars use them. Big machines use them. Old POTS Telephone switching systems used them a lot back in the day. Relays are like BIG transistors. Transistors do something based on an input, except they work on small currents and small voltages. Relays operate on the same principle as a motor: they have an electro-magnet inside that energizes. Instead of repelling against another maget like a motor does to produce rotation, instead they move in two directions to complete a DC-circuit. Relays come in many different voltages and current combinations. When searching for a relay, there are 3 main variables which I searched for:
  1. The power required to energize the coil, anywhere from 6 volts to 12 volts. (The coil is DC, whereas the circuit the relay controls is AC)
  2. The number of contacts the Relay supports: i.e. the number of AC-switches that go on/off when the coil is energized. There is a naming system for these: SPST, DPDT, 3PDT, 4DPT. The last two letters mean "double throw", i.e. there are two circuits on the Relay: "normally open" (NO) and "normally closed" (NC). When the coil (which operates on DC) is energized, the armature opens one circuit and closes the other, and vice versa. That's what the "double" is for. The first two letters mean "Single Pole", "Double" Pole", "Triple Pole", and so on. This indicates *how many pairs* of double-throw AC switches the relay has. For SPDT, there are is one switch pair (i.e. a single NO / NC pair, or in other words, two circuits). 4DPT means that there are EIGHT circuits supportted by the relay. So when the coil is activated on a 4DPT, 4 of the circuits are open and 4 of them are closed.
  3. The number of AC-amps that the Relay can handle when it closes the circuit. As I mentioned before, your household typically provides about 15-amps, but your devices never use that much. They will at most use a couple amps.

I recommend buying a SPDT, 6-volt coil Relay. (or 9-volt if you're using a battery to power the coil). I also recommend making sure that the relay can handle 5 or 10 amps of current. Although a single device or appliance may not need that much current, you may want to plug other things into this project at the same time. Relays are only a few bucks, so, just get the bigger amps =).

Parallel Port and the Simple Circuit

So, now we can talk about how the computer is going to begin to drive this whole contraption of ours. The parallel port has 8-data pins and 8-ground pins. (Refer to the diagram below). The rest of the pins are not important for our purposes. The data pins are pins 2 through 9 and the ground pins are 18 through 25. Google for a picture of the port or look at your cable. The pins are probably labelled in *really* tiny numbers next to each pin.

The data pins source 5 volts of ~2 milliamphers of DC current. The problem with this scenario is that there is not enough current to activate the coil on the Relay described before. When we write our program and send the signal, we are going to want the data pin to activate +5 volts and "magically" turn on the relay. So, if the data pin doesn't provide enough power, where do we get it from? We use a second power adapter to do it (or a battery). The way this will work is that the data signal will drive a single transistor (i.e. the smaller relay). When the signal comes into the transistor from the parallel port, the transistor will "allow power" from the second power source to activate the Relay.

So, again on a high-level:

  1. C-program turns on parallel port data pin
  2. Data pin triggers a transistor
  3. Transistor triggers a Relay
  4. Relay turns on power to the extension cord
  5. Anything attached to the extension cord comes alive (or goes off).

NOTE: There are THREE power sources mentioned in the above list. The first is the signal from the parallel port. The second source powers the relay (from an adapter or battery). And the third powers the external device that you're interested in.

The Circuit

Here's a picture I drew of the circuit: (Click to enlarge)

Step 1: Tripping the relay.

Now let's look at the diagram I created above. First, we'll start with the power source on the top-right of the diagram. The Relay is the easiest part of the circuit. Take the relay you bought and connect your power source (adapter battery) to the positive and negative contacts for the relay's coil. When you complete the circuit, the relay should make a loud "click". That sound is the armature inside moving. When you release the power source, the relay will snap back. As I described before, this is causing the armature to disconnect from one Pole and touch the other pole. Assuming you have a SPDT relay like the one in the diagram (all relays have diagrams on the product that tells you which contact is "normally open" or "normally closed"), your power source would have cause the armature to create a simple circuit between the "normally open" contact and the "common" contact. Removing the power source will restore the circuit between common and "normally closed", i.e. with the armature at rest.

You can test this by grabbing a light bulb or lamp and running some wires between the contacts and the lamp and a second power source to successfully control the first power source.

NOTE: I recommend a 9V battery or a 300Ma adjustable-volt adapter from the store to control the postivte and negative parts of the relay. For the NO, NC, and Common contacts, simply use a regular AC lamp or light bulb. In the end, this will be an extension cord, instead of a light bulb, so that you can plug anything into the relay-controlled circuit. Don't send a voltage into the +/- of the Relay at a higher voltage than the relay can handle, or you'll end up buying another one.

Step 2: Testing the Parallel Port

Whip out your multimeter! Turn the dial to test voltages around 5-volts. Plug in one end of your parallel cable into the computer. Now, compile this C program, reproduced here:


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/io.h>
  5.  
  6. #define base 0x378 /* /dev/lp0 */
  7.  
  8. main(int argc, char **argv) {
  9. int value;
  10.  
  11. if (argc!=2)
  12. printf("Enter a number between 0 and 255.\n"), exit(1);
  13.  
  14. if (sscanf(argv[1],"%i",&value)!=1)
  15. printf("Parameter is not a number.\n"), exit(1);
  16.  
  17. if ((value<0) || (value>255))
  18. printf("Enter a number between 0 and 255.\n"), exit(1);
  19.  
  20. if (ioperm(base,1,1))
  21. perror("ioperm");
  22.  
  23. printf("Setting base %x to value %d\n", base, value);
  24.  
  25. outb((unsigned char)value, base);
  26. }
  27.  

It's a very simple program which uses the outb call to set a value high on the eight data pins of the port. Each pin is one bit of a whole byte. If you run the program with "255", all 8 bits will be set, and so forth.

Now, take your multimeter, and using the diagram, connect the positive pole to Data Pin 0 and connect the negative to Ground Pin 0. Run the program with "./program 1" to set a value of 1 on the parallel port. Your multimeter should succesfully detect a +5 signal coming out of the data pin. If it worked, then we're in business! I successfully used this program on a 32-bit 2.6.18 Linux box, so I'm sure it'll work on your Linux box =)

Step 3: Using the Parallel Port to Drive the Relay

Now, we have to setup the rest of the circuit. This is the tricky part, because it requires getting all the connections right.

The Transistor. So, your whole life is surrounded by these tiny little things, right? You've got that NPN transistor I mentioned earlier (preferably some extras) and you're ready to put it to work, right? On the package, you should see a diagram of the transistor for each of the transistor's 3 pins: B (base), C (collector), E (emitter). The package's diagram will tell you which pin is which. So, here's how this works: the NPN transistor is a little "AND" gate, basically - except it works on "power on / off" instead of bits. The input power from the AC adapter or battery connects to the "collector" pin of the transistor. The input power from the Parallel Port's Data Pin connects to the "Base" pin on the transistor. Think of the collector pin as always have a '1' input constantly from the AC adapter. The difference is the parallel port pin. When you run the program and drive +5 volts on the data pin, the transistor will activate, satisfying the "AND" of the transistor. When that happens, transistor will "allow current" from the collector pin to flow through the "emitter" pin. The current going into the collector and out of the emitter has way more amps (from the adapter) than the amps from the parallel port, and that current will cease when the parallel port is turned off. That's what those tiny transistors are for: they turn a smaller current into a much larger current.

And, as you've probably guessed, the larger emitter current (originally from the adapter) is what connects to the Relay.

NOTE: be careful connecting the right power sources to the transistor. Transistors burn out easily and will silently fail. Make sure you buy extras.

Putting it on the breadboard

The way it works is: the two top rows are connected, usually accepting current (Vcc). There are two rows in case you have two power sources. The two bottom rows are also connected, but they're used to do the opposite and sink the current back into the power source. Finally, each of the vertical rows in the middle are connected. But they are not connected across the gap. The important thing to remember is to create your circuits according to the connections, not in a visual manner. Trying to duplicate the geometry of the circuit from a circuit diagram doesn't make any sense, because the breadboard's connections don't orient the same way, so you'll have to translate the circuit diagram connection by connection in a step-by-step manner.

Now, BE SURE that you bought those diodes and resistors.

Diodes are used to make sure that current only flows in one direction. They're vital. Don't use the breadboard without them. Otherwise, you'll cause your transistor to silently fail or you screw up the coil-mechanism inside the relay. The diagram on the diode package will tell which direction to put the diode according to my diagram. There are two diodes in the diagram - make sure you put both of them in there.

Resistors are equally important. They restrict the flow of current to that at which the transistor can handle. You only need one for this project

Here are some recommendations for putting all the connections together on the breadboard:

  1. Use the "hook-up-wire" and alligator clips extensively. DO NOT use regular-old everyday copper wire. It frays. You will damage the breadboard if you try to shove copper wire in there. Buy these tiny little copper alligator clips from the store and attach 3 to 6 pairs of the hook-up wire / alligator clip combinations. You can use the clips to connect to the relay, or the power sources, or the parallel port pins, or anything that cannot attach directly to the breadboard. The only thing that really attaches to the breadboard are the power source from the adapter (using hook up wire extensions) and the diodes, resistors, and transistors. Everything else will need easily-detachable connections for testing.
  2. Use your multimeter on the transistor before attaching it to the relay. The relay is the last part you should connect to the transistor. Connect the multimeter to the collector and emitter pins of the transistor, and run the program. If you see current flowing, then you've made great progress!
  3. Take baby steps. Test everything! Test, test, test. Because if you connect one thing, and don't test it, you'll immediately have cascading problems because something down the line wasn't connected right.
  4. Study the diagram. I re-drew that diagram for the lay-man as a more descriptive collection of diagrams from other sources you may have run across on the internet. Remember: there are 3 power sources and 3 individual circuits.

Step 4: Put it to work!

Once you know the transistor is working and is driving the relay, take an extension cord and splice it on to the relay's common and NC (closed) pins. (The Normally Open pin will always remain unused). Then plug the extension chord into the wall (i.e. the 3rd power source). At this point you should have two sources from the wall and one from the parallel port. Then plug in a light or something (or your DSL router!). Normally power should always be flowing through the Relay. When the parallel port is activated, the relay will disconnect the AC circuit on the extension cord. You can then write a simple shell script or C program to turn off the extension chord power for arbitrary lengths of time and another program that detects when your internet connection is out. You can even do stupid things like hook up all the lights together in your apartment and turn them off with your computer. Or you can keep going and make more complicated circuits!

Step 5: Making this permanent

When you're finished, of course you need to get out your soldering iron and make this permanent. In order to do this, you're going to need a female parallel port connector and a power connector so that you can make this whole contraption detachable. At this point, you probably have wires everywhere. The electronics stores sells all these parts, including large, black plastic housings and circuit boards. You should solder all the pieces onto the board and carve out places for the connectors so that you can plugin things into the whole circuit in case you decide to shift things around. For me, that was the most satisfying part of this project - when you actually have that classical "black box" sitting in front of you with all the components soldered properly inside of it.

I hope this has been as helpful and informative for you as it was for me. I've also posted a few of the pictures I took documenting the process as I created the finished product located here. Feel free to contact me if you have any questions about this tutorial. I'd be more than happy to help!

Here are some of the links I used to help me learn and put this tutorial together:

  1. DslMon -- Power Cycle your DSL modem automatically whenever the net goes down
  2. parallel_output.html
  3. Shavano Music Online - Using Mechanical Relays - Part 1
  4. Parallel Port Relay Board
  5. Serial port control of power switch | Bolis
  6. Relay Specification Sheets
  7. Coffee Making: Hardware
  8. Controlling a relay and motor with a serial port | Windmeadow Labs
  9. How to Convert Watts to Amps Simplified -- Converting Amps to Watts the easy way
  10. Vcc, Vdd, Vss, etc.
  11. Transistors
  12. Diodes
  13. Resistors
  14. Transistor Switches and Amplifiers
  15. Welcome to the Electronics Club

27 Comments: ( add comment )

Michael during January 27, 2008, 4:40 pm  

If this HOWTO has helped you, please leave any comments you think would be helpful to others trying to do the same thing. Thanks!

moiz during January 28, 2008, 3:47 pm from chatshow119 ** [at] *** hotmail.com  

give the value of resistor

Michael during January 28, 2008, 4:53 pm  

The resistor is a standard 4.7K ohm resister that you can find in a comprehensive electronics store.....

joel during January 29, 2008, 8:41 am from Hidden  

how to input data to the computer using rs 232 connector?

Michael during January 29, 2008, 1:24 pm  

Instead of the "outb()" call you would use the "inb()" call. (Do a man inb).

And instead of specifying 0x378 for the parallel port, you would need to find the right port address.

Keep in mind that the serial port only has one pair of datalines (in and out). The rest of the pins on 232 are stricly used for signaling.

Ishtiaque Hossain @ Bangladesh during January 30, 2008, 10:09 am from ishti_anon_48 ** [at] *** hotmail.com  

The voltage and current at the parallel port varies from one computer to another. The 4.7k resistor may not provide enough current to the base of the transistor. In case the circuit doesn't work, try altering the resistor or shorting it.

zild during February 1, 2008, 11:02 am from Hidden  

how can I turn off or set a pin to 0 of a parallel port...for example is pin D0 for the data port

Michael during February 1, 2008, 11:50 am  

Each pin corresponds to exactly one bit of a whole-byte value. So what that means is: If you set run the program with value "7", for example, then pins 0,1, and 2 will each have the value "1" in Binary: i.e. the decimal number 7 corresponding to the binary number 00000111 (one binary digit for each pin, i.e. a byte).

So, for pin 0, *any* even-numbered value will produce a zero on that pin. Any odd-numbered value will produce a one on that pin.

Gofast @ mumbai during February 21, 2008, 6:03 am from Hidden  

hi guys i have tried a program sending value 0x00 and later sending 0x01(alterantely) but my parallel port just shows a constant reading of 4.83v at data pin0 WRT pin18(GND). i have run the program on windows xp. using turboC. any suggestions????

Michael during February 21, 2008, 9:27 am  

4.83v is a *good* thing. It worked =). Now you wanna move on to the next step and connect it to the rest of the circuit.

Did you think that was bad or something?

orangesquid @ Wilmington, DE, USA during March 18, 2008, 8:55 am from Hidden  

I've thought about doing this to power on/off the various computers in my parents' basement (since I no longer live there). They kindly let me keep them there, but sometimes ask if I can cut back some of the power usage.
Now, for some machines, they're definitely "on" more often than "off." For other machines, it's the other way around (in which case, I could flip the relay wiring, and have a daemon to keep the parallel port output steady).
What would be more elegant, though, is an external RS flip-flop circuit with either a LiMH or Lead-Acid battery backup (yuck, requires battery controller circuitry for the occasional charge cycle) or a capacitor bank, since I wouldn't want occasional noise de-activating a relay for a normally-off machine. I could plug it into a UPS, but a capacitor bank would be a little easier IMHO. The question then, is, how large would the capacitor bank have to be to supply a nominal switching current for the relay. I might play with some RC-decay curves and look at some relay spec sheets and see how it looks.
What do you think? Are there any relay-like devices that have some sort of hysterisis, so I would only need to momentarily pulse the relay to flip it between states? (Say, for example, maybe something with two coils. Basically, a relay flip-flop with no steady-state power consumption...)

Job during July 11, 2008, 12:43 pm from Hidden  

Why are all the grounds connected together?

Job during July 11, 2008, 1:00 pm from Hidden  

Very nice tutorial, btw. Thank you. I will be using USB 5v for my power instead of an adapter or battery: 500mA should be enough to power the relay.

Michael during July 12, 2008, 10:23 am  

Cool. Glad to be of assistance.

Only ground2 and ground3 have to be connected because of the transistor. You have to siphon off some of the sink'd current from the transistor back into the computer as well as the power adapter. Since there's only one ground coming out of the transistor, you then split the ground up, which is why they appear connected.

matt during September 12, 2008, 3:49 am from nofxkid_86 ** [at] *** yahoo.com  

hi.. im a electrical engineering student from Malaysia.
do you know how to use visual basic for this project?
what is the code?

please help me. this is my final year project.

sorry my bad english. :)

Michael during September 12, 2008, 5:08 pm  

In google, use the following keywords:

"access parallel port visual basic"

This returns many, many examples of visual basic sending a value to the parallel port.

Iván Caballero Cano during September 12, 2008, 6:51 pm from ivanhalen77 ** [at] *** gmail.com  

What versión of "C" do you use to compile the code?

Michael during September 12, 2008, 7:13 pm  

Regular C (i.e. not c++).

In Linux, this is of course gcc.

In windows you need a basic C compiler.

matt @ Malaysia during September 12, 2008, 7:36 pm from Hidden  

Thank you Micheal! =)

Iván Caballero during September 12, 2008, 11:21 pm  

Excuseme Again, but in your case, what is exactly the version of C that you use to compile the code? Borland C 2.0? Turbo C? Exactly what version? There are many versions of C, but I want to use exactly that you use Thanks :)

Michael during September 12, 2008, 11:30 pm  

I apologize. I do not use Windows. Haven't used it in years..... I'm afraid I don't have experience using a C compiler in that respect.

The primary difference, however will simply be the system call used to access the parallel port: specifically, you will need to find the windows-equivalent of "outb" and "ioperm" system calls.

Once you find those, you should be able to use *any* C compiler. The code I wrote is very basic C code and should compile under any system as long as you change the system calls as I described...

On the other hand, I recommend searching for a FREE program on the internet that has a graphical user interface that will simply allow you to "set values" on the parallel port itself without writing a program at all.

Basically you just want SOMETHING to control the port - so if you can find a free program (and I'm sure there are many), then that will be sufficient to complete the circuit.

Iván Caballero during September 13, 2008, 1:13 am from ivanhalen77 ** [at] *** gmail.com  

Do you compile the code in Linux?

Michael during September 13, 2008, 1:31 am  

Yes.

abee @ audiblecode.wordpress.com during October 17, 2008, 7:23 pm from Hidden  

This is a very great tutorial, i world like to ask a few questions.(i am a CS student too). I can see that in your project you were controlling only one device/ or an extension board that controls the device. how world you extend this to control multiple device independently. I need a circuit on that. and also allowing the circuit to give the computer feedback as to what is going on in the circuit. Thanks.
ps. Do you have any information about and IC that i can use as a radio transmitter and also any information about PIC's Thanks again

Michael during October 19, 2008, 5:17 pm  

On your first question, you should simply use the remaining seven devices on the parallel port. To get feedback (assuming, as you said, you're using an IC to do something more complicated), you would need to connect wires from the IC output to the input pins of the parallel port. If you do that, you would extend the C program I've provided to use the "inb" system call instead of the output system call. The, once you read the value, you would interpret one of the 8 bits (per pin) to signal to you as to what is going on with the logic in the circuit.

I do not have an IC recommendation, however. I have only played with very simple IC chips that employ basic and and or gates. I'm guessing you're using timing circuits and that kind of thing. For advice on those kinds of IC's, I'm going to refer you to google =)

Dan during October 21, 2008, 7:43 pm from DBPythonmaster ** [at] *** gmail.com  

Unfortunately, this doesnt work in Windows natively properly. Windows doesnt allow C to access parallel port, because windows sucks. There are alternatives, but they are not as elegant as C. Linux is your best bet for this.

viju during November 4, 2008, 2:13 am from vijumohan ** [at] *** rediffmail.com  

Hi..
can you plse help me regarding parallel port program in C.....i want to test output of 7 meters at a time using c program ...i want to get the output pulse in a graph...so that we can see which pulse is showing error...now am taking each 7 outputs to each each d0 to d7 of parallel port....and from that am taking pulse and showing in graph......in this stage i got stuck...if u have any idea how to do this plse help...as i dont have much knowledge in c language i dont how to show this 7 pulse in a graph at a time....if you have any sample code plse help....its urgent...ASAP...

vijunambiar@gmail.com

Name:
Email:
Website /
Location
:
Hide Email?       Yes No
Simple Math: + == ?        
Email Replies? Yes No

Site written and designed by: myself       

hinespot.net: ... tales of an lowly grad student peon