*** I've made a few updates to this instructable since Aug 2014 ***

I decided to share this information so that it might help others who have been struggling to do similar things with their Arduino. I've only recently gotten involved with the Arduino. I bought R3 versions of the Mega 2560 and the Ethernet Shield a couple months ago in order to learn and play. Soon after getting them, I had an idea that I could automate some things around my home. I'm not very far into the automation, but so far I have my Arduino serving up a simple web page (with the help of other instructables) which gives me the option to turn lights and ceiling fans on/off as well as power up/down my PC and HP Media Vault. I'll call the Media Vault MV for short.

Forgive me for not taking more pictures of the work in progress. I thought about making this instructable after most of the work was completed.

It's not that hard to turn on lights and ceiling fans manually. I decided to include the PC and MV because I often stream media from each of those to my smart TVs, home theater receivers and Blu-ray players. I don't always leave the PC or MV running, so at the time I need to use either, I can turn them on using my Nook tablet, or a smartphone or computer in the home. Anything on my home network with a browser will do.

I have to give some credit before I forget. I learned quite a bit from Beginner Arduino and Intermediate Arduino: Inputs and Outputs by amandaghassaei, and from Control an LED over the internet ... by CDCosma. My Arduino's web page is largely based on that from CDCosma's instructable.

I have to admit, my start with Arduino was pretty rocky, as my first Ethernet Shield was defective and it wasted lots of my time and effort.

If you are new to Arduino, I don'’t recommend that you start with my i'ble. I don't intend to give you all the information you need from A-Z. Please refer to the resources linked above, especially those by amandaghassaei for the basics of Arduino and to open your mind to the possibilities of Arduino. Without some background on Arduino, relays and switches, not to mention networking and wiring, some of this i'ble may not make much sense.

I will show you how I use my Arduino to turn on lights, ceiling fans and trigger my PC and HP Media Vault model MV2020 to power up or shutdown/suspend.

My PC’'s power management is configured for suspend to disk or hibernate, and the default action of pressing the power switch on its front panel is to hibernate. The MV does not support advanced power management and completely shuts down from a booted up state when the power switch is pressed. Update September 2014: I've switched my PC from Windows to Linux and hibernation is not supported, so pressing the power button shuts down. I've also done away with the shutdown prompt, so when I decide to shutdown, I don't have much chance to change my mind. But, this way when I use the Arduino's web page to shut down, the PC does shut down.

My Arduino's control of lights, ceiling fans and PC is accomplished with the use of the Sainsmart 8-channel 5 v relay board. My PC and MV are controlled by external reed relays connected to the front panel switch wiring of each.

Step 1: Disclaimer and Warnings!


I cannot be held liable and responsible for any fines or legal case which may be levied against you due to local codes or other reasons, or any damage/loss of property, life or limb that may occur as a result of reading this instructable.

  1. I reserve the right to be wrong. But, please feel free to post a comment. I do strive to be accurate, and a good way to learn is from the experience and knowledge of others. I feel that is part of the great spirit of Instructables.
  2. This project requires working with the electrical wiring in your home. There is a huge difference in the dangers of working with 110 v AC versus 220 v AC in many other countries. They both can kill, however, 220 v AC is much less forgiving. A callus on your fingertips may save you from catastrophe with 110, but not as likely with 220.
  3. This project requires going into the attic, or in the crawl space under your home. There are many hazards of this type of activity. If you live in a home, condo or apartment that you don't own, I strongly urge you not to attempt this on property owned by someone else without their full permission.
  4. This project involves soldering, although you could choose other methods of connecting wires. If you do any soldering, you should be aware if your solder contains lead, and of the dangers of introducing lead into the body, including inhalation of lead vapors. Soldering poses dangers of injury and fire caused by molten solder and a hot iron.
  5. Read your local/state or other governing entity's electrical codes to be sure you are wiring/connecting to their specifications to avoid possible fines. Those codes are also a good general guide for safety when working with your local power voltages and wiring.

Difficulty Warning!

This is a moderately difficult project. If you have at least some experience at home electrical projects (changing light bulbs does not qualify as a project) like replacing or upgrading electrical switches, light fixtures, adding an electrical outlet to a circuit, and you are also experienced working in your attic or crawl space, and especially dropping wires down walls, then you should be able to accomplish the most difficult and labor-intensive parts of this project. It is a good idea to consider enlisting the aid of an able-bodied friend who has similar experience, but I performed all aspects of this project entirely on my own.

