Saturday, December 28, 2013

Game review: Little Inferno

I'm sick of casual games. Do repetitive stuff to get coins/stars/points. Spend points to get better equipment. Continue doing more repetitive stuff. After the first five minutes, they aren't fun at all. Games with in-app purchases are particularly bad, as they force you to do the same mindless chores again.

A few months ago, I had purchased a game called Little Inferno but I only just got around to playing it. It is brilliant. Estimating by the game content, I have played one tenth of the total content. Made by the same people who made the World of Goo, it is as enjoyable as my experience with the World of Goo.

The basic concept is boringly simple: you have a fireplace and you burn things. That gives you coins, with which you can purchase other things. But in a crazy twist, there are no in-app purchases. You get more coins when burning your things, so your cash keeps growing. Even if you somehow run out of money, there are small bugs that will give you coins for free. It gets even twisted...

There is no aim, there is no goal. You never lose.

You play for fun.

There is some story-line in the game, but that doesn't keep you going. What keeps you going is that this game is fun. You burn stuff, and it does interesting things. Sometimes burning things together does interesting things. It is difficult to explain why anyone would want to play it. Ever threw something in a camp-fire to see what happens? Well, this game is like that. You burn stuff, then head to your catalog to see what else you can burn. You could be done in five minutes and stop playing. Or you could burn stuff for hours. Either way, you get calm and enjoyment. That sets it apart from a significant chunk of the games already.

This game does two things which are remarkable. First, it has a commentary about the state of the world that unravels as you play it. I'm far from the finish, but the hints till now suggest an interesting message about the world we live in. The game is also a hilarious look at casual games, and how inane casual games have become. If it were that alone, it would be a gem. However, more importantly, this game is truly funny. The things you get are funny. The way they burn is funny. As it proceeds, the game introduces you to more elements. The instructions are funny, the in-game characters are funny.

Why must games be about the same boring concept? Why are half the games about being a soldier -- fighting or shooting? Computers are limitless: games should experiment and develop their own message and goals. How does it feel to be a honeybee? Maybe a game should allow you to find out.

Little Inferno is available from their product website. For the next two days, you can buy the Humble Bundle which includes Little Inferno. Runs on Linux, Android, Mac, Windows, toasters, ...

It is surprisingly, funnily, engagingly good. Now throw this review in a fire!


(Thermometer courtesy: Sugar Plumps)

Wednesday, December 25, 2013

E911 testing

A few months ago, I was working on a component that interacted with the Enhanced 911 dialing on a mobile platform. 911 is the emergency telephone number in the US for medical and law enforcement services. Other countries have something similar, like 112 in the European Union.

When I was developing my feature, I had to test out 911 functionality to ensure it was still working. My hope was to substitute the emergency number with something safe, like the number of my spouse. That way, I could call my fake emergency number without actually bothering the police.

I found that there are special requirements placed on mobile platforms for emergency dialing. Even if a GSM device does not have a SIM card, 911 dialing is required to work. An encrypted device does not have to be decrypted for 911 dialing to work, etc. Perhaps to ensure that the strict requirements are met, 911 dialing is handled directly by the telephony chipset. A mobile platform has little control over how 911 dialing works.

So, my testing plan wouldn't work. I would be forced to call 911. The real emergency number. Repeatedly. Now that was a scary thought. I had called 911 only once before that, for a true emergency. I wasn't looking forward to calling the emergency operators. When calling emergency operators, it is inadvisable to hang up immediately. This is for your own safety: you could be in a life-threatening situation. So 911 operators usually call you back or route the police to your location.

I developed a script that I would read out. The basic idea is to convey the following ideas as quickly as possible:
  1. It is not an emergency.
  2. You are an engineer testing stuff.
  3. This is your job, a routine matter for you.
  4. You are happy to be placed on hold.
The last part is important. 911 operators handle life-threatening emergencies all day and all night. They need to prioritize the events and dispatch them as quickly as possible. You want them to put you at the bottom of their priority list.

Here was my full script, which I now know by heart:
Hello, this is not an emergency. I am an engineer working at <company> testing out 911 functionality. Please tell me when to hang up.
While it is only three sentences, I am proud of my writing. The script conveys all the important points. It eliminates words, saving time. Instead of saying "Please let me know when it is safe to hang up", I chose a much more bland "Please tell me when to hang up." It avoids the tricky word safe, which could be misinterpreted to mean that I am in an unsafe situation. It introduces tell me to convey that I am at leisure to be instructed by the operator. Said in a calm and mechanical voice, that script accurately conveys my low rank in their priority list and my very routine intent. It lets the operator know that I am completely safe, and awaiting their instruction. I debated whether I should waste time with a Hello. Saying hello makes the conversation calm and highlights the lack of emergency. Removing it saves a second. After some thought, I kept it.

Somewhere around my second sentence, the operator would cut in and speak, "Please hold" and put me on hold.

There was no wait music.

I don't remember how long I waited, it was well over ten minutes on most calls. It was rare for me to finish all three sentences. On exactly one occasion, the operator listened to my entire script, and then said, "What do we do now?" I replied, "That's it. Please let me know when I can hang up." The operator allowed me to hang up, and we were both done.

On most calls, I was placed on hold.  I would hold the phone very, very patiently. I couldn't hang up, and I couldn't get distracted with something else. In addition, my phone had to stay charging because running out of battery would hang up the call. I couldn't attend a meeting or talk to a colleague. I couldn't go to the bathroom to relieve the stress of calling 911. On my first few calls I was tense. I was worried that I would do the wrong thing and cops would storm into my office building. Luckily, I didn't mess up. After calling them over a dozen times, these calls became routine. The stress involved with calling 911 for testing never went away though.

The operators were always calm and professional. They have to quickly evaluate the emergency of each call, determine the appropriate course of action, and move on to the next call. They don't have time to smile. They don't have time for pleasantries. During the testing, I developed great respect for their capacity. It must be a frustrating and stressful job: dealing with one difficult situation after another. Yet, they were calm, professional, and direct.

After I was off hold, the operator would sometimes quiz me on the nature of my testing. Sometimes they would ask what else was required of them. I was only testing outbound 911 dialing, so I required nothing else. After a polite and serious "thank you", I would hang up. I don't recall the operators ever thanking me or saying bye-bye. Like I said: no time for pleasantries.

My office-mates would perk up when they heard me call 911. It was a serious matter for everyone. Frankly, they were glad it was me making the calls and not them! For my part, I tried making the calls when the office was quiet and empty.

During the development of my feature, I called 911 frequently. I have lost count of how many calls I made. When the feature was done, I was glad to be done with 911 testing. It is one part of my software development I won't miss.


Qt Creator: a superb IDE for Linux

I learned programming in school with an ancient IDE: Turbo C++. I never got over the idea: the command-line is great for productivity, but there are times when you just want to explore. An IDE feels just right for such recreation. You can poke around and learn the environment. I developed an itch to test out a C/C++ IDE a few weeks ago.

Many people recommend Microsoft Visual Studio Express, and there is a free version for Windows XP. I spend most of my time on Linux machines so it would be a lot more useful to develop for Linux. In addition, my Windows XP machine is anemic compared to my Linux desktop. So I began looking for a good contemporary Linux IDE. Anjuta and QT creator both get good reviews. Anjuta was built for Gnome development, while QT creator focuses on the Qt toolkit. I am unfamiliar with Qt and have wanted to explore it, so I tried QT creator.

...and I found that QT creator is impressive! You can navigate to their web page or their Wikipedia entry to learn more. In short, it is a one-stop shop for project development, debugging, inspection. They have detailed tutorials through which you can learn the Qt toolkit. You can debug right from the IDE, inspect variables, set breakpoints.

My favorite feature is the integrated assembly debugging. You can get the disassembled output and step over an instruction at a time. You can view registers and it will highlight the ones that have changed after each line gets executed. This is a great way to learn assembly. The code is interspersed with assembly instructions. Even comments are included in the disassembly so you can find your way around. Now I wonder if we could install Qt creator on a Raspberry pi and use it to learn ARM assembly directly on the device. Here is a screenshot of the assembly output on the left and C++ source on the right. Pop quiz: what's my architecture?



Good C++ programmers understand what is going on under the hood. The innocuous line " : QWidget(parent)" produces a lot of assembly above because the child class (AddressBook) is initializing its parent (QWidget). Looking at the generated assembly code, you can learn the innards of C++, in addition to learning about your architecture. There are many books on 32 bit Intel assembly but few on 64-bit Intel assembly. So poking at toy examples is a great way to learn how something is implemented.

Qt creator integrates with good source control tools like git, subversion, ... And it integrates with memory analysis tools like valgrind.

This is an amazing tool, highly recommended for casual C++ hacking. Here's the full screenshot. You can click on it to expand the image.



Image courtesy: me.

Tuesday, December 17, 2013

Article about how children perceive pain

This is a brilliant article about how children perceive pain, and how to reduce their anxiety around a specific task. It is from a doctor who needs to address anxiety on a daily basis. From the article, it sounds like he has a great hold of the issue.

I won't paraphrase the article because the real article is much more valuable than isolated soundbites. It is a great read for parents: many difficult spots in parenting revolve around reducing anxiety and establishing rapport.

I am glad I am not a doctor in such a difficult role. I am also a little jealous about how much Dr. Baruch Krauss has gained from his experience. Luckily he can share his wisdom.

Sunday, December 08, 2013

A fun programming book: Land of Lisp

Do you want to read a fun programming book? Grab a copy of Land of Lisp.  Still undecided? Read on.


The recent explosion in programming languages and platforms has led to a similar explosion in books about programming. You can get a dozen books on each of a dozen popular languages: C++, Java, Python, PERL, Ruby, Scala, Haskellapackman.  There is a large variety of books, but I feel all of them miss out an essential ingredient.


None of them are any fun.

Remember fun? When you popped open an arcane book with funny cartoons and typed out a program filled with cryptic letters? And if you were right, the game worked!  You could change the source to see what happened.  That was truly fun: experimentation without an objective. You could imagine a wide expanse of possibility: there was so much a computer could do. Sometimes you typed hundreds of lines, and nothing worked. But that was fun too, in its own frustrating way. Sometimes you figured out how to make it work and felt very good about yourself.

Fast forward twenty years and modern computer programming is a mindless drudgery. Books are all about the techniques: how to combine five libraries to produce an XML parser. How to combine visual elements to make an application for a bank. None of these books would inspire anyone to learn a new language. They are all about how to get specific skills. Boring and dry, these books are made so a career software engineer can learn the buzzwords and stay employed for a few more months.

Learn <language> in 20 days: data types, branches, functions, objects, network programming, advanced techniques. That describes half of the books I see in bookshops.


So amidst this very boring scene I stumbled on The Land of Lisp. This book could be about an arcane and completely useless language and it would still be a lot of fun!  The book revolves around writing games in LISP.  Unlike old books containing BASIC code, the LISP code in this book is well explained and motivated. You can see why the author writes a specific function one way. Little functions are presented highlighting what their purpose is. You are told how to get CLISP and run code inside it. The games are fun! And there are cartoons.

Funny cartoons.
In a programming book about LISP. Hell just froze over.

This book gets you to enjoy programming. It could be written for Java or C++, and it would still be a lot of fun. Because programming, like any other hobby, is a heck of a lot of fun.  You could be a dentist and write code for fun. Isn't that a crazy thought?

To be fair, this book won't work for children. It is quite a detailed look into LISP, and requires a lot of motivation to get through. Children might enjoy looking at the cartoons (my kid certainly does) but they might not understand the intricacies (my kid certainly doesn't). It is like Calvin and Hobbes: a child will enjoy it but not understand a word.


For younger kids, a simpler book would be welcome. I'd love to see more books written in this style.  Let's make programming fun, and kids will learn it without any further incentive. A similar book on BASIC or Python might just work for young children. Yes, BASIC, that language nobody uses because grandpa won't stop talking about it. Well, that ancient language is still a lot of fun for children because children don't care about infix versus prefix, or cyclomatic complexity. They care about doing cool things with a computer. Children want to have fun while playing with their computer.


And while we are hoping, let's see more books like this for adults. I'm waiting for a book on Android programming or C++ that makes it fun!

(Image courtesy: Land of Lisp website)

Saturday, December 07, 2013

Simple program for a two year old child

I had blogged earlier about a program for a one year old.

Since then, my child has started identifying alphabets and has great fun hammering keys on his keyboard to produce letters. He has also started identifying numbers and lower case alphabets. Finally, he has strong preference on the color of the alphabets and the background.

So I present an update for my program, now for two year olds!

The basic structure is the same: it is a full screen GTK program that shows a number or alphabets. A number is shown in the middle of the screen. Alphabets are shown in both upper case and lower case. Finally, stars (an asterisk) is a recent favourite, so I allow typing that one special character. A brown bar at the bottom fills up as sleep-time approaches. This was useful in making the child aware of time: as the bar filled up, night time was approaching.

The full program is presented below.


#!/usr/bin/python

