Wednesday, 31 October 2012

CleverDic 1.06 Released

CleverDic on Google Market

The latest version of CleverDic, the crossword solver app, has been released. The user interface has been revamped to give a smarter and cleaner appearance. The background now has a sky blue gradient and there is a status bar that indicates the number of matches or if the app is busy searching. The keyboard automatically disappears after you press search or enter.

The text field on the main screen has now been replace with a list. This meant I had to provide help and information in other ways. I've created a help screen and one time only  welcome dialog that shows a simple help message.

You can now look up the word definitions by touching the words. This works by opening up the web browser and performing a special search through Google. For example, to look up the word android, the app will now browse to this URL:

To help gather user feedback and to promote other apps, I've added an about screen. The screen shows icons for Facebook, Twitter, Blogger and Google Android Market.

Other refinements include switching off the auto-rotate feature, this was just annoying, the app remains in portrait mode now.

For the next release I'm considering adding a settings screen to allow the user to select the background colour, the maximum number of  words shown and turn on/off the sub-anagrams feature.

Happy Crosswording!


CleverDic on Google Market

Sunday, 28 October 2012

New Website

I've set up a new website for Pig Dog Bay:

For now it contains the Pig Dog Bay logo and links to:

Android Market




The idea is to promote my Android apps and more importantly to gather feedback from users so that I can make improvements. This blog will contain technical articles about software engineering and information about my Android apps, hopefully readers will be able to share their ideas and knowledge as well.

My goal is to see if I can make a living from writing Apps for Android, any tips or advice would be greatly appreciated. I won't be giving the day job up just yet though.

C# versus Java

Recently I bought a Google Nexus 7 tablet and so immediately entered the world of Android development. My old friend Java beckoned, and it seems that Java has not kept up with modern programming developments.

Functional Programming

This paradigm has completely passed Java by. C# supports Lamda expression, you can pass functions as parameters to functions, return functions from functions and proper closures (making local variables available to the lamda function). The best you can do with Java is anonymous inner classes, clumsy and lots more typing.

There is no LINQ or IEnumerable<> interface equivalent in Java, however Java does have its own version  of the foreach statement.

Clean up

I like C#'s IDisposable clean-up pattern, OK its not perfect especially when you need to share a resource.
The great thing about tidying up resources in C# is the using statement. The latest version of Java has implemented something similar using try{}, not available for Android Java though, hmm.

String or string

I'm forever typing string instead of String in Eclipse, gahhhh! I can see why now C# now uses boxing it makes things simpler if you also regard types such as int and floats as objects. I also hate having to use NumberFormat to format ints/longs/floats into strings, just have ToString(), oh they can't in Java because they are not objects.


When I first started writing C# I couldn't believe how lax it was as you didn't need to say what exceptions a function throws. Going back to Java, having to either catch exceptions or declare them is a real pain in the A. I can see this leading to bad practices such as programmers using try/catch around every piece of code, thus hiding problems.


User clicks the button, so you need a click listener? That means implementing an interface or using an anonymous inner class in java. I consider C#'s built in event keyword a superior, simpler and more concise alternative to the Observer pattern. Also C#'s extension methods are a great alternative for the Visitor pattern, which you can't really achieve in Java (or in C# using OOP techniques) due to the lack of Multiple Inheritance.


I use Netbeans (or MPLAB X) for PIC development and it is great. VS2010 with CodeRush is just heavenly. What the heck is Eclipse? A throw back to the 1990's? Eclipse is not pleasant to use, I find it slower to type code, I hate having to hover over a red squiggle to see the bug info, intellisense is slow or non-existant and it has another bunch of key-strokes to learn. I do like Eclipse's auto fix feature though and it does seem to auto-generate boiler plate in an intelligent fashion. Eventually I'll grow to like it, maybe!

Final Thoughts

C# has developed into a multi-paradigm language where as Java seems to have stayed stuck. I guess Sun's demise has not helped Java's cause, it would of been better for Google to have bought Sun instead of Oracle. I once loved Java, my first OOP language,  I scorned C# as a rip off of Java, but now it is clear C# has features that fix many of Java's flaws. Pity C# is a Microsoft technology though.

Thursday, 25 October 2012

Embedded C Timing Functions

This post is about simple timing functions written in C for embedded processors or micro-controllers such as PICs. The timing functions here are a delay function and function that you poll to see if a set amount of time has elapsed.

The most basic timer feature I have seen is a global variable, or tick count, that is incremented every time a timer interrupt is fired. The problem here is if another piece of code interferes with this variable or if the timer interrupt fires during the read of the tick count value. The code below instead safely wraps the tick count and returns a structure. The code is written for the CCS  C compiler for PIC micros.