Attics: Some attics have plenty of space to move around and work within, while many are very cramped, some even not tall enough to walk in so that you must crawl around. It is difficult to crawl in a cramped space while carrying tools/equipment and trying not to slip off a joist or poke a knee or foot through a ceiling. In an attic you risk stepping in the wrong place and damaging or even falling through a ceiling and possibly injuring or killing yourself. You could even step on what looks like a safe, sturdy place, such as a decked part of your attic, but that decking maybe too thin to support your weight, giving way similar to sheetrock. You could possibly cut into the wrong electrical circuit in your home by mistake, one which you did not turn off at the breaker, causing anything from a slight burn to your skin, a cut or gash from quickly pulling away from danger/sparks, to possible fire and damage to property or loss of life (yours by electrocution or someone else's by fire). Please don't attempt to do these things if you have never done them before. Hire a licensed electrician to do the electrical wiring parts of this project. It may cost a bit, but you'll be glad you did it safely. Also, there are likely sharp objects such as nails, sheet metal edges, ventilation ducts and supports, or building debris that could pose hazards for you. There is a slight risk of running into a rodent making a home in your attic. Some rodents will be more afraid of you than you are of them. But, others like squirrels, may become aggressive if they feel cornered and in danger.

Crawl Spaces Under Homes: The crawl space under some homes can be cramped. Some may have ample room to walk around upright, or while being slightly hunched over, but many have less than 2 feet of clearance between the ground and the floor joists. There may be sharp objects such as nails, concrete pilings, sheet metal and pipes that could be hazardous. There is a somewhat greater risk than in attics that you could find a rodent or small animal in your crawl space. Snakes have been known to take up habitat in these places. All of these possibilities and more exist, and you should pay attention at all times.

Step 2: Materials and Tools List

This is quite an extensive list. I didn't buy all these tools and materials just for this project. I've owned many of the tools for years.

Materials and tools you'll need to pull of this project as I did:

Arduino Mega 2560 R3 board (about $40 from Amazon)

Arduino Ethernet Shield R3 (about $30 from Amazon)

An enclosure for your Arduino to protect it from shorts and dust (I started making one from plexi but have not finished)

Sainsmart 8-channel 5 v relay board (about $18 from Amazon)

Arduino IDE software for uploading your sketch

PC or laptop running Windows, MAC OS or Linux with a USB port for uploading to the Arduino

A wired or wireless home network to connect your Arduino's ethernet shield so it can be accessed by your other network devices.

5 v reed relay(s) if you want the Arduino to trigger a PC to power up. You'll need 1 for each PC. (price ? I salvaged mine)

Update: resistors, diodes, micro switches (tactile button switches)

GE breaker box (I used a 4-breaker model from Home Depot costing about $11)

GE grounding bar (Home Depot about $4)

Adapters for wire to enter the breaker box without damage (Home Depot for under $4)

Stud finder

Sheetrock or wall board saw (Home Depot for $10)

carpenter's level

tape measure

Hammer, nails or screws (drywall or deck screws work well) and scraps of 2" x 4" wood to support breaker box

Tube of Liquid Nails to attach 2" x 4" wood pieces inside wall. (You can't get a hammer or screw gun inside the wall without making the hole for the box bigger than you really want.)

Silicone caulk to seal opening around breaker box.

14-2 NMB electrical wiring with ground. If your wiring is larger, like 12-2, use larger gauge wire

various sizes of electrical wire nuts

combination wire cutter/stripper/crimper

adjustable box cutter for stripping electrical cable sheath

reliable digital multimeter

good lighting from either a flashlight, headlamp or shop light for working in attic or crawl space

lineman's pliers (handy for cutting 14-2 NMB with ground, difficult to cut with small cutters)

black electrical tape

prewire outlet box(es), sometimes called 'new work', to conceal electrical wiring splices (Home Depot for $.49 ea for single-gang box). You'll need 2 for each splice unless there is enough slack in your existing wiring. If you can't double up about 4-6" of wire, plan on using 2 boxes with 1 new section of cable between them.

blank wall plates to cover wall boxes concealing spliced electrical wiring in attic or crawl spaces

postwire outlet box(es), sometimes called 'old work', for running/terminating control wires if your project is as spread out as mine

Cat5 and/or Cat3 wiring (price ? I've had this on hand for years)

soldering iron and solder

heat shrink tubing for solder splices

solderless breadboard (I got a 750-point board from Amazon for under $15 including some of the jumper wires below)

jumper wires (male to male - I found an assortment of lengths on Amazon for about $5)

jumper wires (male to female - I found a nice 40-wire ribbon on Amazon for under $6)

Drill and various wood/metal bits from 1/8" to 3/4" sizes

6' flex bit for drilling through wall cap and fire break (if present)

12' to 25' fish tape for pulling wire down walls

Roll of fairly strong pull string to run for possible future wiring needs

Needle-nosed pliers

Screwdrivers of various sizes, both flat and phillips heads. A jeweler screwdriver kit came in handy for me to connect the wires to the relays. (Prepare to do this with the breaker(s) off, or at least before you've wired into existing circuits)

Gloves (for working in attic or crawl space, they help to get a good hold on a joist covered in fiberglass insulation, also to give you a bit of insulation from electricity in case you should manage to push your fish tape into the top of a switch or outlet box)

Respirator mask (to keep from inhaling fiberglass particles floating around in the air in your attic)

Footwear providing good support and grip for climbing around in your attic

Safety glasses/goggles

You may also need:

Modular wall plates and pop-in jacks to terminate control wiring on your wall plates. (I already had wired network, phone or TV outlets where I ran my control wiring, so I didn't need to open up any new holes in the walls other than for the new breaker box. The wall plates are usually pretty cheap, but if you decide to go with modular jacks that pop in to the wall plates, go with sets of the same brand or you may have trouble getting them to pop in or stay in place, and these can run up your bill depending on how many you go with. Some pop-in jacks alone run around $5 each, so I am glad I went through that expense years ago already. Where I ran new wiring for this project, I soldered my wires together in most cases. Where I needed to run wires out from behind a wall plate, I just ran them out an open hole in a multi-position wall plate.

Something else you'll need lots of:

Patience, time and concentration, good balance, a clear mind, some digital (meaning fingers this time) dexterity, maybe even bug spray in case you come across ants, bees, wasps. Take lots of notes and make schematic drawings of how you plan to place and connect your parts to help avoid surprises. This will also help you troubleshoot when something doesn't work.

Step 3: Plan What to Control With Arduino, and How to Do It.

You should plan exactly what you want to control with your Arduino, and exactly where you want to place all the parts of your project. Knowing that and how you plan to use your project is key to having all the parts that you need. In my case, as far as things that require switching of house current, I am only planning to control lights and ceiling fans, so the 8-channel relay was my choice of interfaces between the Arduino and electrical circuits.

If you only want to control very low-current, low-voltage circuits like LEDs, then you don't need the relay board. Keep in mind that the Arduino's IO pins are rated for a very small amount of current at 40 mA, about the amount of current required to illuminate 2 small LEDs with proper current-limiting resistors. I measured a draw of 1.5 mA (surprisingly low) from my Sainsmart relays, making them ideal for my application. But the relay board 5 V power draws over 150 mA, making it ideal for a separate power adapter of its own. I haven't found current-handling specs for anything more than the IO pins. I've been running my relay board powered from the Arduino's 5 v pin for a few months continuously without issues, but this might be ill-advised. You don't want to overload the Arduino with higher current draw than it is rated for because you will burn it up quickly (either the internal circuitry to the overloaded pin, or the whole board) or shorten its life significantly. I did experience relays that wouldn't engage when I used a different power adapter.

Update August 2014:

I decided to power my relay board separately to take unnecessary load off the Arduino's voltage regulator circuit. To do this, I used two AC-DC adapters (wall warts); one for the Arduino and one for the relay board and switch circuit board combined. I had an extra 7.5vdc adapter from an iHome iPod dock/alarm clock/radio that is rated at 2A; I use this for the Arduino, plugged into its DC power jack. I salvaged a 5vdc adapter from an Iomega zip drive that is rated at 1A; this one powers the relay board and switch circuit board. I had an extra DC power jack from a project from years ago matching the size of the barrel on the zip drive adapter's cord. I soldered and heat shrinked wires to that jack and ran those to a + and - rail on my solderless breadboard. I've plugged in the wires that connect to the closet-mounted relay board's VCC and ground of the relay board in the closet to the respective rail of the breadboard, as well as a jumper from a ground pin of the Arduino to that - rail, and the + and - on the circuit board containing my new tact switches to that rail. The two - connections must be tied together and to the Arduino ground for this to work correctly.

-End of update-

A safety feature of the Sainsmart board is that each relay requires a digital 'LOW' signal or ground to trigger the relay to engage, while the absence of a signal does not engage it. This is so that if you lose/regain power or for any reason your Arduino resets, all relays should start up in the OFF or disengaged position. But, your Arduino sketch also needs to take this into account. Each output pin of the Arduino that will control a relay attached to an appliance running on house current should be initialized in a 'HIGH' state by your sketch, which ensures its relay is disengaged. Otherwise, while you are away from home, if your house loses power for any reason (storm, power pole hit by car), when power returns the Arduino would trigger all your relay-controlled lights to come on, posing a potential fire hazard.

Here is the layout of my project:

Arduino board and ethernet shield reside on a chest in my master bedroom. A new breaker box concealing my relay board was installed in a closet wall about 12' from the Arduino. My office, where the PC and MV sit, is about 25' from the breaker box. Master bedroom ceiling fan and light controlled by Arduino is adjacent to the closet where my relay board/breaker box are located. Two 14-2 NMB cables with ground run from a splice point in the attic just above the master bedroom wall switch to a point about 10' away, where they drop down the closet wall and into the breaker box where the relay board is mounted. Living room ceiling fan controlled by Arduino is also adjacent to the closet where my relay board/breaker box are located. Two 14-2 NMB cables with ground run from a splice point in the attic near the ceiling fan to a point about 15' away, where they drop down the closet wall and into the breaker box. One of these cables is for 'future use' in case I add a light kit to the ceiling fan. Two 4-pair cables run between the Arduino and the Sainsmart relay board to power the relay board and control its individual relays, and leave the option to add another 4-channel relay board in the future. One 4-pair cable runs between the Arduino and the office to control switching on/off the PC and MV by connecting to an existing low-voltage circuit. One existing ethernet cable (Cat5) runs between the Arduino and the office to connect the Arduino Ethernet shield to my router. I already had an ethernet cable for a computer that I previously used in this location, so I didn't have to run another cable.

The first image above shows this basic layout of wiring and placement of equipment throughout my home. I may get criticized about all the wiring I chose to run. Years ago, I wired my home for 10/100 ethernet when everyone else was wasting money on 802.11a/b Wi-Fi that was slow and had little range. I’ upgraded the wiring over the years to support gigabit ethernet for my MV and a couple of PCs. Wi-Fi routers/access points are much better now, and I do use 2 of them in my home. But often it is much cheaper to go wired than wireless. I do plan some upgrades and future additions to this project using RF modules if I can find components that I like at reasonable prices, but mostly this will be used only for the high-current devices. The second image above illustrates the network and control wiring of my project. The third illustrates the electrical wiring involved in the project.

After playing around with the relay board to see it successfully turn on a lamp, it became even more obvious than before that the relay must be concealed somewhere safe since it will have live house current and some bare contacts. I couldn't think of a better way to hide the relay while keeping mindful of the hazards than to put it in its own electrical service panel/breaker box. Even something simple like checking the tightness of the screw terminals on the relay board with a jeweler's screwdriver will 'light you up' if you don't insulate yourself properly or shut off the breaker first. The thought of this happening is how I decided on the breaker box mounted in the closet.

To operate the relay board is fairly simple. My 8-channel board has a header of 10 male pins. With the header side of the board facing you, from left to right those pins are:

  1. Ground
  2. Relay 1 trigger
  3. Relay 2 trigger
  4. Relay 3 trigger
  5. Relay 4 trigger
  6. Relay 5 trigger
  7. Relay 6 trigger
  8. Relay 7 trigger
  9. Relay 8 trigger
  10. +5 v

The fourth picture above illustrates the layout of the Sainsmart relay board, although viewed from the opposite side of the board as the pin header.

The Arduino has a +5 v pin and five ground pins. With a power adapter or USB powering the Arduino, connecting the Arduino's +5 v and a ground pin to +5 v and ground on the Sainsmart board readies the board for service. Then, all it takes to energize any of its relays is to connect a digital 'LOW' or ground signal from an Arduino output pin to the correct trigger pin on the relay board. Each relay is opto-isolated, isolating your Arduino from downstream circuits connected to the relay. When given a digital 'LOW' signal, its NO (normally open) terminal comes into electrical contact with its COM (common) terminal. While the relay is not energized, either when the Arduino and relay board are power 'OFF' or the Arduino is providing a digital 'HIGH", the NC (normally closed) terminal is in electrical contact with the COM terminal, so be sure you wire yours the way you intend to avoid surprises. The relay is basically an SPDT (single pole double throw) switch, meaning it connects one pole, the COM terminal with one of two other contacts. COM is always in contact with either the NC (digital 'HIGH') or NO terminal (digital 'LOW').

I have my relays wired on the ‘business’ end with power coming from the wall switch connecting to the relay’s NO terminal, and the load (ceiling fan or light I'm turning on from the relay) connecting to the relay’s COM terminal. Always switch your HOT wire, never switch neutral. By only connecting a wire which serves as the HOT to a switch terminal, you reduce the chances of someone being electrocuted when working on or even just using the circuit. Never switch a circuit using its neutral, because even though taking away the neutral from a 110 v appliance may shut it off, it will still have live voltage on it up to the point where the neutral path is open at the switch. And, switching the neutral on an appliance correctly wired to a 3-prong plug to connect the appliance to HOT, NEUTRAL and GROUND will almost never turn the appliance off.

Step 4: Installing the Breaker Box

Breaker box installation

Since the relay board will have high voltage electrical wiring connected, making those connections and traces under the board potentially lethal, I am installing a box to safely conceal the relay board and connections. For my box, I chose a GE breaker box designed for four breakers. I removed everything from the inside of the box as the breaker standouts will not be used for my project. Also, since the grounding bar was part of the breaker standouts I removed, I've installed a much larger ground bar capable of connecting about a dozen ground wires.

It is beneficial to know what is above the location where you choose to install the breaker box. If my location were just 15 inches to one side, the air conditioning/heating unit in my attic would be right on top of it, making it very difficult to run the wiring. Check out your chosen location thoroughly and know what is nearby or in the path that might make your attic or crawl space task more difficult. If unsure, use a tape measure to find the distance from some '‘landmark'’ such as the attic opening. For common square/rectangular box building layouts, measure two lines at 90 degrees between the box location and the attic opening so that you can repeat the measurements from up in the attic to check for clearance. If you live in a house with round rooms, well, other than using a string and a nail, I hope you'’ve already figured out how to address your dilemma. :-)

My breaker box dimensions are about 5-1/2" wide by 10" tall. To locate a spot to install the breaker box, I used a stud finder on the closet wall to locate where the wall studs were behind the drywall, marking lightly with a pencil in case I decided on a different location. I didn't want to locate my breaker box directly next to a stud because to the right side it would put me too close to the corner of the closet to reach it easily, and to the left, I wanted a space on that side of the box to bring in the control wires keeping them as far away from the incoming electrical cables. So, I chose to place my box about 4" to the right of a stud. I double checked the entire area before cutting the drywall to make sure there were no obstructions for placing the box and to the best of my knowledge, nothing to impede running the wires.

I held the box against the wall with a level on top and I traced the outline with a pencil. With the drywall saw, I carefully pierced the drywall at a corner of the pencil outline. Once through, I slowly moved just the tip of the saw up and down inside the wall using it to feel for obstructions. None found. Commence cutting! I cut just to the outside of my pencil marks. This really only gave me about 1/8" on either side to make up for the wire entry adapters, and I needed just a bit more. The drywall saw is pretty good for trimming off just a small amount to enlarge the hole or to make it straight.

I cut two scraps of 2" x 4" pine to place at the bottom and right side of the hole to attach and support the box. I ran a bead of Liquid Nails on the front and back edges of each piece where it would contact the drywall, as well as the end of the piece that would meet up with the stud to the left. I used the level to get it good and true, tapping the horizontal block lightly with the hammer until it was just above the bottom of the drywall opening I cut out, about 1/16" or so. The second wood scrap was secured vertically on the right side of my box where there are no wires entering it. At this point, the box is not secured to anything, so it can be moved around inside the opening making wire installation easier.

In the attic, I drilled one ¾" hole through the wall cap for the electrical wiring, and another one about 6" away for the control wiring to keep some space between the high-current and low-current wiring. I ran my four 14-2 NMB electrical wires with an extra pull string for future wires and the two 4-pair control wires with another pull string down the wall and out through the hole cut in the drywall for the box. I routed the wires through the appropriate entry adapters (high-current through the top near the right corner, low-current through the left side near the bottom corner) before putting the box into place in the wall. Doing this before securing the breaker box permanently greatly simplified fishing all those wires through the entry adapters. Any future wires I need to pull will tie onto the pull string and will be accompanied by yet another pull string to replace the original. To get the box into the hole with all the wiring in place, I found it necessary to remove the adapter where the control wires entered. I unscrewed its ring-nut from the inside of the box and let the plastic adapter slide freely on the wiring outside the box. This allowed me to get the big adapter at the top of the box into the wall first, then the bottom into place while carefully shoehorning the box and control wires through the tight opening. Just be careful not to damage your wiring doing this. Once the box was in place, I was able to coax the adapter back into the hole, securing it with its ring-nut. These boxes are really not intended to be installed after the drywall is in place.

Note: I took a few extra minutes to label my electrical wiring inside the new breaker box with the number of the breaker from the main panel that controls each circuit. This takes some of the guess work out of any troubleshooting or maintenance I may need to do in the future.

If your situation calls for the wiring to go through more than 1 horizontal stud or fire break between your box and your attic or crawl space, you'’ll most likely need the 6'’ flex bit for this. Also, use a fish tape to help pull the wire through the hole you drilled. It’'s sometimes difficult to hit that hole using the wire alone, especially from a considerable distance away. A good fish tape like mine will have a hole in the end for attaching a pull string or wire to pull through holes and tight spaces. My 6’' flex bit has one for this purpose, too.

After the Liquid Nails set up the next day, I mounted the breaker box in the wall with drywall screws into the 2" x 4" wood blocks, positioning the box so that it protruded about 3/8" outside of the drywall. The box's cover is designed to fit over this lip.

Installing relay board

I used a couple of strips of 1/2" MDF to attach the relay board to the breaker box using screws. I cut the MDF so that it made no contact with any of the electrical traces on the bottom of the board. Two small screws attach each end of the relay board to a strip of the MDF, and one larger screw attaches each strip of MDF to the back of the breaker box.

Step 5: Wiring Everything Together.

I connected the relays as follows:

  • Relay 1 (top) connects to the 14-2 for living room ceiling fan; white to COM and black to NO terminals.
  • Relay 2 connects to the 14-2 for master bedroom light; white to COM and black to NO terminals.
  • Relay 3 connects to the 14-2 for master bedroom fan; white to COM and black to NO terminals.
  • Relays 4-8 are not currently being used.

The two 14-2 NMB cables with ground connect like this to the existing wiring (which is 14-3 NMB with ground) and to the first relay for my living room ceiling fan:

  1. The red wire in the existing cable running from the wall switch is the HOT for an optional light kit. It connects to the black wire of the first cable that I ran to the closet. It is for future use and is not connected to a relay at this time. Since this is connected to a wall switch that could get turned on, this black wire is connected by wire nut to the white wire of the same cable. This white wire is wrapped with black tape on both ends denoting it as a HOT wire. Back in the attic, the other end of this white wire connects to the red wire leading toward the optional light kit for the ceiling fan. If I decide to add a light kit, all I need to do to add it to a relay is turn off the breaker in the main panel, remove the wire nut, trim the ends a bit and secure them to COM and NO terminals on an unused relay.
  2. The black wire in the existing cable running from the wall switch is the HOT for the fan, and it connects to the black wire of the second cable that I ran to the closet, where it connects to the first relay's NO terminal. The white wire in the existing cable running from the wall switch is NEUTRAL for the fan/light and it connects back to the white wire leading to the fan. This white wire does not connect to anything that runs down to the box where the relay is mounted.
  3. The bare copper wire in the existing cable running from the wall switch is GROUND and it connects to both the ground lead of the original cable leading back to the fan, as well as the ground leads of both cables I ran to the closet, where those connect to the ground bar I installed in the breaker box.
  4. All that is left is a white wire in the second cable running to the closet. This white wire is used as a HOT from the relay back to the fan, so I wrapped black electrical tape around the insulation near each end denoting it as being used for HOT, and did the same on the outside sheath of the cable both in the attic and in the breaker box. It connects to the COM terminal of the first relay in the breaker box, while the other end of this wire in the attic connects to the black wire leading back to the fan.

See first image above for clarification. Second image shows one example of how I wired into original circuits and extended wiring to the relay board.

My wiring connections for the master bedroom light and fan are identical to the living room wiring described above, except for the following. Since I am also controlling the master bedroom light, instead of the black wire being connected by wire nut to the white wire of the same cable inside the breaker box, the black wire connects to the third relay's NO terminal and the white wire connects to that relay's COM terminal. This white wire is wrapped with black tape near each end to plainly denote it as a HOT. Both ends of the outside sheath are also wrapped with black tape.

So, as far as house current, the HOT wires from four circuits have been cut between the wall switches and the loads, spliced to other wiring to redirect those HOT wires to the breaker box where they are switched by relays, and then spliced back to the original wiring back to the load. The NEUTRAL wires are spliced through along the original path and do not go to the breaker box/relays. The GROUND wires are spliced through along the original path AND down into the breaker box where all four GROUNDS connect to the ground bar.

Control wires connect from top to bottom of the relay board header as follows:

  1. - from separate power adapter, which is also tied to - from other adapter and a ground from Arduino
  2. pin 4 from Arduino
  3. pin 5 from Arduino
  4. pin 6 from Arduino
  5. not connected
  6. not connected
  7. not connected
  8. not connected
  9. not connected
  10. + 5 v from separate power adapter

You may notice that there are now two switches in series in each circuit; the original wall switch and the relay controlled by the Arduino. I intended this to be the case for this phase of the project, but I hope in a later phase to interface the wall switches to Arduino inputs for triggering each circuit. Right now, my wall switches are pretty much master controls that must be left on in order to allow the Arduino to control a circuit, but can be used to override the Arduino for turning a circuit off.

Step 6: Wiring the PC and MV for Arduino Switch Control.

For another project several years ago, I wired up a remote switch box to both my PC and MV so I could power them up from my desk. See first image above. I was using the PC as a Home Theater PC (HTPC) and kept it and the MV in my wiring closet so I wouldn'’t hear the cooling fans while I worked or watched movies. The PC was replaced a few years later and I moved both from the closet back into the office.

The way the remote switch box works is that it has a small switch and an LED with current-limiting resistor for each piece of hardware. The LED indicates the power state of the hardware by illuminating if it receives +5 v from the power supply unit. The small switch on the box is wired into the front panel power switch wires. I decided to splice into my existing wiring between the switch box and the hardware to add Arduino control of the PC and MV power for this project.

I am using a length of Cat5 cable from the switch box that runs about 10’' toward the PC and MV, and splits with two pairs of wires running to each. To incorporate this into my Arduino project, I tapped into that Cat5 cable near the switch box with another Cat5 cable. I spliced each wire, color for color with one exception I will point out a bit later, using solder and heat shrink, making a ‘'T'’ from the original cable. The outline below describes the function and connection of all wires in the Cat5 cables including the ‘'T'’. See the second image above for my rough illustration of this.

  1. The blue and white pair of wires connects a resistor/LED to the PC’'s +5 v power supply rail using the red and black wires on a Molex connector (the 4-wire power connector used on older IDE drives) inside the PC. The blue and white pair in the ‘'T'’ I added runs to an Arduino input pin and ground respectively, giving the Arduino a sense of the PC's power state.
  2. The orange and white pair of wires connects to the PC’s power switch and the ‘'T'’ goes to a reed relay, which has its coil controlled by a connection to an Arduino output pin and ground. I ended up having problems with this reed relay salvaged from an old project. I didn'’t want to take the time to find a replacement for it yet, because all the 5 v reed relays I find have lower coil impedance equating to more than 40 mA current draw on the Arduino'’s output pin. I decided to wire the PC’s power switch to an unused relay on the Sainsmart board temporarily. You'’ll also see this change in the code when we get to programming the Arduino. Connecting the orange and white pair of wires does not require following any particular polarity, since they don'’t power an LED and the relay (either reed-type or relay board) is merely acting as a switch to make or break the connection of those two wires. For the reed relay, the two contacts on the far opposite ends of the relay’'s tube shape are the contacts that will be switched to make/break continuity with each other, while the other two contacts near one end of the tube connect to the internal coil used to make the switching of the first two contacts take place. All the coil needs is one lead connecting to an Arduino output pin that will periodically provide +5 v and the other lead connecting to an Arduino ground pin. Update August 2014: Problem with reed relay was that 1 leg was just a bit too short to contact underneath the breadboard without constant pressure on it. I've soldered both relays to a perf board now, so the reed relays are both being used for the PC and MV again. Look for my update on what else is wrong with this on last step! -End of update-
  3. The green and white pair of wires connects to the MV'’s +5 v power supply rail using the red and black wires on an internal Molex connector. The green and white pair of the ‘'T'’ runs to an Arduino input pin and ground respectively, giving the Arduino a sense of the MV'’s power state.
  4. The brown and white pair of wires connects to the MV'’s power switch and the ‘'T'’ goes to a reed relay, which has its coil controlled by a connection to an Arduino output pin and ground. The brown and white pair of wires no longer connects to the switch box.

Now, the reason the brown and white pair of wires was excluded when I tapped into the Cat5 cable from my original switch box project is due to the way the MV power switch functions, which differs from ATX powered devices. The MV operates more like the older AT power supply-equipped computers; the switch must remain closed during the entire time the MV is powered up for use. Pressing the switch again causes the circuit to open, but does not immediately shut off all power to the MV. Its motherboard senses the open and triggers a shut down sequence that takes about 9 seconds to complete. In that respect, the power switch is nothing like that on an AT power supply-equipped computer. Due to this behavior, my MV'’s front panel power switch is always left in the open or off position, allowing the toggle switch on the remote switch box on my desk to control power. Since you can'’t easily make a toggle switch change positions remotely, I decided to do away with the switch box'’s toggle switch for the MV to integrate this with the Arduino project. In this fashion, only the Arduino can control the power state of the MV. I can always unplug the control cable from the switch box or the MV and use its front panel switch.

Update August 2014: I added a circuit board with two momentary tact switches with room to add three more later. See last four pictures above. The switches are connected to input pins on the Arduino and are used as alternate ways to interact with the circuits controlled by the Arduino. This is a 'proof of concept' for me, and I will use this to integrate similar switches in place of the regular wall switches soon. In the near future, I plan to change out the wall switches in the master bedroom with an extension of this added circuit board containing two switches to control the light and ceiling fan from the wall switch location. I will also extend two more switches wired parallel to these to place behind the headboard of the bed within reach while resting. The 110-volt power leading to the original wall switches will be terminated in the attic so it won't cause EMI with the lower voltage circuit in the wall switch box.

On the circuit board I added an LED to confirm the button is pressed along with a 1/4-watt current-limiting resistor of 390 ohms. Pushing the switch closes the circuit connecting +5vdc to the Arduino input pin via a 10k ohm pull-down resistor connected to ground. The LED circuit is connected in parallel to this. See last image for schematic. The extra switches in the schematic illustrate extending each circuit to multiple switch locations, ie. wall switch location and headboard.

In operation, I push either of the two switches, the corresponding LED lights while the switch is pressed. Immediately upon pushing the switch, I hear the corresponding relay on the Sainsmart relay board switch on or off (opposite of what it was before). Releasing the button turns off the LED. Both pushing and releasing a switch cause the Arduino to send serial data for monitoring during troubleshooting; the data sent indicates the button state 'pressed' or 'released', as well as the state of all Arduino pins used in my project. I'll show this in an update to the sketch step later in this instructable. -End of update-

Step 7: Programming the Arduino

Attached below is the Arduino sketch for my latest version of this project. For your convenience, it is zipped in a folder with the same name as the sketch. This is necessary for you to use it with the Arduino IDE software. ***sketch can be viewed with any text editor***

Be careful with the placement of opening and closing braces ‘{‘ and ’}’ because for the code to work the braces have to be balanced. If you get lost trying to keep up with the braces, you should notice that using the Arduino IDE (I have been using IDE 1.0 on Linux, and previously 1.0.5 on Windows) if you put your cursor just after an open or close brace, the IDE will surround its matching brace in a rectangle. You may need to scroll up or down within your code to find the matching brace, as large parts of your code may contain braces with many other pairs of braces in between them. You can use this feature of the IDE to find the brace that is out of balance or extra, or perhaps should be matched with a missing brace.

Going over the code at a high level, mainly I want to point out the part of the code that makes the web page. It starts with client.println(""); This tells the Arduino to print a line to the web browser connecting to the server over the established connection. If you are somewhat familiar with HTML, you can modify the page content and links following that to suit your needs. Just keep in mind it needs those client.print statements at the beginning of each line that contains the content of the actual web page; either client.println which prints a line with the effect of a carriage-return line-feed at the end, or a client.print which prints what follows, but will need to end with the html code
for line break to get the same effect. To print multiple things on the same line, use something like:

client.print("I ");

client.print("like ");

client.print("Arduino ");

client.println("home automation projects");

The above will print

I like Arduino home automation projects

to the web page with a carriage-return line-feed afterwards.

I added a twist to CDCosma’'s web page when I decided on adding PC and MV switch control, so you'’ll see a small amount of code between parts of the HTML that is just used by the Arduino to decide what the HTML will display in the browser. For instance:

if (digitalRead(8) >0){

client.print("MV is ON");


client.println("Shut MV Off");

} else{

client.print("MV is OFF");


client.println("Turn MV On");


This means that the Arduino will read digital pin 8 to determine if it is HIGH or LOW. Digital pin 8 is connected to the +5 v power supply rail of the MV so the Arduino can sense the power state. If pin 8 is read as a digital HIGH, it will carry out the next 3 lines of code, printing 'Media Vault is ON' (ON will be in bold, green text), 2 line breaks so the text doesn'’t overlap the button below it, which will read ‘'Shut Media Vault Off’' and the linked url of that button is ?mvoff or (See image above for the web page.) This means it will send ?mvoff as the header to the Arduino, and when the Arduino reads that string, it will carry out code near the end of the sketch starting at

if(readString.indexOf("?mvoff") >0)//checks header string for off request

Else, being what is carried out if pin 8 is LOW, the code will print to the client web page 'Media Vault is OFF' (OFF will be in bold, red text), 2 line breaks so the text doesn'’t overlap the button below it, which will read ‘Turn Media Vault On’ and the linked url of that button is ?mvon, and the Arduino will carry out the code near the end of the sketch corresponding to ?mvon.

I liked the way this worked enough to go back and modify the light and ceiling fan control parts of the web page to include this conditional behavior. The only thing I don't like about using this is that the page is not truly dynamic, meaning it does not update after clicking a button. I believe that would require adding AJAX or JSON which I have not learned yet. I did experiment extensively with plain JavaScript and was not able to succeed. I then added 'Refresh' buttons to each section which don't actually refresh like the browser refresh button would do, but they just link to for the Arduino to send back a fresh page without the browser sending any additional header string at the end of the URL. Using my pseudo-refresh buttons will not cause the Arduino to change the state of any pins. If the browser shows, using the browser's refresh button would cause the browser to resend that request and cause my PC to suspend. This is since I am using the power switch to interface with the Arduino and the same action is required for the switch to turn on as turn off. It's a good idea to avoid using any of the browser navigation buttons in cases like this.

Following that code near the end of the sketch, you’'ll be able to see the actions caused by each of the header strings, including the requests for turning light or fan on and off. Those pins which I have connected to the Sainsmart relay board are initialized as HIGH in the setup function of the sketch starting with void setup() so that when the Arduino first powers on and runs the sketch, those relays are disengaged. This must be taken into account. Because what happens when the Arduino loses power, then regains power? It starts up and runs the sketch from the beginning. The setup function where the Arduino’'s pins are initialized executes only once each time the sketch runs. You’'d probably rather be occasionally left in the dark for a few seconds if your home power cycles briefly while you are home, than to come home from work or vacation to find all the lights on because the power went off and came back on again while you were away.

I also have the Arduino write to the serial port what action is being performed. This helps when troubleshooting using the Arduino IDE's serial monitor.

Notice that the code in the sketch for switching on the PC works much differently than for the MV. This is due to the differences in the types of front panel switches. The PC needs only a momentary short from its front panel switch (or from any external switch mimicking the front panel switch). Because of this, pin 9 needs to cause the relay to close momentarily and then open again. To do this, I’ set pin 9 to LOW, which engages the Sainsmart relay (recall I am using the relay board instead of an external reed relay), the sketch waits for ¼ of a second before setting pin 9 to HIGH again, disengaging the relay, all this mimicking the effect of pressing the front panel power switch briefly and releasing it. The exact same action from the sketch is required to cause the PC to wake from its suspended state as it does to suspend it. I also wrote in the ability to reset the PC by mimicking a 4-second press of the power switch in case the PC locks up on me. I don’t expect to ever need to use this one, but thought about adding it while I was going through the possible front panel switch inputs in my mind.

At the very bottom of the web page, I added some lines to remind myself which sketch was loaded, when I uploaded it and from which computer. I recently moved a laptop and one PC from Windows to Linux and wasn't sure if I'd have differences in the behavior of my uploaded sketches based on the OS I used to run the IDE. The only thing I noticed due to my OS move is that with Linux, when you open the serial monitor in the IDE, it resets your sketch. So in my case, all my high-power relays switch to off. There has been no difference in the behavior of my sketches relating to my OS move.

Update August 2014:

Along with adding the circuit board with tact switches, I added some tricks I picked up from diving deeper into amandaghassaei's Intermediate Arduino: Inputs and Outputs. In order to print out to the serial port the state of each pin when I want it to, I added a section to my sketch before the setup() which declares a variable for the each pin's state, like:

int pinState1 = digitalRead(4); //I did this for each pin in my project, pins 4-9, 11 and 22-25, all inputs and outputs.

and using her example for debouncing a switch before determining its state, declared boolean variables for currentState, lastState, debouncedState for each button (like currentState1, currentState2), unsigned long timeOfLastButtonEvent for each button, and a standard debounceInterval to be used for all like this:

boolean currentState1 = LOW; //storage for current measured button1 state, ... etc for 2, 3 and 4

boolean lastState1 = LOW; //storage for last measured button1 state, ... etc for 2, 3 and 4

boolean debouncedState1 = LOW; //debounced button1 state, ... etc for 2, 3 and 4

int debounceInterval = 20; //wait 20ms for buttons to settle

unsigned long timeOfLastButtonEvent1 = 0; //store the last time button1 state changed, ... etc for 2, 3 and 4

At the end of my sketch outside of my setup() loop, I added the following function which I named 'States':

void States(){

pinState1 = digitalRead(4);

pinState2 = digitalRead(5);

pinState3 = digitalRead(6);

pinState4 = digitalRead(7);

pinState5 = digitalRead(8);

pinState6 = digitalRead(9);

pinState7 = digitalRead(11);

pinState8 = digitalRead(22);

pinState9 = digitalRead(23);

pinState10 = digitalRead(24);

pinState11 = digitalRead(25);

Serial.print("Active low lr fan circuit-output pin 4's state: ");


Serial.print("Active low br light circuit-output pin 5's state: ");


Serial.print("Active low br fan circuit-output pin 6's state: ");


Serial.print("MV switch output pin 7's state: ");


Serial.print("MV power status input pin 8's state: ");

Serial.println(pinState5); Serial.print("PC switch output pin 9's state: ");


Serial.print("PC power status input pin 11's state: "); Serial.println(pinState7);

Serial.print("LR fan button input pin 22's state: ");

Serial.println(pinState8); Serial.print("BR light button input pin 23's state: ");


Serial.print("BR fan button input pin 24's state: "); Serial.println(pinState10);

Serial.print("MV switch button input pin 25's state: ");

Serial.println(pinState11); }

And I debounce each switch, determine its state, decide if that changed, and call my States() function from each section within my loop() like this:

//master bedroom light
currentState2 = digitalRead(buttonPin2);

unsigned long currentTime2 = millis();

if (currentState2 != lastState2){

timeOfLastButtonEvent2 = currentTime2;


if (currentTime2 - timeOfLastButtonEvent2 > debounceInterval){ //if enough time has passed

if (currentState2 != debouncedState2){ //if the current state is still different than our last stored debounced state

debouncedState2 = currentState2; //update the debounced state

//trigger an event for master bedroom light

if (debouncedState2 == HIGH){


Serial.println("Button2 pressed");

digitalWrite(5, !digitalRead(5)); // invert state of pin 5 by first reading its digital value, then writing the opposite




else {


Serial.println("Button2 released");






lastState2 = currentState2;

I also call States() each time an action is taken based on input from the web page, making for a seriously large amount of serial output. That was mostly to troubleshoot some odd behavior which turned out to be caused by a slightly conductive surface (top of stained antique chest) where my Arduino and switch circuit board lay, still without a project case. I need to fix that soon but for now, I've placed a sheet of paper beneath everything. Before that, I could place my hand on the top of the chest and a relay would invert states. Not exactly desirable results! I'll cut back on the heavy use of States() and/or whiddle down its content soon. Also near the top of my 'to do list' is to finish my plexi enclosure for the Arduino Mega and ethernet shield and make something similar for the switch circuit board.

The last three images above are screenshots of the serial monitor output with notes.

-End of update-

Step 8: Future Changes to My Project-updated!

I thought about adding some code to have the last state of each pin written to an SD card inserted in the slot which is built onto the ethernet shield. I could have that result read by the Arduino setup() for the purpose of initializing a LOW rather than the default HIGH for my high-powered relays. But I can see a potential problem if I want to leave the house during a power outage, and don'’t want the Arduino to bring devices back to their last state when power returns. This could be remedied with a simple on/off switch that feeds +5 v to another pin on the Arduino and included in my sketch. Even though without a UPS, there will be no +5 v during a power outage, that circuit could be used for the Arduino to determine if it is to resume last state set by the user, or default to the safe ‘OFF’ mode. When power is restored, if you’'ve flipped that switch to ‘OFF’, then the pin set to read that will not see +5 v present and default to safety.

I haven’'t experimented with the use of the SD card as of yet, but this idea has me thinking of doing that soon. A simple database stored on the card and managed by the Arduino code should suffice. The safety default switch wouldn'’t need to be complicated, and could get its +5 v from the Arduino through a 10k ohm pull-down resistor to ground rather than needing another power source. I could also run wires to my exit points and locate the switch there for convenience. It could even incorporate a flashing LED powered by a battery backup to get my attention as I am leaving during that power outage.

I also would like to add a logic circuit so that my MV doesn't power down any time I forget that the serial monitor resets the Arduino, or if I lose power even for a split second. So basically, if the change to the control pin's state was due to anything other than user input, the Arduino or an external circuit could prevent the MV from shutting down.

Another thing I want to add to my project is to convert my wall switches to +5 v DC and use them as an alternate trigger via the Arduino for the relays controlling lights and fans and other things I add in the near future. September 2014 update: I've now completed this for my bedroom. See pictures. As a proof-of-concept for the alternate method of triggering circuits, I added the switch button circuit board to give me access to control circuits right from the Arduino's location without needing access to the web page. The buttons act as toggles due to the Arduino's programming. Button 1 = livingroom fan, button 2 = bedroom light, button 3 = bedroom fan, button 4 = MV and button 5 triggers a new function I added which lights five other LEDs to indicate the on/off status of the five main circuits controlled by the Arduino. Those LEDs are triggered when I press button 5 and only remain on for 3/4 second. I am using the switch button board to interface wiring used to replace 110 v AC circuits at wall switches with 5 v DC circuits connected to the Arduino.

I removed the wall switches, safely capped off the electrical wiring, ran low-power wiring between the Arduino and wall switch box, and extended that a few feet over from the switch box to an unused phone outlet location behind my bed, giving me control of the light and fan from two headboard-mounted push button switches. I bought a blank face plate to cover the switch box, drilled two 1/2" holes to access the button switches, mounted the buttons to a perf board. I drilled two 1/2" holes for those buttons in a rectangular piece of lexan placed between the perf board and the face plate. I soldered in a blue LED that had long wire leads and a built-in 680 ohm resistor, attaching the LED's flat top to a slightly polished edge of the lexan with hot glue. I added an extra resistor to bring the brightness down from 'wake me up' bright to a more 'romantic' soft glow, powering the LED with only about 2mA of current at 5 volts. For the headboard-mounted switches, I didn't have a project box small enough for my liking, so I got an idea that I could just solder the wires and switch buttons to a very small perf board section (I cut the perf board using hack saw) and cover it with hot glue. I used some foil and made a sort of mold for the hot glue, starting with a small layer of glue on the bottom, then setting the board in place and covering the board and wires with more hot glue. But the foil doesn't release from the hot glue like I thought it would. Perhaps a light glaze of cooking spray would have made that work. I trimmed up the hot glue and peeled the foil from the sides, but left it on the bottom. I then hot glued it to the back of the headboard in a convenient location we can reach. End of update!

I could get RF modules and setup wireless links between the Arduino and the wall switches. A flip of the switch would actually be sending an RF signal to the other end connected to the circuit to trigger that circuit to come on. This will eliminate the need to do all that electrical wiring between wall switches and lights/fans and relay board, but the cost in materials would increase significantly.

I would like to add another function to the sketch, one that takes into account the time it takes for the PC or MV to either boot up and be ready for use or to shut down/suspend, and during that approximate time, the buttons would be disabled and a status indicating ‘powering up’ or ‘shutting down’ is displayed on the web page. This way, I can'’t hit the ‘Wake PC’ button twice possibly causing it to shut back down, or worse, cause the MV to lock up from trying to shut it down while it is still booting. The MV is a bit finicky when it comes to power up and shut down, and it is recommended to let it fully do either before having it do the opposite. I know I could write a delay into the startup or shutdown functions for both devices, but I wouldn’'t mind still being able to turn a light or fan on or off while one of the computer devices is booting or shutting down. A delay will make the sketch pause while the delay time is counted by the microprocessor, making it work for its purpose. But it would not be ready to intercept any other commands sent to it until after the delay ends. I'’ll need to do some research on this functionality.

I’'d also like to control my garage door opener, security alarm panel, and window blinds from the Arduino. This area of the state has been in drought conditions for the past several years, and under treated water usage restrictions. I’'d like to catch rainwater that runs off my roof in barrels or an underground storage drum and use it for watering the yard anytime I want without restrictions, and control a sprinkler system from the Arduino.

I would also like to find a secure way to access my Arduino from the Internet. You wouldn'’t want anyone having remote access to such a toy without your permission, so this project in its current state would not be good for adding Internet accessibility. I have on my ‘to do’ list to test some VPN solutions that might be better for multiple forms of remote access. If you have to be on your local network in order to access the Arduino’'s web page because it isn'’t open to the Internet, a VPN would suffice by allowing you to connect to your local network from anywhere in the world. Once connected, anything available over your local network is at your disposal as if you were connected to it locally. As long as that VPN was secure and provided private access, it would be safe.

Step 9: Wrapping Up!

With the world of possibilities the Arduino presents (not to mention all the other similar microprocessor options out there) I can see this being a never-ending project in some ways. And if that inspires innovation and creativity, what’'s the harm in it?

I hope you have enjoyed this instructable, and that it inspires your next project in some way. Please feel free to comment. Thank you!

Step 10: Update Aug-Sept 2014: Things That I Did Wrong the First Time!

Here I'd like to mention a few things where I made a wrong choice about how to do things in this project. I have not burned my home down, nor have I destroyed any of my electronics, but continued research and learning about the Arduino has uncovered some mistakes I would like for you to avoid. Some of this was mentioned in earlier updates.

Don't power too many things directly from the Arduino. It puts too much strain on the voltage regulator and/or the logic transistors attached to each pin. My Sainsmart 8-ch relay board was originally being powered from my Arduino's 5 V pin, but I've since decided that was not a good idea and I wired in a second AC-DC adapter to remedy that.

After adding in the separate DC power adapter for the 8-ch relay board, and adding pull-down and load resistors to the IO pins in my project, I measured current on all pins.

  • Pins 4, 5 and 6 have a current draw of 1 mA each when in a LOW state to trigger a relay on the 8-ch board and 0 mA in a HIGH state.
  • Pins 7 and 9 only draw a max of 5 mA each when HIGH and triggering their reed relays and 0 mA when LOW.
  • Pin 8, 11, 23 and 24 did not register any measured current at all. These pins are all reading the state through a high impedance since they are not triggering anything. They are only deciding if a circuit is active.
  • GND measured between -3 mA and +1.5 mA depending on the state of pin 7. Pin 7 stays HIGH all the time the MV is on, and its reed relay coil draws the 4.5 mA difference the GND pin changed.
  • Arduino DC power jack measures a current draw of 270 mA on initial power up, then drops to 235 mA.
  • Sainsmart 8-ch relay DC power adapter measures a current draw of 50 mA to 140 mA.

Using relays, motors or servos (anything having inductive coils) requires either a diode to dissipate flyback current (large voltage spike heads out of the inductive coil in the direction of the power source when the coil's electromagnetic field collapses) when switching the relays off, or a driver board that isolates flyback from the IO pins of the microcontroller. If your voltage source is an Arduino pin and you haven't planned properly, you could damage your board. The Sainsmart relay board has this protection in its design and is intended to be connected directly to a microcontroller safely, but my reed relays do not. My Arduino is running on borrowed time until I resolve this! My reed relays draw (and source) such a small amount of current that I could replace them with transistors. However, I'll probably leave the relays in place now that I've gotten this far. Perhaps next time I think of using a very small relay, I'll also compare the pros and cons of using a suitable transistor.

My reed relays measure a coil resistance of 1k ohms, and with 5 volts supplied would draw 5 mA. I measured 4.5 mA current draw at the Arduino output pin. I have added in a 1N914 diode (equivalent to the 1N4148) across the relay coil terminals, see first two images above, to absorb/dissipate that flyback current created when the reed relays switch off. Note: A flyback diode is placed in reverse polarity so that normally no current flows through it. When the electromagmetic field in relay's coil collapses as input voltage is switched off, the flyback diode creates a path of least resistance for that collapsing field's high voltage to travel its final several milliseconds backwards through the coil into the diode, out the diode back into the coil until it dissipates. An effect of this is the coil takes several ms longer to de-energize, however, this is not a problem in most circuits.

I don't know how to measure flyback voltage, but some indications involve measuring the amount of carbon crust on your expensive but busted electronic components that you didn't protect. When I learned that flyback can be hundreds of times the original voltage supplied to the inductive coil as the EM field tries to go anywhere it can in a suddenly open circuit, I decided this had to be fixed. Now it is!

I still haven't decided on a box to conceal and protect the Arduino and its connections. I haven't completed my Plexiglas box, and now that I added the board with switches, I either need a bigger box, or more than one box. I may design a larger Plexiglas box that has room for the Arduino, a board that will eventually replace the solderless breadboard, and the board with the switches, and have power inputs for both adapters powering the project.

Placement of sensitive parts is near an unexpected source of static. I found out the anti-static chair mat next to the chest the Arduino sits on holds a static charge. So much for the extra bucks shelled out on the 'anti-static' claim, but this is very bad for the Arduino. Occasionally when I'd touch a wire or rest my hand near the Arduino, I would hear one or two relays in the closet-mounted breaker box click off. I saw and felt no discharge, but obviously there was a static discharge.

When exposed to ESD (electro static discharge), the microcontroller not only does things it's not supposed to do, but it can experience permanent failure. Static electricity can have the potential of tens of thousands of volts and can be very damaging to sensitive electronics. Not all electronic components are sensitive to ESD but why risk it when you know there are at least some delicate components in your project. I can be a few feet away from the boards, but lift the chair mat off the carpet a few inches, and the Arduino will cause a relay to switch off. It is just too close, so I need to see what it takes to eliminate that static. I'd remove it if the carpet wasn't so thick that the chair won't roll without a mat. I'm now looking at other static-free solutions.

I didn't make my original design to include pull-down resistors on input pins. Everything I added recently includes a 10k ohm pull-down resistor, and I have gone back and added pull-downs for Arduino pins 4-7, and 9. See third image above. See http://arduino.cc/en/Tutorial/DigitalPins to learn about pull-up and pull-down resistors for digital IO pins on your Arduino.

Proper opto-isolation and grounding of Arduino and relay board, as well as use of UTP cabling wire pairs. I should have known better than to just randomly pick which wires connect to what between the Arduino and the Sainsmart 8-ch relay board. I think my intermittent relay behavior (not to mention intermittent Arduino pin HIGH/LOW output) may have been caused by static, as mentioned earlier, perhaps in combination with poor wiring practice when connecting the Arduino and the relay board together. I've gone through my UTP (unshielded twisted pair) cabling and made sure that only one wire of any twisted pair is used for signal or +5 v power, and the other wire of that twisted pair is connected to the Arduino's GND pin, but left NOT connected to anything at the relay board. This practice should reduce cross-talk between channels (a HIGH for relay 1 picked up by the wire connected to relay 2, etc).

I read on http://arduino-info.wikispaces.com/RelayIsolation that to truly opto-isolate the relays from the Arduino, the Arduino's ground pin should not be connected to the relay board's ground pin. A wire leading to the relay board should be connected to ground at the Arduino, but left NOT connected at the relay board. This apparently eliminates a possible ground loop condition that may further complicate things.

First, I moved my separate DC power supply near the relay board, though I'll need to make this permanent soon. I've removed the VCC to JD-VCC jumper on the relay board, and connected the +5 v lead from the adapter to JD-VCC pin and the 0 v or negative lead to the GND pin on the relay board. I've reconnected a +5 v wire from the Arduino's +5 v pin to the VCC on the relay board's main header. See fourth image above for clarity.

Then, I went through the wiring I was using to connect each Arduino pin to a relay board pin and made appropriate changes. Now, out of two 4-pair cables between the Arduino and relay board (that's 16 wire conductors total) I only have 8 of those wires connected to the Arduino; one +5 v and one GND (one twisted pair), and three output pins and three GNDs (three twisted pairs). And at the relay board, only four of those wires are connected; one +5 v, and three output pins to trigger the three relays I'm currently using. The separate DC power adapter is now sitting in the closet with the relay board and its 0 v lead is the only GND connection to the relay board. In total, six wires connected to the relay board's two headers.

So far, this works well. Although, in general, it was working pretty well before, the red LEDs on the relay board that indicate the 'active LOW' state of any relay that is 'ON' seem to be brighter. During my reconfiguration of all those connections, a relay would trip off while its LED would still be lit. I had similar experience with all relays in the beginning of this project when I was powering both the Arduino and the relay board (entirely) from one inadequate DC adapter. It was rated high enough in current and voltage. In the real world it didn't put out enough current to hold the relays closed, yet it could light the LEDs. I am hoping this change will eliminate the rare but occasional intermittent behavior I was blaming on static. It could still have been static (that chair mat made lots of sparks when I lifted it off the carpet) that was being induced into the wiring of the DC power adapters' outputs as well as all the signal wires to the relay board.

One last recommendation for grounding was to connect the Arduino GND to the building GND by using only the ground wire of a wall plug plugged into a wall outlet and the other end of that connected to the Arduino GND. I haven't done this but will soon. I'll head off to Home Depot to buy a $2 build your own type of plug and wire a 12- or 14-ga ground wire between the plug's GND and the Arduino GND.

<p>Wow! This is a ton of great information! Thanks for sharing all your knowledge! </p>
<p>Glad to share <em><strong>@Danger is my middle name</strong></em>! Thanks</p>
Hello, I am going to to home automation through WIFI, I need a cheap solution, Can you tell me that can I interface wifi module (circuit based) with arduino? which Wifi module will it be? and where can I buy it?
Hi ZainubB,<br>There are several WiFi shields available for Arduino, but I have not used any of them. I chose to use a wired ethernet shield with my Arduino project, if I recall, mainly because of the limited support for WPA2 Personal at the time. You should also research what solutions have libraries included in the Arduino IDE, because it can be difficult to get 3rd party libraries to conform to Arduino in some cases, so I've read. A great resource is the Arduino Forums. Read up on Arduino WiFi projects at http://forum.arduino.cc/. I bought all of my boards and shields through various merchants on Amazon, but there are lots of places to buy them.<br>Good luck!

About This Instructable




Bio: I like doing things myself. I've installed my own automotive and home sound systems. I've built my own electronic gadgets including an LED ... More »
More by destructor gadget:Arduino Powered Home Make an articulating wall mount hold your TV perfectly level 
Add instructable to: