20120620

Low-Voltage Controlled AC Power Strip


NOTE:  This hack involves working with dangerous voltage levels, which can result in property damage, injury, or death!  Proceed at your own risk.  If you are not comfortable working with power circuits and wiring, you may want to consider using something like the PowerSwitch Tail II from Adafruit instead.

As part of a larger project I'm working on, I needed a way to control five AC powered devices from a small microcontroller.  At work, we use Opto 22 G4 Solid State Relays in our industrial control systems.  They are small and convenient to work with, but I was looking for something more compact.  Searching around the web, I noticed that many hobbyist were working with Sharp S108T02 Solid State Relays, but doing a little research at Digikey I decided to use the similar Sharp S201S06V instead.

S201S06V Solid State Relay Diagram

Next, I needed to find a way to provide outlets to plug the controlled devices into.  I thought about using a project box and mounting three standard dual outlet wall sockets on it, then using a standard outlet cover on those.  That would work, but it would still be on the large side.  I then considered using a standard six outlet power strip.  I headed down to my local Home Depot to see what options I had there, and returned with a nice, metal cased power strip.  I removed the four screws holding the bottom on and checked to see if my relays would fit:

Ready for surgery

It looked like everything would fit!  As a bonus, mounting the relays flat against the bottom would allow the metal to act like a heat sink.  I measured to get them evenly spaced, drilled the mounting holes, and attached the relays using a bit of thermal compound for good heat transfer.  (I thought I would be able to attach the wires after the relays were mounted, but it turned out to be easier to do with them unmounted, so next time I would wait on the thermal compound).

Power and control bus wiring

I started by soldering the common buses for the AC power and DC control lines, covering all the exposed wiring with heat shrink as I went.  Once I had the common wiring done, I added the individual AC output wiring using different colors for each – I picked colors that matched the low-voltage cable's colors.  For the low-voltage cable I just used the cable from an old PS/2 mouse that had a 6 pin DIN connector, which gave me 5 lines for control signals and 1 for ground.  The mouse cable works nicely here because it is long and flexible.  Before you start wiring the DC cable,  drill a hole in the upper part of the case near the power cable, big enough for an appropriate strain-relief.  Then run the cable through that hole, before you begin soldering it!  I also made sure to write down the sequence of wire colors on the DC cable that corresponded to the pin numbers on the DIN connector, so that I could attach the AC control wire colors in the same sequence.

Added power control wiring

After getting all the AC and DC wiring attached to the solid state relays, I mounted everything to the bottom plate of the power strip, and routed the wires, with the inputs coming from the side where the power cable comes in, and the outputs at the opposite end.  As you can see, I also added some cable tie points to make sure the wires did not get pulled out or shorted.

Solid state relays wired and mounted

Next, I removed the black “hot” bus from all but the outlet closest to the power cord, and broke the jumpers on the hot side between the top and bottom outlet of each outlet pair that connected them together.  I am leaving the outlet closest to the power cord always hot, so I have some place to plug in the project's controller.  I can still turn the entire thing on and off using the existing power switch.  Now that that the remaining five outlet's hot sides are disconnected, it's time to start wiring them up.

Since these outlets use “slide in” connections intended for lower gauge solid core wire, and I am using smaller gauge stranded wire, I soldered the ends of the stranded wire to form a stiff end that would easily slide into the outlet connections.  You can sort of see the soldered end of the red wire in the next photo.

Connecting the power wiring

Now I attach each of the AC control wires to the corresponding outlet, making sure to keep them in the same order as the relay (and DIN connector) wiring.  I cut each wire to the proper length, so that I wouldn't have a lot of extra wire to try and tuck inside.  Here it is all wired up:

Ready to close

And now all assembled and ready to go with its new “tail”:

Ready for work

Now I should note that the solid state relay inputs are simply LEDs, and require a current limiting resistor in series or you will destroy the devices.  In this design, those resistors are located on the controller board, but you could easily include them inside the power strip by soldering them inline with the DC control wires.  If you are going to use this with multiple projects, I would suggest including the resistors in the power strip to help protect the relays from damage.

This hack worked out very nicely, and it's been working for several months without any issues.  Once again, since this project involves dangerous voltages, you should exercise extreme caution when building and using this hack.  I am not responsible if you decide to duplicate this project and you electrocute yourself, set your house on fire, or encounter some other mishap.  You have been warned.

