Archive for the ‘Electronics’ Category

Taking a break from the EEG work.. Outdoor Automation

November 9th, 2012

2012-11-09 18.00.05I’ve always wanted to implement some home automation system.  My first attempt at implementing an X10 based system worked for a time, then it failed.  Lights would turn on randomly, switches stopped working.  Ultimately, the lesson I learned was that you get what you pay for.  With the X10 system: cheap shit.

I’ve since implemented a couple systems, they work for a time, but nothing robust.  I was happy to find the Electric Imp which is an inexpensive WiFi module with a cloud based backend.  I wanted to test it out, and thought automating my backyard low voltage lights and sprinkler system would be a good first application.  Luckily, most of the work was initially done by their developers in their implementation of the ‘Jane’ platform.  I asked, and was given access to their source files (since posted on their site).  I modified it to my liking:

  • Only 3 relays, not 4 to reduce PCB size cost
  • Swapped their temp sensor for an SHT71 temp/humidity sensor.  Overkill, for this application, but I have a number of extra ones from a previous project
  • Replaced their shift register with an I2C I/O expander (I need more I/O pins)
  • Used a full bridge rectifier to allow more power to supply the caps.  I also like the way full bridge rectifiers look. 
  • Added support for an external NPN based light sensor.
  • Added support for an external rain sensor.

I need to test/debug the hardware, write code in some language named after a rodent, get a box to mount the electronics – and then I’ll be all set. 


For the UI, I will be putting a framed Nexus 7 permanently in the wall.  It will serve as a frontend to a number of applications I want to make.

I think I’m going to make a number of visualization widgets to plot things like power consumption, temp, etc, and have a webserver running on the hardware that will serve html pages to do the configuration (when the sprinklers work, etc).  I plan on using it to control music in the house.  Let see how far I get along this project before being sidetracked.


Website Migration from to Amazon’s EC2

October 31st, 2012

It was a bit of work to get everything setup, but I finally migrated my websites from (horrible horrible company) to amazon’s EC2 service.  Wow, performance is great, I pay for what I use only  (way cheaper) – and the first year is pretty much free for you to try out.  If you know anything about setting up a linux box with apache and mysql – it’s trivial. 

The EC2 management console took a bit of playing with to figure it out.  You can add disks, make backup snapshots, configure the firewall, increate the ram, add CPUs, etc.. Very slick.

In any case, the migration is still in progress and I need to fix a few more things.  But after the migration, I hope to be updating this site more frequently.


Thermostat Replacement For Kegorator

February 26th, 2012


I had experimented for some time with a peltier based heat exchanger to cool beer from my kegs (home brewing), but after a few iterations, I felt the system would not be as compact as I hoped, and the peltier was eating up too much current (80W).  Here’s the unit  – heatsink, peltier, and big block of metal that would be placed in a water bath.  I have 16ft of stainless steel tubing that wraps around the block for the beer to flow through.  I had the unit in a bucket surrounded by expanding foam for insulation.   Ultimately, it was ugly.

I finally gave in, and decided to buy a dedicated fridge for the kegs instead.  I found a neighbor selling one of the right size across the street (very convenient).  He was the nth owner, and it was a commercial unit with a nice stainless steel exterior.  However, after getting it home, it seemed apparent that the thermostat was useless.  It would turn on randomly and off randomly.  I figured I could fix this, but my goal was to spend no money.  Also, the thermostat has this meal tube that goes into the wall of the fridge – and it seems permanently attached, so I wasn’t sure how feasible it would be to replace the thermostat if I had to take the entire thing apart to replace that tube.


After looking through my pile of PCBs that I could repurpose, I came across my Texas Instruments LauchPad that I picked up at ESC.

The thing that makes this unit amazing as compared to the arduino is that it costs $4.30.  The thing that sucks is that the target MCU is a POS and really didn’t have enough ram/flash for my liking.  However, after looking at the schematic, the IC at the top left of the picture caught my eye.  It’s a MSP430F1612, and it is used as a programming interface for the target IC.  Unlike the target MCU, it’s very nice and had all the features I wanted.  It’s powered off USB (5V) but has a 3.6V regulator onboard.  This surprised me a bit as this is the max voltage the MSP430s run at, with 3.3V being more logical, and what I would have expected.  Additionally, the header exposed 4 of the I/O lines which are used to interface (program) the target MCU.  This was the minimum I needed to implement a temperature sensor, a display, and to control a relay to switch on the refrigerator compressor.

I love how appliances have wiring schematics on them these days (though I had to remove the condenser coils to access it).


Both neutral and line voltage (120VAC) are present at the location of the thermostat, and a simple relay is sufficient to drive it.   Oddly enough, the lamp switch was present but unused in the fridge (so it was always on – was probably a design mistake as the door never made contact with the lamp switch anyhow).   Not surprisingly, the bulb was burnt out.


The relay replaced the thermostat (pins 3,4 in the photo).  And a wall adaptor for my old cell phone which presented a 5V USB interface was used to provide power.  It was connected to the BLU wire and the WHT wires in place of the lamp.

imageThe schematic for the lauchpad is provided by TI, which was nice.  The header I interfaced was J3. If you look, you’ll find that pins 5.1, 5.2, 4.7, and 4.2 are all connected through R5 to SBWTDIO.  Setting all but one pin as an input, and using the output pin worked fine.  Additinally, pin 5.3 connectes to SBWTCK (with a pulldown resistor which we can ignore if we are driving the pin).  Finally, we have the a serial interface on pins 3.7 and 3.6.

The header on the top left (you need to add pins) provide the programming header for the MSP430F1612.  There might be some way to program it from the USB port, but as I had the programmer, it was fairly easy.

The interface I  built was super simple, but looked ugly as it was a mass of wires handing all over.  Here’s the schematic.


Starting from the top, an IO is used to switch a darlington which turns on the relay.  Again, I just used what I had lying around, and it was able to switch the relay at 2V, which was good.

I have a number of SHT75 temperature and humidity sensors lying around that require a clock and data line to interface.  Additionally, the data line requires a pullup resistor, but the MSP430F1612 doesn’t have any so an external one was added.  They have some horrible example code that I ported over and after a few tweaks I was able to get it to work.  One tricky bit is that the data line should never be driven high – when the code wants it to go high, set it as an input so that the pullup resistor pulls it up.  For some of the messaging, you need to watch that line and see when the SHT75 module pulls it low.

Finally, I got lucky and had an LCD with the SerLCD module from sparkfun mounted.     It lets you use a serial line to drive a serial interface, dropping the I/O line requirements from something like 8 to 1.

I recently got an Ultimaker which is cool, but the documentation sucks sucks sucks sucks for a commercial product.  I need to spend the rest of the day today taking apart the print head and which is encased in melted plastic to add some teflon tape to prevent the plastic from oozing everywhere.   In any case, I was able to print out an enclosure for the device, and for the most part, it works fine.  Not having any additional input lines, I have no way to adjust the temperature setpoint without pulling the board out and reprogramming it.  It’s currently set to turn on at 45 deg F and off at 40 deg F, which seems a reasonable temperature range for beer.  Here are some photos of the unit operating.


The temperature probe is taped to the back of the fridge.


Yes, humidity is pointless in this application, but I had enough space on the LCD.


It’s still a mess, and I would like to remake the enclosure so it’s a bit nicer and it fully hides all the wires.  Feel free to contact me if you want a copy of the firmware.

Electronics ,

Android Intents, registerReceiver, BroadcastReceiver, updating GUI elements from threads

August 12th, 2011

First, let me make one thing clear.  I have Java.  I think that there is something wrong with the way people who code java think.  It’s like they have to make things as complicated as possible, as verbose as possible, and as convoluted as possible for no reason.

I had a simple goal, and that was to have a background thread receive some data and update a text field in an “Activity”.  There were plenty of webpages that attempted to describe how to do it, referring to explicit intents, to modifying the Manifest.xml file, and all sorts of other jargon – but no clear examples.  I came across dozens of posts from people trying to do the same thing I wanted to do, but no answers.  I spent about 4 hours trying to piece together a method that worked. 

Hopefully, this simple explanation will help someone..

If you want to send data from one thread to another you can do it through a messaging protocol, and encapsulate data in that message if needed.  One big complication is that the messaging can occur across applications, it can be directed at a specific target if you know it exists, or it can be ambiguous and you figure something will deal with it.  The messages can also invoke an application (“Activity”) to do something.

What I’m going to describe is how to send a message from one part of an application to another – with the typical goal being to send data to the active “activity” to display data or somesuch.


1. In the activity where you want to receive messages, you need to create a class within the activity class (I have no idea what the java developers were smoking to come with this idea) that extends BroadcastReceiver().  You then want to override onReceive() to contain the business logic.


public class ActivityClass extends Activity {

  private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("net.reza.SET_BATT")) {
            setBattery(intent.getIntExtra("value", 0));

  /* rest of your code */


In this example, I’m creating  mReceiver which is a BroadcastReceiver but I am modifying the onReceive() method.  In the method, I’m checking to see if the activity string is equal to “net.reza.SET_BATT”.  This can be anything.  There are some standards that are meaningless.  Use whatever you want.  I think it’s called an intent or intent-filter.  I’m going to call it a ‘tag’ for clarity.

2. You need to register that mReceiver is capable of handing the “net.reza.SET_BATT” tag.  There are a bunch of places to do this in your code.  I stuck it in the onCreate() method for the Activity class.



public void onCreate(Bundle savedInstanceState) {
  IntentFilter ifilt = new IntentFilter("net.reza.SET_BATT");
  registerReceiver(mReceiver, ifilt);

  /* more code */


A lot of the documentation said you need to modify the Manifest.xml file and stick it in there, but that was a mess and not obvious how to make it work.  Defining it this way is /much/ easier, and in my mind, much more manageable.  Why do java people love XML so much? 

And I have no idea why they call these tags “intent-filters” but they do.  Based on my code, you don’t need to bother with the action.equals() line, as the only time it will be called is if that tag is registered with registerReceiver(), and I’ve only registered that one tag.   But if you register multiple tags with the same BroadcastReceiver then you should check to see which one is being called.


3. You need to invoke that tag.  This can be done anywhere, as far as I know.  Even from another application.  In my case, it’s from a background thread that monitors the battery voltage by polling a device over bluetooth. 

public class BatteryMonitor extends Thread{

Context context;

public BatteryMonitor(Context y) {

  this.context = y;



public void run() {

  /* some code */

  Intent i = new Intent("net.reza.SET_BATT");
  i.putExtra("value", bat);

  /* more code */



Couple things here.  First, I still have no clue what a context is, who owns it, and how to use it properly.   I kept trying different things till it worked.  I passed the output of getBaseContext() to the constructor of the background thread, and that seemed to work.  I think some other options are getContext() and getApplicationContext(), so try those too.  Please post a comment if you know what’s going on.  

So we create an Intent with the same tag.  We can then stick extra data in there – in my case, I add an int. And then you call the sendBroadcast() method from the context object to make it go. 


I now need to go write some more code in C to cleanse my mind from all this gibberish…


Skunkworks Project–Modern Art PCB

July 10th, 2011

Been busy the past month with a secret project.  Still in stealth mode, but the layout looked like modern art, so I thought I would share…




Bluetooth enabled multifrequency bioimpedance spectrometer for hydration monitoring.

June 5th, 2011


I finally had a chance to assemble this PCB.  Alas, I ordered an SO8 package for a part accidentally and had to stick it on a daughterboard.  Will replace with the right part.  Designed to scan complex bioimpedance from 1k-100kHz and communicate with a handheld tablet over bluetooth.  I’ve moved away from the CSR ICs to using these packages as the BlueCore 3 that we were using became more expensive than these modules, and the modules are a lot simpler to solder.  I’m planning on moving to the BlueCore5 for future designs – can get power consumption down to <10mA (if you believe the datasheet) at 115kbps.


Mobile Health 2011, ESC 2011, HCI-DC 2011 all in a week

May 4th, 2011

Its been a busy week for me, I was in DC last week for a conference, san jose yesterday for an embedded systems conference and now in stanford for the mobile health conference. Last night I ended up at a super-geek dinner which was cool though the venue was not optimal. I got a chance to meet Grant Imahara from the mythbusters fame, the founder of iFixit, and some other geek VIPs. It was more of a show and tell with all sorts of gadetry in the middle of a restaurant, including a rc helicopter flight that almost srt off the sprinklers.

They just started the talks at the MH2011 conf. So far I think that there are a ton of interesting people here, but I’m a bit dissapointed with the first 3 talks. Ill be posting some more as the conference progresses.


Bioimpedance Spectroscopy Boards Arrived

May 2nd, 2011

I had some PCBs made up to do some bioimpedance spectroscopy for edma detection through the cole-cole model. One set has an MCU & space for a bluetooth module meant to communicate with an android tablet.  The other is a stand-alone module that I’m going to try and interface directly with a microtouch avr touchscreen.


  bioZ pcb 001


These will go from 1kHz to 100kHz.  If you notice the big PCB, I made the VIAs have a teardrop shape – they look cool.  It’s based on my design for a fixed 50kHz device for impedance plethysmography that I use to measure respiration.  Fun stuff!


One more day

January 26th, 2011

I’ve been stressed out about what’s going to happen tomorrow.  For almost 3 years I’ve been thinking about tomorrow.  It’s a simple exam that in the history of my department, no one has failed.  I present a research project, show I know the background to the material, and I pass.  However, I’ve managed to get advice from a set of people who have the most disparate ideas about what said proposal should entail.  That might not seem like a bad idea, but I’ve probably put together 3 totally different project, with multiple revisions of each that take a whole different slant on the material.  To nail that point home, I found out yesterday that the cumulative sum of months of work was “just not going to work” and I was advised to learn a multitude of new mathematical frameworks to be able to come up with an answer that really wouldn’t address my hypothesis.  And the exam date was fixed.


What ensued:

  1. Panic.  I felt like I was the captain of a plane that was on fire.  I wasn’t dead but I had to do something.
  2. I decided pursue all my options simultaneously.  These included
    • call library to find relevant mathematical and psychological textbooks.  Probability of mastering (which was required) the new material in 48 hours: 3%. 
    • Email various departments looking for a tutor to help with the material.  (10% success probability)
    • Try to figure out a way to slice and dice my content such as the “it’s not going to work” condition goes away.  This involved asking for a number of people to help in a brainstorming session.

    Of the three options, the third won out and 5 hours later, I had a 100% different presentation that utilized 20% of the material I started out with.  An additional 7 hour of work on the slides and I had a first pass ready.  4 hours of sleep later and a 30 minute drive – and I was back on campus working the written part of the project.  I found a tutor who offered to help and we covered the relevant material in no time.  If someone explains content at the right level, I can digest it very quickly.  For example, I love “The Darker Side” – it does an amazing job of explaining mixed signal electronic design.  He’s also the only good author left on Circuit Cellar’s payroll. 

    In any case, the exam is tomorrow.  One thing I’ve learned though all this is about stress, both the theory, about my experiences, and my developed theories (one of which I’ll be presenting on).  And what’s amazing is that I’ve been able to control the physical manifestation of stress – I’m so much better at being able to deal than I was just 3 months ago.  I’m really not stressed about tomorrow, even though I should be. 


    printf in arudino works.

    December 21st, 2010

    I’ve always had to deal with the fact that printf() is missing from the arduino environment.  I would have to come up with these huge blocks of code consisting of multiple Serial.print() commands to put together a simple message.  Well, no more!  It seems that printf works just fine, and for some unknown reason, it’s just not used or talked about. 


    In order for it to work, you only need to specify a target for STDOUT by adding this function..


    int my_putc( char c, FILE *t) {
      Serial.write( c );


    and inside the setup() function you need to point to that function


    void setup() {
    fdevopen( &my_putc, 0);

    That it!  Now printf() works!


      fdevopen( &my_putc, 0);
      printf("hello, world!");




    Why this isn’t documented, I have no idea!

    Electronics, Software ,