Thursday, July 11, 2013

Hacking with your child

Kids want to be involved in adult activities.  This is so fortunate!  My son has started taking interest in my microcontroller devices.  If I could involve him in building some circuits, I get more time to play with electronics. As a bonus, this would give my wife some free time and distract my son from his usual business of hiding valuables and destroying property.

So we set out to build a simple circuit: we chose a blinking lights circuit.  The core of the circuit is the NE 555 chip in astable mode: with a single LED blinking. If you want to do this, follow along. The point of this post is not what circuit to build, rather it is how to build this circuit to keep the interest of a very young child.

Some overall guidance:

  1. Simple circuits: A friend at work suggested this idea. Select a trivial project that you can get done in no more than 15 minutes. Everything takes longer with a child, and they have shorter concentration spans. Aim to finish in 30 minutes with the child.
  2. Prepare in advance: Depending on how old your child is, you might want to prepare most of the circuit in advance. Remember, you don't want to debug things with a potentially cranky child. One trick I use is to wire everything with long wires and tall leads on the components and get it working. Once it is working, get your kid along and switch all the ugly long wires for short ones, trim the leads, and have the child put the most critical component in, which gets everything going.
  3. Involve the child: The idea is to get them to participate and get a feeling of accomplishment.
  4. Avoid theory: At this age, the child is too young to understand what a resister does. Get them to love the process.
  5. Light-based circuits: Light-based circuits work well. Sound-based circuits get annoying for parents.
  6. Real pieces: The more this looks like a real grown-up thing, the more some kids will be interested. Avoid tacky childish substitutes.
  7. Future hacking: Keep some room for future hacking. Extra room on the breadboard, potential to add a switch for some simple interaction. This will come in handy when the child starts to lose interest, or asks to make another circuit.



The goal: get a 2-3 year-old child to see how a circuit board is built and get the child familiar with some components.
  1. This is the circuit we built. Open the page and print it out.
  2. Obtain twice the parts: a breadboard, a 9V battery and clip, a 555 chip, a capacitor, three resisters and one LED.   You are getting twice the parts because young kids love holding on to some parts. You want a spare sets of parts both to account for loss and for a child getting very affectionate towards a 1uF capacitor.
  3. Prepare the board and make sure you know what you are doing. Your electronics chops might be weak, check if you can get the circuit working.
  4. When your child is free, motivate the idea. "Do you want to make a NEW blinky-blinky?" "Oooh, shall we make a NEW blinky-blinky?". Stress on creation, stress on the fact that you are doing it together. If the child is not interested, wait for an opportune time. Consider involving your spouse in motivating the idea: the child might be going through a mommy-phase or a daddy-phase. It could be that your child just doesn't care about circuits. Respect your child's interests.
  5. Get the child to sit down on the dining table high chair. Consider strapping the child for everyone's protection.
  6. Show the child all the components, name them. You'd be surprised what they can remember. 
  7. Start putting the components in, carefully clipping leads and wires to a precise fit. You want all the components to fit tightly on the board. With any luck, this will be your child's favorite toy for a few weeks. That means high G-forces, and being carried everywhere. You don't want to drop components all over town.
  8. If your child wants to put in components, allow it. Allow incorrect component placement. Don't chastise. Instead, gently correct the component while saying, "Hmm.  That's good, but how about we put it this way..."  Any negative words might turn your child away from this entire affair. And success here can justify that $1000 oscilloscope to your spouse. So be patient, and avoid evil thoughts.
  9. Keep an eye on your child's interest level. If they look bored, stop. Return another day.
  10. Leave the 555 IC for the very end, and perhaps get your child to put it in.
  11. Hopefully, you get the project done. Congratulations! If it helps, call the breadboard something special to enforce that something new was created: "Wow, this is a 555-blinky-blinky!"
  12. Allow your child to hold the breadboard, toss it around. Don't disapprove of rough handling. This is your child's toy, not yours.
  13. Ideas for future hacking:
    A second LED that turns on when output on pin3 is low. You'll need a pull-up resister and an LED. Try a different color if possible.
    You could add another 555 for two extra blinking LEDs. Choose a different period of oscillation.
    You could include a push-button switch to force Pin3 high to keep the LED on as long as the button is pressed.

Things you might do differently depending the age and personality of your child:
  1. Solder: I used a breadboard rather than soldering because the end-product should be non-sharp, and should be child-friendly. Depending on the age of your child, you could use this as an opportunity to teach some soldering.
  2. Explanation: If your child has more background, perhaps from electronic toys, consider explaining what the components do.


Credit: Many people at work for suggesting projects and giving guidance before I started out. You know who you are. Thanks!

Wednesday, July 10, 2013

Camera shutter control for Arduino

I'm building a remote shutter release for my Nikon DSLR. I'm using Arduino to light up an Infra-Red LED.  There are many libraries that provide the correct LED pulse for Nikon cameras. Unfortunately, they don't often work, leading to time-consuming debugging. So here is the current state of affairs when it comes to Nikon IR shutter release through Arduino.

The library that works