Update

Several of the commenters over at Hack a Day noted that I didn't mention the solid state relays I'm using are only rated for 3 amps (and you would likely need a heat sink for that).  Although that is fine for my project, you probably shouldn't try to control your air conditioner using these devices!  You could do a similar hack using a larger power strip with more internal room and beefier solid state relays, and along the way provide either fusing or circuit breaker protection for the individual outlets.

Read More......

20120601

Let There Be Music


I needed to be able to play MP3 files as part of a larger project I'm working on.  I did a quick search on the Internet for embeddable MP3 player chips and circuits, but everything seemed a bit too expensive or too much work.  It was around then I saw Hack a Day's post pointing me to Gadget Gangster's Instructables article Adding MP3 to your project for $3.00.  Being the cheapskate that I am, $3 sounds great to me!

A quick trip to eBay and I had two of these “mini-clip” players on the way.  I figured I should get an extra just in case I damage one while fooling around.   Before I began hacking the player, I tested it out to make sure it was operational and get an idea of how it behaves.  One of the things I discovered is that the USB interface is pretty flaky (at least when connected to a Linux system), so it was much easier and faster to transfer files onto it by writing directly to the MicroSD card using a card reader.

Player liberated from its case

I cracked one open and took a look to see what it would take to hook into it.  One of the things I wanted to do is to be able to move this from prototype to finished product, or between projects.  The Instructables article showed discrete wires soldered to the board, which I could have brought out to some kind of connector.  After a bit of thought, I realized I could use a small 10 pin IDC connector and ribbon cable to allow me to plug it into a nice wire-wrappable header.  And with the extra pins, I could also supply power, and even pick off the audio!

After some minor surgery

First, I removed the power wires and also carefully removed the surface mount audio connector.  Somewhere in my lab I have the parts to build the IDC/ribbon cable assembly, but I found a pre-made one in my parts bin so I just cut it in half and started peeling back a few of the wires.

IDC cable ready for action
 I started by connecting to the power pads (mostly because they were big and easy to get to).  This also conveniently allowed me to set the amount of overhang from the connector to the board.  I then cut and stripped the remaining three wires for that side and landed them onto the pads where the audio connector used to be.  Next, I flipped over the board and cut each of the wires to length and soldered them to the center of each button pad.

Wires landed on board

Now with all the wires hooked up, it's time to test it out and see if I fried anything.  I wired up a 2x10 header on my main project (more about that in a future post) and wrote some quick code to “push” the buttons.

At home in the new project

I'm using a PIC18F4550 in this project, and using my favorite language – assembly. I love the challenge of hand-tuning code to make it as small and fast as possible, and that's not so easy with the PIC18F's!  Anyway, I wanted to drive the switch outputs open collector style, so for the switch outputs I initialize the ports by setting the switch TRIS bits and clearing the LAT output bits.  Then when I want to “press” a switch, I clear the the corresponding TRIS bit which drives the output low, and set a tick countdown timer.  When that timer expires about 200ms later, I set all the TRIS bits again to “float” the outputs and release all the switches.

After checking to make sure the software was doing as I expected, I connected the MP3 player to the main project, powered it up, and out came music!  I then tested each of the switch functions, and the player responded as expected, pausing, playing, skipping forward and back, etc.  To my surprise, everything worked as expected.  The player has been working without any hiccups for several months, despite powering it with 5v instead of it's expected 3.7v battery, and shorting the switch inputs to ground instead of the other contact (although I expect that is the way it is wired anyway).

I would like to thank Gadget Gangster for sharing his cool tip to re-purpose cheap MP3 players for use in embedded projects, and Hack a Day for bringing it to my attention.

Read More......

20110827

Hacking WebRunner to work with Firefox 6.0

I have come to depend on Salsita Software's WebRunner extension for Firefox that let's me create “applications” out of web sites. It comes in especially handy when I want to be logged in with multiple identities on the same web site, as well has keeping an always open window on my Zoneminder cameras.

When Firefox 6.0 was pushed out in Ubuntu, I was quite dismayed to find that when it checked add-ons and extensions for compatibility, WebRunner was not compatible, and furthermore, an updated version was not available. I waited for around two weeks for Salsita to update their software, but so far there's been nothing. So I dug around in the .xpi file and came up with this hack to make the current version work with Firefox 6. These instructions are for Ubuntu/Linux (since that is all I have running now), but the changes should be very similar for Windows as well.