#ifndef TIMING_H
#define TIMING_H

#include "defines.h"

typedef struct
 uint32 Duration;
 uint32 StartCount;
 uint32 EndCount;
} TimerInfo;

extern void OnTick(void);
extern uint32 GetTickCount(void);

extern void StartTimer(TimerInfo* timerInfo, uint16 duration);
extern bool HasTimerElapsed(TimerInfo* timerInfo);
extern void TimerWait(uint16 duration);

#ifdef _DEBUG
 void SetTickCount(unsigned int32 tickCount);

//Include guard


 The aim of this code file is to implement a background timer in a safer manner by
 making the TickCount read-only.

 To perform a timed task:

 TimerInfo timerInfo; 
 StartTimer(&timerInfo, 42);
   //perform some task

#include "Timing.h"

volatile static uint32 _TickCount = 0;

uint32 GetTickCount(void)
 uint32 nonVolatile;
 nonVolatile = _TickCount;
 return nonVolatile;

 Call this method from the timer interrupt to increment the tick count.
void OnTick(void)

 Call this method at the start of a timed task.
  TimerInfo timerInfo = StartTimer(42);
  while(!HasTimerElapsed(timerInfo)){//perform some task}

 Inputs:  duration - number of ticks to wait for
 Returns: TimerInfo - A structure holding the relevant timer information
void StartTimer(TimerInfo* timerInfo, uint16 duration)
 timerInfo->Duration = duration;
 timerInfo->EndCount = timerInfo->Duration+timerInfo->StartCount;

 Poll this method to determine if the timer has elapsed.
  TimerInfo timerInfo = StartTimer(42);
  while(!HasTimerElapsed(timerInfo)){//perform some task}

 Inputs:  TimerInfo - Timer information as returned by StartTimer()
 Returns: bool  - True timer has elapsed, false - timer has not elapsed

bool HasTimerElapsed(TimerInfo* timerInfo)
 uint32 tickCount = GetTickCount();
 //Timer info uses uint32, but the logic still needs to be able to cope with overflow.
 if (timerInfo->EndCount >= timerInfo->StartCount)
  return (tickCount>=timerInfo->StartCount && tickCountEndCount) ? false : true;
 return (tickCount>=timerInfo->EndCount && tickCountStartCount) ? true : false;

 Wait for the specified number of ticks
 Inputs: duration - number of ticks to wait
void TimerWait(uint16 duration)
 TimerInfo timer;
 StartTimer(&timer, duration);

#ifdef _DEBUG
  Allow unit tests to manipulate _TickCount
 void SetTickCount(uint32 tickCount){ _TickCount=tickCount;}
The tick count is marked as volatile, this warns the compiler not to optimize the use of this variable and to always read from its memory location. You'll notice that I disable and then enable interrupts when reading the tick count. To increase the tick count you call OnTick() from your timer interrupt sub-routine, I've marked this function as inline to save doing the function call.

To use the code, you first need to get a TimerInfo which contains the start time, and then pass the TimerInfo to HasTimerElapsed() which returns true, the time has elasped, or false, the time has not elapsed. See my previous posts about C Type defines if you're wondering where the bool has come from.

You can easily port the code, but you will need to replace the #inline pre-processor and the disable/enable interrupt calls.

Embedded C, Defining Common Types

How do you write portable C code that you can use on any processor architecture or compiler and even unit test such code on a Windows PC? This is one problem I've been addressing over the last year or so as I've written firmware for several processor architectures  PICS, Renesas H8's and Infineon 166.

The first problem is that an int can be 1,2 or 4 bytes in size and it depends on the compiler, processor and OS. In this post I'll show how to use precisely defined types that you can use throughout your code so that you will not need to worry about the size of types.

Common types that you will use are signed and unsigned ints, so these will need to be defined and standardized:

Signed ints: sint8, sint16,sint32, sint64
Unsigned ints: uint8, uint16, uint32, uint64
For floating point I use, float32 and float64

The C language is missing the bool type, so I define this as well, which is great as I can now mix the embedded C code with the C++ unit test harness code running on my Windows PC. I also prefer returning a bool instead of error codes so as to keep things simple.

Here is an example of my defines.h that I use when writing C projects for PIC micro-controllers.

#ifndef DEFINES_H
#define DEFINES_H

#ifdef WIN32

typedef char   sint8;   // -128 T0 127
typedef unsigned char uint8;  // 0 TO 255
typedef signed short sint16;  // -32768 TO 32767 
typedef unsigned short uint16;  // 0 TO 65535
typedef long   sint32;  // -2147483648 TO 2147483647
typedef unsigned long uint32;  //0 TO 4294967295
typedef float   float32; //(1.4012984643248171e-45f) to(3.4028234663852886e+38f)
typedef double   double64; // 4.9406564584124655e-324 to 1.7976931348623158e+308

//A byte is a one byte unsigned integer
typedef unsigned char BYTE;
//A double word is a four byte unsigned integer
typedef unsigned long DWORD;
//A word is a two byte unsigned integer
typedef unsigned short WORD;


typedef signed int   sint8;   // -128 T0 127
typedef unsigned int                    uint8;  // 0 TO 255
typedef signed long   sint16;  // -C32768 TO 32767
typedef unsigned long                   uint16;  // 0 TO 65535
typedef signed long long                sint32;  // -2147483648 TO 2147483647
typedef unsigned long long              uint32;  //0 TO 4294967295
typedef float    float32; //(1.4012984643248171e-45f) to(3.4028234663852886e+38f)

//A byte is a one byte unsigned integer - already defined in CCS compiler
//typedef unsigned int BYTE;
//A word is a two byte unsigned integer
typedef unsigned long WORD;
//A double word is a four byte unsigned integer
typedef unsigned long long DWORD;

typedef unsigned char   bool;
#define true    (bool)1
#define false    (bool)0


//C definition of null is (void *) 0, for C++ it is just 0
#ifndef NULL
 #ifdef __cplusplus
    #define NULL 0
    #define NULL ((void *) 0)

//Include guard

In my future embedded C posts that I'll be using these types, eg sint16, in my example code.

Wednesday, 24 October 2012

Android Scaled Images Tool

Android supports 4 screen types, extra high, high, medium and low density. Extra high density means that the screen has a higher number of pixels per inch than a lower density screen. If you have images in your app then you need to provide images for each screen type, so that the image size will remain consistent.

My approach to doing this is first create my extra high definition image and then resize it for the less dense screen types:

High Density - Reduce Image to 75% of the original size
Medium Density - Reduce Image to 50% of the original size
Low Density - Reduce Image to 37.5% of the original size

 I start with the top most image and then reduce it in size to create the other images. On your computer screen each image is becoming smaller, but on a Android phone with a low density display and a phone with a high density display will pick the right image so that to the user they appear the same physical size.

I've not found a tool yet on Eclipse to actually resize the images for me so I created my own. Its a .Net tool for Windows, you can download it from:

The tool is called AndroidScaledImages.msi

I've had a few issues with creating a shortcut in the users StartTo menu (a technical issue to do with advertised shortcuts being default in MS Setup). Anyhow you will need to create a short cut to the AndroidScaledImages.exe file in your Send To folder. To do this.

  1. Open the start menu
  2. Go to run / search
  3. Enter shell:sendto
  4. Now open a new explorer window
  5. Navigate to the program files\pig dog bay\Android Scaled Images
  6. Create a short cut to AndroidScaledImages.exe and drag it into your send to folder.
Once done, you can right click your extra high def image, send to, AndroidScaledImages.exe - shortcut
The high, medium and low density images will then be created in the same directory as the image you clicked. You then move each image into corresponding apps res/drawable folder, and then rename them all to the same name.

The tool is very simple and the source is below in case you want to role you own. If anyone has a better way of creating the lower density images,e.g. from Eclipse please let me know.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace AndroidScaledImages
    class Program
        static void Main(string[] args)
            if (args.Length != 1)
            if (!File.Exists(args[0]))
            string filename = Path.GetFileNameWithoutExtension(args[0]);
            string path = Path.GetDirectoryName(args[0]);
            Bitmap bitmap = new Bitmap(args[0]);
            Bitmap high = ResizeImage(bitmap,0.75);
            Bitmap medium = ResizeImage(bitmap,0.50);
            Bitmap low = ResizeImage(bitmap,0.375);
            high.Save(Path.Combine(path,filename + "_h.png"),ImageFormat.Png);
            medium.Save(Path.Combine(path, filename + "_m.png"), ImageFormat.Png);
            low.Save(Path.Combine(path, filename + "_l.png"), ImageFormat.Png);


        static Bitmap ResizeImage(Bitmap original, double ratio)
            double w = (double)original.Width;
            double h = (double)original.Height;
            w = w * ratio;
            h = h * ratio;
            Bitmap resized = new Bitmap((int)w, (int)h);
            using (Graphics g = Graphics.FromImage((Image)resized))
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(original, 0, 0, (int)w, (int)h);
            return resized;