import datetime, 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."""
        # Start out by setting the current time
        self.set_time()
        ascii_value = data.keyval
        # Print the keycode received
        print ascii_value
        changedText = False
        # Lowercase alphabet should be shown as uppercase chars.
        if (ascii_value >= 97 and ascii_value <= 122):
            self.textBuffer.set_text(string.ascii_uppercase[ascii_value-97] + " "
                                     + string.ascii_lowercase[ascii_value-97])
            changedText = True
        # Uppercase alphabet should be shown as uppercase chars.
        if (ascii_value >= 65 and ascii_value <= 90):
            self.textBuffer.set_text(string.ascii_uppercase[ascii_value-65] + " "
                                     + string.ascii_lowercase[ascii_value-65])
            changedText = True
        # Numbers
        if (ascii_value >= 48 and ascii_value <= 57):
            self.textBuffer.set_text("%d" % (ascii_value - 48))
            changedText = True
        if (ascii_value >= 65456 and ascii_value <= 65466):
            self.textBuffer.set_text("%d" % (ascii_value - 65456))
            changedText = True
        if (ascii_value == 65450):
            self.textBuffer.set_text("*")
            changedText = True
        if (changedText):
            start = self.textBuffer.get_start_iter()
            end = self.textBuffer.get_end_iter()
            self.textBuffer.apply_tag_by_name("real_big", start, end)


    def realize_handler(self, widget):
        pixmap = gtk.gdk.Pixmap(None, 1, 1, 1)
        color = gtk.gdk.Color()
        cursor = gtk.gdk.Cursor(pixmap, pixmap, color, color, 0, 0)
        widget.window.set_cursor(cursor)

    def set_time(self):
        """Set the progress indicator to the current time.  The idea
        is to show time in a horizontal access with the morning being
        near the left edge and night being near the right edge."""
        current_time = datetime.datetime.now()
        # Total hours past since 6am
        # (Assume Dev wakes up at 6am)
        minutes_past = (current_time.hour - 6) * 60.0 + current_time.minute
        # Minutes are capped at 8am, which is when Dev goes to
        # bed. Expressed as minutes after 6am
        day_end = ((20 - 6) * 60.0)
        if (minutes_past < day_end):
            fraction = minutes_past / day_end
        else:
            fraction = 1.0
        self.progress.set_fraction(fraction)

    def __init__(self):
        """ Create a window with a single giant text view. Disables all chrome.
        """
        # Foreground and background color are read from here.
        background_color = "black"
        foreground_color = "#1133ff"

        self.w = gtk.Window(gtk.WINDOW_TOPLEVEL)
        # No border
        self.w.set_border_width(0)
        # 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)
        # self.w.connect("realize", self.realize_handler)
        # 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
        textView = gtk.TextView()
        # Disable a cursor in the text view.
        textView.set_editable(False)
        textView.set_can_focus(False)
        # Show the single character in the middle
        textView.set_justification(gtk.JUSTIFY_CENTER)
        # This is the place we will write the character to
        self.textBuffer = textView.get_buffer()
        # Make the text view huge and bold
        fontdesc = pango.FontDescription("monospace bold 400")
        textView.modify_font(fontdesc)

        # Creates a tag that is applied to the text every time
        tag = self.textBuffer.create_tag(
            "real_big", background=background_color, foreground=foreground_color)
        # The progress bar shows the current proportion of awake-time for a child.
        self.progress = gtk.ProgressBar()
        self.set_time()

        
        # Make the text view take the entire window
        vbox = gtk.VBox(homogeneous=False, spacing=0)
        color = gtk.gdk.color_parse(background_color)
        self.progress.modify_bg(gtk.STATE_NORMAL, color)
        self.progress.modify_fg(gtk.STATE_NORMAL, color)
        textView.modify_base(gtk.STATE_NORMAL, color)

        vbox.pack_start(textView, expand=True, fill=False)
        vbox.pack_start(self.progress, expand=True, fill=True)

        self.w.modify_bg(gtk.STATE_NORMAL, color)
        self.w.add(vbox)

    def show(self):
        """ Show the window"""
        self.w.show_all()
        # gdkWindow = self.textView.get_window(gtk.TEXT_WINDOW_WIDGET)
        # display = self.textView.get_display()
        # cursor = gtk.gdk.Cursor(display, gtk.gdk.BLANK_CURSOR)
        # gdkWindow.set_cursor(cursor)


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

Wednesday, July 31, 2013

MSP430 Serial communication with LInux

In addition to hacking on Arduino, I am interested in other hobbyist microcontroller boards. One of the more promising ones is the MSP430 Launchpad by Texas Instruments. It is a tiny kit with interchangeable microcontrollers, and it runs great on Linux with an IDE called Energia.  Energia is a fork of the Arduino IDE so it should be familiar to most microcontroller hackers.

One downside to the Launchpad is that serial communication for the board don't work on Linux. The problem seems to be that the USB-serial emulation on the launchpad has a bug.  A person on the forums found that the Launchpad device is requesting a disconnect shortly after connecting. Gerald Stanje has an updated cdc-acm kernel module that ignores these disconnects.  That option works in case you don't mind installing a new kernel module. Also, remember to use the normal cdc-acm kernel when using devices other than the Launchpad.

External USB-serial device

A second solution is to purchase an external USB-serial translation device. There is a glut of cheap USB-serial converters available on online sites. Here is one such device based on the PL2303 chipset that costs less than $3, including shipping. If you buy such a device, you can bypass the USB-serial translation on the launchpad and use the PL2303 (or FTDI) based chip.

To use this method, disconnect the jumpers RXD and TXD jumpers that cross the Emulation - MSP-EXP430 line. Then, connect the lines as follows:

  1. GND on USB device to GND on Launchpad
  2. TXD on the USB device to RXD on the Launchpad
  3. RXD on the USB device to TXD on the Launchpad
  4. 5v on the USB device to a solder pad TP1 on the Launchpad near the Launchpad USB connector. This will power on the entire Launchpad device.
Using this, you should be able to communicate with the launchpad. To program it, connect the USB connector to your desktop as before.

This method doesn't require a new kernel module. In addition, this method works with any microcontroller board that can do serial communication: either through hardware UARTs, or through software.

Sunday, July 28, 2013

Tip: External editor for Arduino

I love Arduino: it is the perfect microcontroller platform. It is easy to program on Linux, cheaply available, there is a library for most anything you can think of. And the community is great for when you get stuck.

My only grudge: The Arduino editor doesn't match up to Emacs.

Yes, the IDE is great, but for large programs I find myself yearning for a C mode, proper indenting, incremental search, buffers. You know, a real editor.

Makefile for Arduino

So I experimented with using Emacs and compiling from the console. After experimenting with a few Makefiles, OpenXC works great for me. Clone their project, and set up environment variables according to your setup. I had to change exactly zero variables for their examples to work out of the box on Ubuntu. The Makefile is well documented. You can upload the program to an arduino by doing 'make upload'. This works with simple sketches and for doing everything through a shell script or cron.

It has limitations. It won't do pre-processing: so it will claim that methods or data structures are not defined. It won't work with multiple .ino files. Also, the list of boards is limited, and it doesn't have an easy way to specify Arduino Mini with 8Mhz, which is the device I'm currently hacking on.

External editor for Arduino

Navigate to:
File -> Preferences -> Use external editor.

This should gray out your editor window. Now, your Arduino IDE is only for compiling, uploading, and for the serial monitor, which it excels at. To save screen real estate, you can make the window short, though it wants to be a minimum height. Now edit it in your favorite editor.

When you are ready to compile, switch to Arduino (Alt-Tab), and then compile (Ctrl-R) or upload (Ctrl-U).

I'm waiting for Arduino to tie in with inotify on Linux and automatically compile when the code changes.  But in a pinch, this workflow gets over most of the annoyances of the Arduino IDE while retaining most of its advantages.

Makefile + External Editor

The best approach might be to combine the two above. Switch to an external editor in Arduino, and use a Makefile for automated builds on the command-line. The automated builds on a console will quickly let you know if your incremental edits introduced a compilation bug. And when you want to upload it to your boards, switch over to Arduino IDE.

Monday, July 22, 2013

SoundSleep source code

A while ago, I had developed an application to continuously play music on my phone.  The program is called Sound Sleep and is available for free on the Android store. I use this application every night to play sleep-time music for my child.

I have now put the source code to Sound Sleep online. The entire Android source code for Sound Sleep is available at Github under the Apache License version 2.

To clone the entire repository:
$ git clone https://github.com/youngelf/sound-sleep.git

This source is great for learning how to program with Android. It demonstrates:
  1. Running on a wide variety of Android devices.  The minimum SDK version is 3, and I use this on an ancient phone with Android 1.6
  2. Using SD card storage to read music
  3. Setting up a new service and communicating with it using Local Broadcasts
  4. Playing music from Android applications

I'm happy to accept patches and suggestions. I have used it daily since March, and it has been rock solid and indispensable.  It has exactly the feature-set I need. Here is a screenshot of the application.  There are two controls: the top half plays music randomly from SDCARD/music/sleeping. The bottom half plays white noise.

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!

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!