The Arduino Multi Camera IR control by Sebastian Setz. I have version 1-91 of the library. My current environment is Arduino 1.0 that is pre-packaged for Ubuntu (I obtained it through apt-get install). I'm using this on an x86 laptop. Currently I'm using an Arduino Mega for this, though I'll switch to an Atmega328 for the real project. The IR LED is a 940nm component I bought many years ago.

I mention this in painful detail to illustrate everything that was under suspicion when the project didn't work out. The sample code involved is trivial.  But when things don't work out, debugging can get quite involved as you check every thing methodically.

The library above is the Swiss-Army knife of shutter control. Not only does it work with Nikon, but it also works with other, lesser known brands. Minolta, Sony, Pentax, Olympus, even obscure brands like Canon.


The libraries that don't work

Von Roth's Nikon library:  I had used this in the past with one of my Arduino boards and it had worked on the first try. So this was the first library I used. I was disappointed when it didn't trigger my shutter. I thought the culprit was the IR LED, since it had sat in the bottom of a parts-box for a few years, and looked rebellious at this mistreatment.

Lady Ada's intervalometer code: Given the considerable reputation of Lady Ada, I was certain that this code would work. But I couldn't get it to work, again, leading to more unjustified suspicion heaped on the IR LED.

The debugging was fun, though only in retrospect. To test whether the LED was working, I pulled out my baby monitor and verified that the LED was indeed emitting some Infra-red. A few Arduino boards were swapped, I switched from x86_64 to x86, I switched to the old installations of Arduino.

Hope this saves you some effort.



Credits for the image and the library: Sebastian Setz

Sunday, April 07, 2013

Simple computer program for one year olds

Kids love to use the same things that their parents are using. Rather than buying them toy versions of objects, we use these opportunities to teach them the correct way to use everyday objects.

My son loves to see us use the computer, and wants to use a computer too. So we bought a real adult keyboard at an electronic store, and attached it to a real computer running Linux. The only thing he can do is hit a key and see the computer's reaction.  In most programs, this produces no visible result.

So I wrote a very simple program in Python using Gtk to display a single character from the keyboard in a huge font. This is what the computer looks like when it is running this program:


Lots of advantages to this approach:
  1. The child uses a "real" keyboard and a real computer, something that parents use too.
  2. There is no way to exit, except to Alt-Tab to switch programs.
  3. The child can be rough with the spare keyboard, you just buy a new one.
  4. The computer can be disconnected from the Internet, and put on a spare child account if required.
  5. The program should work on Windows and Mac as well, after you set up Python + Gtk.
The entire program is listed here:
#!/usr/bin/python

import gtk, string, pango

class BigChar():
    """ Create a Gtk window for a single giant textview that accepts all keyboard input. """
    def on_key_press(self, widget, data=None):
        """ Intercept all keypress events and show ascii
            characters. This requires the CAPS_LOCK to be off.  We
            don't intercept CAPS NUM or SCROLL lock, probably
            should."""
        ascii_value = data.keyval
        if (ascii_value >= 97 and ascii_value <= 122):
            self.textBuffer.set_text(string.ascii_uppercase[ascii_value-97])
            start = self.textBuffer.get_start_iter()
            end = self.textBuffer.get_end_iter()
            self.textBuffer.apply_tag_by_name("real_big", start, end)

    def __init__(self):
        """ Create a window with a single giant text view. Disables all chrome.
        """
        self.w = gtk.Window(gtk.WINDOW_TOPLEVEL)
        # No border
        self.w.set_border_width(0)
        self.w.realize()
        # Take over the entire screen
        self.w.fullscreen()

        # Connect the callback on_key_press to the signal key_press.
        self.w.connect("key_press_event", self.on_key_press)
        # Make the widget aware of the signal to catch.
        self.w.set_events(gtk.gdk.KEY_PRESS_MASK)

        # Add a text view to show the key pressed
        self.textView = gtk.TextView()
        # Disable a cursor in the text view.
        self.textView.set_editable(False)
        self.textView.set_can_focus(False)
        # Show the single character in the middle
        self.textView.set_justification(gtk.JUSTIFY_CENTER)
        # This is the place we will write the character to
        self.textBuffer = self.textView.get_buffer()
        # Make the text view huge, blue on white
        fontdesc = pango.FontDescription("monospace 512")
        self.textView.modify_font(fontdesc)
        tag = self.textBuffer.create_tag("real_big", background="white", foreground="red")

        # Make the text view take the entire window
        self.hbox = gtk.HBox(homogeneous=False, spacing=0)
        self.hbox.pack_start(self.textView, expand=True, fill=True)
        self.w.add(self.hbox)

    def show(self):
        """ Show the window"""
        self.w.show_all()


if __name__ == '__main__':
    # Create a bigchar window, and show it.
    bigchar = BigChar()
    bigchar.show()
    gtk.main()



Tuesday, March 19, 2013

Sound Sleep: Free application for Android

Frustrated by existing sleep-time applications, I wrote a simple application to play music on an Android phone. The application is called Sound Sleep and it is available for free on the Play Store.