First download (but don't install/run) the latest .xpi file from here. Then open the file with an archive manager (.xpi files are really just jar/zip files) and edit the file install.rdf, changing the value of /RDF/Description/version from 5.0 to 5.1, and the value of /RDF/targetApplication/maxVersion from 5.* to 6.*. Next, edit the file stub/application.ini, changing the value for MaxVersion from 5.0.* to 6.0.*. You may want to rename the .xpi file at this point to make it easier to keep track of it.

Now update to Firefox 6.0 (if you haven't done so already) and remove the old WebRunner 5.0 extension, in Tools|Add-ons on the Extensions tab. Close that dialog, and go to File|Open File... in Firefox and select your modified .xpi file. It should install without complaint, indicating it is version 5.1 (hopefully Salsita will version their next release higher than this).

At this point, you can either re-create your web application shortcuts, or hack the existing ones to work with the updated extension. To fix the current shortcuts and applications, modify the command for the shortcuts to point to firefox-6.0 instead of firefox-5.0. Then for each application in your ~/.webapps directory, edit the appname@webrunner/stub/application.ini file and change MaxVersion from 5.0.* to 6.0.* and change GRE_HOME to /usr/lib/firefox-6.0. Now try to launch your web application shortcuts and you should be good-to-go!

As with most hacks, I make no guarantees that this won't in some way hose your Firefox installation or your entire computer, so attempt this at your own risk! On the other hand, if you are like me and depend on the excellent WebRunner extension, this hack is a quick way to get it back in Firefox 6. Make sure to leave comments if you have tried this under Windows and get it to work.

Read More......

20100918

Dependency Injection Using Nested Classes

In my day job (lately it seems to be a 24 hour day) I do most of my work in C#, and all our new projects are implemented using Test Driven Development. Like most people doing TDD, we need to inject mock/stub/dummy objects into our objects under test. The traditional way to accomplish this is either via Constructor Injection or Setter Injection.

I have never been a fan of using setters to inject test objects, because it clutters the code with properties and methods that are only used for testing and are never used by production code. At first, I relied on constructor injection, but would sometimes run into cases where I was passing in half a dozen or more objects into the constructor. Many of these objects were simply helper classes that bundled up some functionality needed by the object under test only, and would never normally be used outside of that class.

Over the last year we have evolved another way of injecting mock objects into our test objects – Nested Class Injection (or as we call it, “TestHook Injection”). In C#, a nested class has access to it's containing class's private members, so we can use methods on the nested class to reach into the private details of the outer class. Here is a simple example:

    public class ObjectUnderTest {

private IHelperObject _helper;

public ObjectUnderTest() {
_helper = new ProductionHelper();
}

public bool MethodToTest(int testNumber) {
return _helper.HelperMethod(testNumber);
}

public abstract class TestHook {

public static void InjectObjectHelper(ObjectUnderTest objectUnderTest, IHelperObject helper ) {
objectUnderTest._helper = helper;
}

}
}


Now all the test related code is contained within the abstract TestHook class. This class acts like the diagnostic connector on your car, allowing access to internal data and manufacturer's info without exposing it to the user. In fact, you can even use conditional compilation to exclude the TestHook class in the release build to remove the “connector” if code size or security is an issue.

Now when you are ready to test your objects, you can do something like:
        [Test]
public void Test_MethodToTest() {
ObjectUnderTest objectUnderTest = new ObjectUnderTest();

IHelperObject mockHelperObject = new MockHelperObject();
ObjectUnderTest.TestHook.InjectObjectHelper(objectUnderTest, mockHelperObject);

objectUnderTest.MethodToTest(12);

// Test expectations here...
}


Note that I do not normally create my own mocks as shown above, I typically use Rhino Mocks to create mock objects, and Ninject as my IoC container. The contrived examples above are just to show the basic technique of using a nested class to cleanly access the internals of an object for testing purposes.

Now injecting objects like this is really only useful when those objects are only going to be used internally by the class under test. If you need to pass in an instance of an object that is shared between multiple objects, traditional constructor or setter injection is fine, since that is actually part of the object's contract with the world.

We have been using this technique for several months now, and it has resulted in cleaner production code, and more streamlined testing. Our test setup methods are simpler now, because we only need to inject mocks in the tests that need them instead of in the common test setup method.

I figured I should write this up since I have found the technique very useful, and a quick Google search didn't turn up anything useful. I expect this can be used in any language that supports nested classes where the nested class has access to the outer class's private member variables. Let me know in the comments if you find this technique helpful, or have any improvements. Thanks for stopping by!

Read More......

20100516

Me Day

As a special treat for myself, I recently escaped from the Teknynja Cave to visit JPL's 2010 Open House. This was my first time visiting Jet Propulsion Laboratory or the open house event, and it was even better than I expected. As a science and space enthusiast, there where plenty of things to see. What I didn't expect was the festival atmosphere and all the activities and displays for kids and families. There was plenty of booths selling kettle corn, hamburgers & hot dogs, frozen lemonade and other treats, and the smells were like that of any “normal” festival.




My first stop of the day was the Space Flight Operations Facility, the “Mission Control” room, where spacecraft like the Viking, Pioneer, Voyager and the Mars Rovers have been monitored and controlled. It was exciting to see this room with so much history (and to be in the presence of so many computer monitors).






Next up was a short shuttle bus trip to the 25 Foot Space Simulator facility, a giant environmental chamber that simulates the conditions found in space or on other planets. Spacecraft are placed inside the simulator and subjected to the vacuum and heat of space. You can walk around inside the huge chamber, and I also enjoyed checking out the control room for the simulator.




One of the highlights of my trip was visiting the Spacecraft Assembly Facility, a enormous clean room where JPL's probes and landers are built. It was especially exciting for me to see the Mars Science Laboratory (still in several pieces), which is scheduled to arrive on Mars in 2012.



The big draw for me though, was the Hubble Wide Field Planetary Camera 2 exhibit, which displays the actual camera that flew on the Hubble telescope from 2002 until 2009. Being this close to actual space hardware was an amazing experience! It is difficult to really see it in this photo, as it is enclosed in a protective nitrogen gas environment. This exhibit is the centerpiece of the new museum on the JPL campus, that contains dozens of models of probes, rovers, and landers.



At this point in my visit, the lines were starting to get very long, but I didn't mind. My next stop was the Spacecraft Fabrication Facility, where the components for spacecraft are machined and manufactured. The amount of manufacturing and machining technology in this building is overwhelming, and the tables showing example parts was very impressive.



I finally ended up at the Micro Devices Laboratory, where they do everything from create nano-sized machines to electronic chip fabrication. There was plenty to see there, but this room caught my eye - this would be my dream office, with wires and electronic equipment everywhere. Maybe someday...







I wrapped up my trip taking in the architecture and the festival scene before hitting the “gift shop” to pick up a tee shirt and some swag for the kids. I really only hit about half the activities at the open house, but saw what I came to see and more. I'll have to go again, and next time I'll probably bring the young'ins along as well.

Read More......

20100307

std::string and sprintf

Amongst the many projects I am currently juggling, one of them involves developing some C++ code for an embedded Linux project. I've just hit an instance where I'd like to be able to use “printf” style formatting using std::string instances, but it can be pretty clumsy – I need to allocate buffer space for sprintf, invoke the function, and package up the result into another string.

I did a quick search on the Internet and found many others looking for the same thing: “Is there a way I can use sprintf in c++ using std:strings?” And invariably the answers were either


  • “No”

  • “Use std::ostringstream and c++'s built-in manipulators”

  • “Use boost::format

And they are all right!

It turns out that you can't safely use the *printf style variable argument lists with C++, as only POD (Plain Old Data) types can be passed in the list. Attempting to pass most other types will result in a segmentation fault at run time. The official C++ way is to use ostringstream and the usual stream manipulators to format parameters, but for me, that make's writing tests more difficult because I need to “build” the expected streams exactly the same way in my test code. The final method could work for me, except that this is an embedded project and I am trying to keep the number of libraries referenced to a minimum, since I need to build and include them on my target Linux system.

So my solution was to accept the limitations of the printf function and write a wrapper function that hides the buffer setup and string creation:

#include <string>
#include <stdarg.h>
#include <stdio.h>

string FormatString(const string& format, ...) {
char buffer[1024];

va_list arglist;
va_start(arglist, format);
int length = vsnprintf(buffer, sizeof(buffer), format.c_str(), arglist);
va_end(arglist);

return string(buffer, length);
}



I've tucked this away in a nested namespace so I can invoke it easily when needed. Now when I need formatted text I can just supply a c string or std::string format and my parameters, and get back a nice std::string instance in return. But there's a catch! I can't pass in a std::string as a parameter because the old-school c variable argument list can't handle objects. If I try to do that, I will get a “warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime” warning and a segmentation fault at runtime. The work around (at least for std::string objects) is to invoke the c_str() method on the string parameter instance. So for example

    string argument = "a string instance";
string result = FormatString("I can format a %s parameter!", argument.c_str());


allows me to supply std::string arguments as well. The c_str() function returns a pointer to a temporary buffer containing a c style string version of the string object's value.

So now I have my template style formatting and I can move on with my project. This project is my first foray into any substantial C++ programming, so if you seen any glaring problems or know a better solution, or if this little tip helped you too, please let me know by leaving a comment.

Read More......

20091006

MonoDevelop Custom Color Schemes

I have been playing with MonoDevelop 2.0 on Ubuntu on and off for a while now, but one of the things I find most annoying (other than not having ReSharper) is there is no easy way to modify the colors used for syntax highlighting. Sure, it has several pre-defined schemes you can choose from (Using Edit | Prefrences > Text Editor > Syntax Highlighting), but changing individual syntax element colors using the GUI is not possible.


The reason I find this issue annoying is that I like to have comments and strings really stand out – in our shop we avoid comments as much as possible, and string constants are kept to a minimum, so I like to be able to see them easily in the code. A few years ago, I started using “highlighter” background colors for comments and strings, and have become quite attached to them ever since.


After many attempts to find a solution on the web, I finally found all the pieces I needed to make it happen. The basic problem is that although MonoDevelop allows you to add new color schemes, the format of the scheme file is not well documented, and there are a few tricks you need to know to make it work correctly. The existing schemes are embedded resources and not stand alone files, so they can't be easily viewed for reference. Finally, I discovered this Ubuntu Forum thread that helped me find the solution. The first piece of the puzzle was discovering the color scheme XML source files in MonoDevelop's SVN tree. Now I had some samples to go by. Another useful tidbit from that thread was that the file name must end in "Style.xml" in order to work correctly. I did not actually verify that this was required, but I did it just to be safe. The rest came from a MonoDevelop Developer's Article page I stumbled across shortly thereafter. One of the important things mentioned on that page is that you need to put the color scheme XML file in the ~/.config/syntaxmodes directory (although in my Ubuntu installation it is actually ~/.config/MonoDevelop/syntaxmodes). Now I had everything I needed to start tweaking colors!

The first thing I did was download the VisualStudioStyle.xml file and renamed it to TeknynjaStyle.xml. Next I edited the file to change the name and _description attributes of the EditorStyle tag so they would not clash with the existing styles in the GUI. Finally, using the information from the MonoDevelop article and the existing examples, I modified the colors for comments and strings to get the highlighting I was looking for:

   <Style name="comment" color="black" bgColor="#ffff80"/>
<Style name="comment.doc" color="black" bgColor="#ff8040"/>
<Style name="comment.tag.doc" color="black" bgColor="#ff8040"/>

<Style name="text.preprocessor" color="purple"/>
<Style name="text.markup" color="skyblue"/>

<Style name="constant" color="black"/>
<Style name="constant.language" color="keyword-blue"/>

<Style name="string" color="black" bgColor="#80ff80"/>
<Style name="string.single" color="black" bgColor="#80ff80"/>
<Style name="string.double" color="black" bgColor="#80ff80"/>
<Style name="string.other" color="black" bgColor="#80ff80"/>

<Style name="keyword" color="keyword-blue">
<Style name="type" color="#004080"/>
</Style>

I found the "bgColor" attribute by looking in one of the other color scheme files. Then I copied my customized color scheme file to ~/.config/MonoDevelop/syntaxmodes, restarted MonoDevelop, and selected my color scheme. I was able to tweak the colors by editing the XML file and restarting MonoDevelop until I achieved the scheme I was looking for. Finally I had the highlighting I was used to in Visual Studio, and along with modifying some of my commonly used key bindings, I was able to make MonoDevelop feel a little more like "home".

Read More......
 
Template design by Amanda @ Blogger Buster