To use the application, create a subdirectory called "sleeping" under the "music" directory in the SD-card or external storage. Put night-time sleep music in this subdirectory. Many music file formats (mp3, ogg, ...) are supported. All directory names are case insensitive.

Start the application. The top half of the screen starts and stops night-time music.

The bottom half starts/stops white noise.


Since the application allows tapping anywhere, it is perfect for clumsy night-time use. It works on all Android devices starting with version 1.5, so give it a try!


Privacy policy

Soundsleep collects no data about you. I don't maintain any crash logs, any usage information, nothing. The only information I get is the total number of installs on Android devices through the Play Store. I do nothing with this information either.

 It doesn't serve any ads, doesn't report anything to any server. I don't maintain a backend stack for this.


The entire source code is available if you want to look at it, or compile it yourself. You can compile and install the software on devices that have no network connectivity.

Monday, February 25, 2013

Adding photography grid lines in GIMP

In photography, the "Rule of thirds" suggests places for optimal visual interest. You divide the photo into nine equal parts, like a tic-tac-toe board. The rule says that the most important visual elements must be at the dividing lines, or along the lines of the tic-tac-toe. This is an easy rule, and helps to determine how best to crop an image, or to judge a composition.

GIMP, the free image editor, allows the user to create guide lines. These are lines shown for reference while editing an image. They do not modify the underlying image, and can be dragged out from the ruler or created using a menu item. Gimp also allows certain edits to stick to guide lines. This is useful if you are adding text, or adding layers as it makes it easy to align visual elements in an appealing manner.

I find it helpful to create rule of thirds guide lines to evaluate photographs. Rather than manually drag out guide lines, I have written a GIMP script to automatically create such rule-of-thirds guide lines. This is what the result looks like.


To use, download the rule-of-thirds script and copy it to your local scripts directory. On my machine, this is $HOME/.gimp-2.6/scripts. The exact location depends on your platform (Windows/Linux/Mac) and Gimp version. You can find out the exact location by going to [Menu] -> Edit -> Preferences -> Folders -> Scripts.

Now start gimp and navigate to [Menu] -> Filters -> Script-Fu -> Refresh scripts.

Once it is refreshed, the rule of thirds guide lines should be available under [Menu] -> Images -> Guides -> Photography.


Monday, February 11, 2013

Android framework debugging through IntelliJ

I had blogged earlier about using the Android Open Source Project (AOSP) to learn about the Android framework, and help debug your Android applications.

I missed out how easy it is to do this through IntelliJ, the other popular IDE.

IntelliJ is an IDE that was released in 2001, and has boasted an impressive feature set. It started out as a paid product and a community edition was released in 2009, along with source code licensed under the Apache License 2.0. A commercial version is still sold, and that includes enterprise support. For an Android developer's perspective, the community edition is a great product to use for all Android development. This post shows how to get set up and start debugging your project with full cross-references into the AOSP framework code.  This is a great way to learn the intricacies of the framework.

Installing IntelliJ IDEA


  1. Download IntelliJ IDEA community edition for your platform. Linux, Mac and Windows versions are available. At the time of writing this post, version 12 was the latest.
  2. Install it according to the instructions for your platform.

Set up JDK

Android development needs a Java Development Kit installed on the device. I choose to use Sun's Java 1.6, but you are free to use any JDK of your choice.
Configure -> Settings -> Project
It will say "No SDK". Click on New and select the path to your jdk. This is probably in /usr/local/sun-java-1.6, or somewhere else.


Set Android SDK

You should also have the Android SDK downloaded. If you need to download the SDK, notice that you need just the SDK for other IDEs, not the entire ADT. Say you unzip it into /usr/local/android-sdk-linux:
export ANDROID_SDK=/usr/local/android-sdk/linux

Create a new project on the previous screen.


On the following screen, create an "Android Application Module" and set the location of the Android SDK:

The project name doesn't much matter. You could create a Hello World project for the purpose of this guide. After clicking no "New", you need to set it to the path of the Android sdk, which is the location where you expanded the Android SDK zip file: ${ANDROID_SDK}.  You can change this setting later under  Menu bar -> File -> Other Settings -> Default Project Settings -> Platform Settings SDKs -> Project Structure.
This can also be set on a per-project basis. However, you should never need to change the SDK location. Instead, you can change the Build Target to the version of Android you wish to support. A single SDK location can hold multiple build targets (Starting from the earliest version of Android all the way to the latest.
At the end of this, you should have a Hello World Android project. IntelliJ supports looking up code sources if you have downloaded the sources with the SDK. To verify, run ${ANDROID_SDK}/tools/android
Select the sources for the Android build targets you need.

Debug with framework source

At this point, you are ready to debug using the framework source. Highlight any framework code (like Activity, or Context) and hit Ctrl+B. It will take you to the source for that class. Sometimes documentation can be vague, and the definitive word is the source. You can also use the source to learn how canonical classes like ListView or DialogFragment are written. Looking at framework code is a very powerful way of learning good coding practices and system paradigms.

Happy hacking!