Monday, 22 December 2008

Dell Studio

After aprox 9 months using my EEE PC I have upgraded to a proper laptop. Whilst my EEE PC was handy in lectures for following slides and for watching BBC iplayer it was not really up to much else (viewing PCB layouts on 7in of screen is almost impossible). This was really apparant last week when i had to work on the Student Robotics hardware. I was forced to use it as not much more than a dumb terminal from which I could shell into the SR server, Rob's desktop computer and the slug in order to get anything done. This was really painful and so I bought a Dell Studio laptop which has 15in screen amongst other benefits.

It arrived three days ago with Vista preinstalled. I subsequently shrunk the Windows partition to make way for Fedora 10. I decided to make the switch from Ubuntu to Fedora for no significant reason other than change - and to simplify setting up the MSP430 tool chain. So far so good.

Setting up dual boot was considerably easier this time. This is because I cheated and used a third party windows bootloader tool to set it up. Although there are undoubtedly 'better' ways of doing this, I found EasyBCD really simple to use. There are even Fedora specific instructions for how to do the install. My first attempts at dual booting Ubuntu/XP a year ago, required at least two reinstallations of the MBR (mainly becuase i didn't know what i was doing) so this tool was a welcome change.

Sunday, 30 November 2008

Servo Board V2 Firmware

I have spent today fighting gdb and gdb-proxy in an attempt to update the firmware for the PWM board (Servo board). I spent the first two hours going 'aargh' because msp430-gdb kept issuing me with missing data stack errors and empty symbol tables. Eventually from looking at last years code i was able to view work out what was wrong. Weirdly, adding a static variable into my code (which was only assigned to once) was enough to solve my problem, however this makes no sense why.

The reason the firmware needed upgrading is because we have put a beefier MSP micro-controller on the board, subsequently the board layout has changed. Once I got my head around both the motor controllers i2c routines and the old pwm firmware i began merging bits of code together. After a suitable amount of time, anger, coffee, realisation of how stupid i was being and more coffee, I managed to get the new board to seep all the servo pins back and forth, demonstrating that this part of the board works.

Enjoy the video - I did!

Some Photos:

The new servo board. The two LEDs indicate both power supplies are connected. The third LED which isn't illuminated, should be, however due to some primate-like soldering skills, there appears to be a short.

The servos in motion.

The MSP430 programmer. I mounted it on an old credit card to make the wiring a little more secure. Despite it looking horrible, it actually works surprisingly well. Honest.

Saturday, 29 November 2008

Tongue Extraction

I have just completed my first ever Dynamic Programming project for Intelligent Algorithms module COMP3032. The task was to extract a contour which corresponds to the human tongue shown in the ultrasound image shown below:

The first step was to narrow the search area by applying some boundary conditions. The red points in the image above represent these conditions. The region is extracted by joining up the points and sampling along the lines. Next an energy functional was defined to describe a 'good contour'. An optimal contour will be smooth and have high intensity. The end result is shown below (Note: pixel values have been inverted i.e. negative image):

The contour is a good representation of the tongue and because the energy functional places equal emphasis on smoothness and intensity, it is not affected by the noise (high intensity pixels near the centre of the search area). With a week left before the deadline I hope to improve the computation time and experiment with changing the various parameters.

Sunday, 23 November 2008

Trouble in Ambridge

My Dad likes the Archers, so does my mum. Up until about 5 years ago, My dad would record the omnibus onto cassette for playing in the car during commutes to work and back, likewise my mum would listen to it in the house on the hi-fi. Then my dad bought a car without a tape player, so I taught him how to record the omnibus using his computer (connected to the hifi with a line-in cable), this worked but required editing the audio file in Audacity which my dad never got on well with.

Finally earlier this year my Dad entered the 21st Century and began downloading the archers podcast from the BBC website. This was by far the simplest and quickest way. This was until the company my Dad works for banned multimedia content downloading on the company network. The only other connection in the house is dial-up so i promised to develop a work around.

I have written a python script which parses the RSS feed for the archers podcast, extracts the .mp3 links, downloads them to a temporary directory, compresses them into a single zip file which, with the help of a bash scrip, gets uploaded to my University web space for my dad to download every Saturday. The script is shown below, but the reason I blog about this is because for the first time in my linux lifetime, I have written a script to do a task in less time that it would have taken to just do it manually! (hence time to blog)

The only remaining task is to get the script to trigger automatically every Saturday without me having to remember. But Google calendar reminders will suffice for the time being!

import feedparser
import urllib
import os
import zipfile

TEMP_ADDRESS = "/tmp/archers/"

feed = feedparser.parse(ARCHERS_XML_URL)

shows = feed["entries"]
episodes = []

for show in shows:
mp3_url = str(show["links"][0]["href"])
print "Retrieving: "+mp3_url
fname = os.path.basename(mp3_url)
f = urllib.urlretrieve(mp3_url, TEMP_ADDRESS+fname)
except IOError:
print "Couldn't retrieve file: "+mp3_url


all = zipfile.ZipFile(TEMP_ADDRESS+"", 'w')
for file in episodes:
print "added "+file+" to zip archive"
print "Faile to write "+file+" to zip archive"
all = zipfile.ZipFile(TEMP_ADDRESS+"", 'r')
if all.testzip() == None:
print "succesfully wrote episodes to zip file"
print "failure writing episodes to zip file"
print "end"

Monday, 27 October 2008

*tex Pain

I've just finished writing my first report in Latex. I have also just experience Bibtex, the referencing package. The idea seems simple; keep the reference details and main content separate; and let Bibtex process it and pump out a correctly formatted bibliography.

The reality is that you will spend hours chasing horrible error messages from Bibtex about undefined references due to the minefield of possible syntax errors. The lesson is, use a proper latex editor in combination with some form of reference organiser to remove some of the pain.

Having said all this, i will definitely be using Latex in the future, primarily because it prevents me from getting distracted with formatting whilst writing the report. The end result is also much prettier.

Monday, 13 October 2008

2D CAT scan emulation software

A draft of the brief for my 3rd Year Project:

Recently the principles of CAT scanning have been transferred to non-medical applications. Examples of this include using GPS satellites to map weather in the ionosphere as well as scanning for oil and gas reservoirs. Typically in these environments it is not possible to move the scan points nor to scan the target from all angles. With such restrictions it is possible that large, important structures may not be resolved by the scanning process.

The objective of this project is to write a software tool to emulate the scanning, interpolation and processing stages of computer aided tomography. This tool will then be used to study the effects of restricting the number and position of scan-lines on the final reconstructed image.

The inputs to the program will be:
  • A bitmap of arbitrary size and colour depth that will be used to represent the 2D object being scanned.
  • A text file fully describing the position and orientation of the scan points.

The program will output:
  • The raw scan data
  • The reconstructed image
  • The reconstructed image after image processing
  • A measure of the similarity of the target and scan image

The program will have the following variables:
  • Position and number of scan lines
  • Absorption model – additive/integral
  • Image manipulation techniques – applied after interpolation
  • Target/Image comparison techniques – a selection of methods to evaluate the accuracy and resolution of the scan output
  • Batch processing

The goal of this project is to design an appropriate set of test images and scan configurations to be processed by the emulation software. Theses tests should highlight the circumstances that lead to important data within the target image being lost as a result of the scanning process. The results may then be used to comment on the suitability and effectiveness of CAT scanning in a range of real-world non-medical applications.

Thursday, 9 October 2008

A Better Timetable

The Problem:

The university timetable (at Southampton University) is rubbish. A flat PDF with cryptic course codes and building/room numbers which require at least two other resources to translate into any sort of geographical location. If you are in a hurry (which i usually am when looking at a timetable) not only is it extremely irritating having to log in to various portals (none as exciting as Narnia) just to get at some pretty simple info.

The Solution:

A web based timetable which integrates all the info in one place. The steps involved:

  • Upload the rubbish PDF file downloaded from university website.

  • The file is processed on the server and converted into a database table format

  • All user-identifiable information is stripped from the pdf

  • The user then selects a memorable identifier that identifies their timetable, there is no need for a password (cannot link student number/name with timetable)

  • The user or someone the user has shared their timetable with goes to the site eg.

  • The page then shows the 'now & next' lectures. Each one shows the building number and name and on click highlights the building on the map

  • you can browse the weeks timetable and add extra lectures (tutorials etc.) and 'week specific' events (non recurring)

  • There is a mobile version of the site adapted for the small screen

I just wish i had time to actually do this :-( , perhaps sell it to the uni when it becomes a roaring success

Tuesday, 16 September 2008

This is not just Sardines On Toast ...

Here's something that I made up this lunchtime, and it tasted good so I thought I'd share it.


  • Bread

  • Tin of Sardines

  • Sun-dried Tomatoes (paste)

  • Worcestershire Sauce

  • Basil

What to do

  1. Lightly toast the bread under a grill for just over a minute on each side

  2. Remove the bread and spread a thin layer of sun-dried tomatoes on each slice

  3. Return to the grill for a minute

  4. Meanwhile, remove the bones from the sardines and break them up gently with a fork (keep as much of the sauce as possible

  5. Sprinkle some chopped up basil onto the bread and then add the sardines

  6. Sprinkle some more basil on top and return to the grill for another minute

  7. Add Worcestershire sauce to taste, eat immediately

Tuesday, 19 August 2008

Your Thoughts?

A (virtual) penny for your thoughts...

Do you like the new site Banner?
Yes (Strongly)
Yes (Half Hearted)
No (Nonchalantly)
No (Vehemently) free polls

Diving into C++

My first C++ script to practice string manipulation, standard input/output and formatting. It compiles with GCC using g++ [name.c] -o [name] under linux. Note that to meet ANSI C compliances, it is necessary to use not in the preprocessor directives, hence library function calls are prefixed with 'std::'. Using the 'using namespace std;' statement removes the need to prefix iostream objects/methods with 'std::' - similar to C#.

// Copyright (c) Christopher Cross 2008
// Format Name to fit within
// confines of Envelope window
// (An example of C++ string/cin/cout manipulation)


#define INCOME_TAX 40

void fitOnEnvelope(char * first, char * last);

using namespace std;

int main(void)
char firstName[FORENAME_LENGTH];
char lastName[SURNAME_LENGTH];

cout << "Enter First Name:" << endl;
cin.get(firstName, 15);
cout << "Enter Last Name:" << endl;
cin.get(lastName, 15);
fitOnEnvelope(firstName, lastName);
return 666;

void fitOnEnvelope(char * first, char * last)
int size = strlen(first) + strlen(last);
char border[4] = "***";

if(size < (ENVELOPE_LENGTH - 1)) //allow for \0
cout << setw(ENVELOPE_LENGTH)
<< setiosflags(ios::right)
<< first << " " << last << endl;
char abbrev[ENVELOPE_LENGTH-3]; //allow for wspace, period, \0
strcpy(abbrev, last);
cout << setw(ENVELOPE_LENGTH)
<< setiosflags(ios::right)
<< first[0] << ". " << abbrev << endl;

Sunday, 3 August 2008

Hack, Anyone?

Here's an easy and pointless hack. You will need:

  • Poor quality PC speakers

  • Strong elastic band

  • No headphones nearby

You can see where this is going...

Dolby 2.0?

Saturday, 2 August 2008

Reading List

In an attempt to become more cultured I have compiled a list of books I want to read this year:

  1. One Flew Over the Cuckoo's Nest - by Ken Kesey

  2. Crime and Punishment - by Fyodor Dostoyevsky

  3. Lady Chatterly's Lover - by D.H.Lawrence

  4. Wuthering Heights (Signet Classics) - by Emily Bronte

  5. Of Mice and Men - by John Steinbeck

  6. Dr. Jekyll & Mr. Hyde - by Robert Louis Stevenson

  7. Old Curiosity Shop - Charles Dickens

  8. The Turn Of The Screw - Henry James

  9. Emma - Jane Austen

  10. The Grapes of Wrath - John Steinbeck

  11. Three Men in A Boat - Jerome K. Jerome

  12. On The Road - Jack Kerouac

  13. Alice in Wonderland - Lewis Carroll

  14. The Picture of Dorian Gray - Oscar Wilde

  15. The Communist Manifesto - Karl Marx

  16. The Time Machine - H.G. Wells

  17. The Invisible Man - H.G. Wells

  18. The Day of the Triffids - John Wyndham

  19. A Clockwork Orange - Anthony Burgess

  20. A Tale of Two Cities - Charles - Dickens

  21. Subterraneous - Jack Kerouac

  22. Death of a Salesman - Arthur Miller

  23. Treasure Island - Robert Louis Stevenson

  24. The Illiad of Homer - Homer

  25. War and Peace - Leo Tolstoy

Friday, 1 August 2008

I've Missed You Blighty

For the past 35 days I have been interralining around Europe, stopping at major cities and sleeping in cheap hostels. I have seen 1.5Gb of tourist stuff and eaten an unhealty amount of Salami and Ice Cream (although never at the same time - thats just silly). Now I am back, and I have never been so glad to be back in England. Whilst my travels were fun and educational (travelling really does broaden the mind), they were nonetheless tiring and exhaustive.

My contact with the outside world has been limited. Very limited. I had a mobile phone with a UK only SIM and a collective total of 90min of internet cafe time. Despite my undeniably unhealthy addiction to the internet and my computer I missed neither whilst away. Even being unaware of the latest headlines and tabloid playthings was of no concern to me. Now that I am back in the country (still devoid of a permenant internet connection and my computer) the usual distractions are creeping back into my daily routine.

My travel photos are available, unfortunately on Facebook only (i love flickr, but I only have time to upload to one site, and I've got fbook-only friends to please). They can be found here: Part III, Part II, Part I. But what have I actually learnt from this trip??

  • It is possible to eat Ice Creams every day for 35 days continuous and not put on weight

  • Europe is expensive

  • The Interrail pass does not always work out cheaper than buying tickets ad hoc. Hefty reservation fees soon add up, especially in Italy, Greece and on sleeper trains

  • The leaning tower of Pisa is tiny - There is nothing else to do in Pisa

  • Florence is dull and I cannot imagine it not being 'overcast'

  • The Berlin TV Tower is overprice for what it is

  • European trains sometimes have splitting carriages. Always check that you are in the correcct car before the journey.

  • Greecians are not all friendly

  • Venice, in places, smells

  • I like Oscar Wilde

  • Sleeper trains are termed sarcastically (I do not sleep well on them)

  • Prague is very much 'hyped'

Salvidor Dali, before the Prage Castle

Thursday, 5 June 2008

apt-get install linux

I have an EEE PC. However until last week something just wasn't quite right. Here's a story about my tenuous relationship with Linux.

My experience with Linux is very much a love hate one. I'd love to love Linux, but Linux just isn't making this easy for me. My first experience with it was only a little over a year ago when I eagerly launched a live CD - at the time, I wasn't really sure what that was - but I must admit it was impressive. Gutsy Gibbon ran like a panther compared to XP, which, constrained within the confines of a Dell Dimension 3000, was (and still is) just 'putting on a brave face'.

Eager to release Ubuntu from the limitations of its live CD, but cautious of upsetting the fragile but dependably unreliable XP, I concluded the way forward was to install it on an external hard drive. Don't do this. I did and it worked for a day. The problem was, of course, unquestionably due to my naivity in thinking I knew what I was doing. Because the bootloader 'Grub' was installed on the external drive, a delicate 'ballet' of switching things on was required to get beyond the boot menu. Eventually even this failed and XP came to the rescue by rebuilding the MBR.

Knocked slightly by this, I sat in the familiar but uncomfortable gardens of XP which always booted, rarely crashed and talked to every piece of hardware I owned. Over time and with every unresponsive window and XP 'quirk' my resentment towards Windows grew. One night, with a still-warm CD of Gutsy I slowly built up the confidence to repartition my internal drive and do a fresh install of Linux. All went to plan and as the days went on Windows made its way further and further down the Grub boot order.

And then along came Hardy Heron. Brilliant! An overnight upgrade later and then bye bye Linux. First it takes an age to log in, then parts of the desktop are missing, and finally I can't get past the splash screen. Undeterred and giddy with the success of installing Ubuntu, I bravely entered the 'Fail safe terminal' where I diagnosed the fault to lie with Gnome. Convinced with my prognosis and inspired by forum posts I sudo apt-get'ed my way to reinstalling Gnome. Don't do this. It doesn't work. Apparently apt-get remove gnome; apt-get install gnome; isn't big, and certainly isn't clever.

Xandros on the EEE PC

Crawling back to XP, I dismissed Linux as 'not for me'. Then along came the EEE PC, with Xandros pre-installed. Dressed up to look like XP, Xandros is poor visually, but more importantly, poor functionally. The package repository was pathetically small and restrictive. Nonetheless I messed around in terminal apt-getting myself around, hoping to find programs to do the jobs I wanted. This all ended when I typed apt-get upgrade which filled the internal solid state drive and locked up the PC, nothing would load.

Puppyeee on the EEE PC

I though puppeee linux (EEE spinoff from puppy Linux) was the temporary solution, it was. Wireless worked, keyboard almost worked, it was incredibly responsive and it looked a little rough around the edges. Incidentally, to date it is the only linux distro to make it to the end of its natural life without being broken by me.

Bored of the steep learning curve of puppy and envious of the gnome desktop I installed eeeXubuntu onto my eee. The process was educational but about 5 days longer than the tutorial I was following implied. XFCE window manager is a great gnome substitute and is lightweight enough to be usable with such a small device.

eeeXubuntu on the EEE PC

My dependence on Linux has grown and grown since fixing the EEE and now even my trusty dell is running Ubuntu Hardy Heron.

Monday, 2 June 2008

Run Forrest Run

Spontaneous run #1:
Running in the rain :: The best way to get over an electromagnetism exam (click to view route)

Err, yeah, I got lost OK? - Deal with it! (Isn't that the plough constellation)

Monday, 28 April 2008

Student Robotics Blog

As well as this blog, I have also started a blog dedicated to Student Robotics activities, electronics and ideas. It is at:

Setting up Windows Mobile for SQL CE

My battle against Windows Mobile 5 continues. Set back initially by its limited support for databases, i was forced to adapt my (poorly written) code to use SqlCe which doesn't even fully support the SQL dictionary.

With some - even if limited - database implementation I hoped to move from the VS Emulator to the actual device. Predictable this was not easy. Despite SqlCe .sdf file capabilities and even a program already on the device to open such files - my program refused to run.

Missing libraries. Installing these librarys was more painful than it should have been. Originally i hoped that the compiler and linker would copy all necessary code into the executable file. After all the program ran in the emulator fine. Unable to find an installer for just SqlServerCe which would run on the device itself, i manually hunted out the necessary .CAB files (as spotted in the output pane of VS during deployment) onto the device, learning during the process that they must be installed to 'This Device' and none of the other options for .CAB installation.

These tricks eventually coaxed windows into running my program. Fortunately my luck changed at this point.

I discovered a very useful way of quickly starting the emulator without having to wait for the deployment of all the library files each time. Basically, once it has successfully deployed once, enter the settings>memory>running programs and then stop all processes. Save the state (File>Save State) and close the window. Next time you hit debug it will load much quicker.

Wednesday, 23 April 2008

Database Options For Windows Mobile

In my last post I discussed connecting to MS Access DBs using C# on the full Windows platform. If the target platform is Windows Mobile 5.0, running .NET 2.0, then it is necessary to use a different type of DB. Access DBs are bloated, processor hungry and not available for the Mobile platform. I have found SqlCe to be the best DB option for the Pocket PC since it is lightweight and fully supported by default.

As mentioned in my last post, DataSets are not associated with any particular database or structure until you use them. This means all of the techniques described for OleDb are applicable with SqlCe - just replace OleDb with SqlCe in the code. There are some differences in the connection string which describes the connection but that is the only difference.

To create the initial SQL DB file you will need to use Visual Studio 2005's Data>Add New Data Source and use the Wizard to create a blank .sdf file with password protection.

More Info
Again the MSDN site is very helpful:
  • SQL Syntax and data types for use with SqlCE
  • Windows Mobile can open .sdf DBs and display the contents in tabular form. This can be very helpful when debugging. You could also use it to create the blank DB
  • In SqlCe the 'CE' stands for Compact Edition. This means that not all of the SQL commands are available to use. IF/ELSE/EXISTS for example are not supported
  • Errors in SQL string formatting manifest as 'Token' errors, so if you see references to Tokens, its probably your SQL statement.

The full code for SqlCe
The following code illustrates opening db, creating table, reading table, adding row, and closing connection using the SQL Mobile Server DB. Its very similar to the code in the last post:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
class Program
static void Main(string[] args)
GpsDb myGpsDb = new GpsDb();
class GpsDb
private SqlCeConnection conn = new SqlCeConnection();
private SqlCeDataAdapter adapter = new SqlCeDataAdapter();
private DataSet ds;

public bool Open()
if (conn.State == ConnectionState.Closed)
return true;
catch (SqlCeException ex)
Console.WriteLine("SqlCe Error: {0}", ex.Message);
return false;
return true;

public bool Close()
Console.WriteLine("Connection Closed");
catch (SqlCeException ex)
Console.WriteLine("OleDB Error: {0}", ex.Message);
return false;
return true;
}//end close

public DataTable getTable(string tableName)
Console.WriteLine("File Exists = {0}", File.Exists(@"tax.sdf"));

// create the adapter and fill the DataSet
conn.ConnectionString = "Data Source = '\\Program Files\\ConsoleApplication1\\taxdb.sdf';" +
"Password = 'demeter'; File Mode = 'shared read'; ";

SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE roads (id int IDENTITY (1,1) PRIMARY KEY, road integer, name nvarchar (50), toll integer, x integer, y integer)", conn);
command.CommandType = CommandType.Text;

command = new SqlCeCommand("SELECT * from roads", conn);
adapter.SelectCommand = command;
SqlCeCommandBuilder cb = new SqlCeCommandBuilder(adapter);
ds = new DataSet("roads");
adapter.Fill(ds, "roads");
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
Console.WriteLine("{0} Costs {1} per mile", dr["name"].ToString(), dr["toll"].ToString());

DataRow newRoadsRow = ds.Tables["roads"].NewRow();
newRoadsRow["road"] = 5664;
newRoadsRow["name"] = "St Chris";
newRoadsRow["toll"] = 7;

return dt;
}//end getTable


Tuesday, 22 April 2008

Connecting to an Access Database using C#

This may seem like a common task, and it is, however I found it ridiculously difficult to learn how to do it. The MSDN website has articles on each class involved but nowhere does it explain how to put everything together. After reading this blog you should be able to:
  • Open a connection to an existing MS Access (.mdb) database
  • Perform SELECT queries
  • Extract the results from queries
  • Modify/Add row of a table
  • Update the changes to the Database
  • Close the connection
  • Figure out for yourself how to do other operations
Opening a connection
I will assume that there already exists an MS Access database with at least one table already created. This is fairly easy to do using MS Access and there are plenty of tutorials showing you how to do this. The DB should be in the same folder as the executable file (/bin/debug). To configure a connection to a database:

OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=tax.mdb");
OleDbConnection is a special class which deals with creating a connection or 'handle' to the database. The first part of the string describes the database type, the last part is the name/location of the database file. To actually open a connection use:


You should enclose this in a try/catch statement and test for OleDbExceptions. The connection is now open. To close the connection:


.NET provides support for accessing many different database types. Programmers generally don't want to worry about what particular database they are using, they just want the data. This is where Adapters come in. Adapters (Specific to each database type) present the data structures as a generic 'DataSet' object. Theoretically the database type could be changed without affecting all the code.

OleDbDataAdapter adapter = new OleDbDataAdapter();

The above statement creates a new Adapter object. OleDb is just the name of the adapter specific to Access DBs. The next step is to attach a command to the Adapter for it to execute on the DB.

OleDbCommand command = new OleDbCommand("SELECT * from roads", conn);

This statement creates a command object which will return all the rows from the table 'roads' using the connection we made earlier. Lets attach this command to the Adapter we created:

adapter.SelectCommand = command;
OleDbCommandBuilder cb = new OleDbCommandBuilder(adapter);

Whats actually going on here is a little more complicated. By defining the SelecCommand property of the Adapter, the OleDbCommandBuilder() function will automatically build the SQL statements necessary to update, delete and add to the database. This will come in useful later.

DataSet -> DataTable -> DataRow
As mentioned earlier, C# uses the generic 'DataSet' to store results from DB queries. Therefore we need to create a DataSet object to store the results of our query.

ds = new DataSet("roads");

The "roads" argument is optional and just gives the DataSet a name. Now we must associate our new DataSet with the results from our query:

adapter.Fill(ds, "roads");

The Fill() method will make cause the adapter to execute the SELECT command, get the results and store them in the DataSet 'ds'. 'ds' now contains a local copy of part of our database. The structure of the DataSet is identical to the structure of the DB. We can now access the data easily. DataSets contain Tables, which contain Rows which contain Columns. To access a table:

DataTable dt = ds.Tables[0];

A numerical index or the table name (string) can be used as the array index. We could iterate the rows of a table as follows:

foreach (DataRow dr in dt.Rows)
Console.WriteLine("{0} Costs {1} per mile", dr["name"].ToString(), dr["toll"].ToString());

Notice the hierarchy: DataSet.DataTable.DataRow['columnName']. Using a local DataSet rather than referring to the DB all the time frees up the DB, allowing multiple connections to be made to it.
Adding Rows to the database
As mentioned before DataSets are generic, they have no default structure, no column names, no associated data types. They inherit their structure from the Data Base thanks to the OleDbAdapter. With this in mind, to add a row we therefore need to create a new object 'newRoadsRow' say, which is of the same format as the DB Table where it will end up:

DataRow newRoadsRow = ds.Tables["roads"].NewRow();

We can now enter data into the new row, addressing it as follows:

newRoadsRow["road"] = 5664;
newRoadsRow["name"] = "St Chris";
newRoadsRow["toll"] = 7;

As before, the indexes are the column names as defined in the DB. Now our data is stored, we must add this row to our local DataSet.


Finally our changes must be saved to the database. Again, we need to use our Adapter:


We are now in a position to close the DB connection.

More Info
For more info on these objects/classes visit the MSDN Site:

The above scripts give only a very basic grasp on DBs. There are many more features than I have described here but you should now have the knowledge to research these yourself. The full code is reproduced here, please reference this website if you use it in any projects:

//Simple DB Operations
//Requires existing DB called tax.mdb in /debug/bin folder
using System;
using System.Data;
using System.Data.OleDb;
using System.Xml.Serialization;

public class TaxDB
private OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=tax.mdb");
private OleDbDataAdapter adapter = new OleDbDataAdapter();
private DataSet ds;

private bool open()
// create and open the connection
catch (OleDbException ex)
Console.WriteLine("OleDB Error: {0}", ex.Message);
return false;

return true;
}//end db open

public bool close()
Console.WriteLine("Connection Closed");
catch(OleDbException ex)
Console.WriteLine("OleDB Error: {0}", ex.Message);
return false;
return true;
}//end close

public DataTable getTable(string tableName)
// create the adapter and fill the DataSet
OleDbCommand command = new OleDbCommand("SELECT * from roads", conn);
adapter.SelectCommand = command;
OleDbCommandBuilder cb = new OleDbCommandBuilder(adapter);
ds = new DataSet("roads");
adapter.Fill(ds, "roads");
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
Console.WriteLine("{0} Costs {1} per mile", dr["name"].ToString(), dr["toll"].ToString());

DataRow newRoadsRow = ds.Tables["roads"].NewRow();
newRoadsRow["road"] = 5664;
newRoadsRow["name"] = "St Chris";
newRoadsRow["toll"] = 7;

return dt;
}//end getTable
public class Program
static void Main()
TaxDB myTax = new TaxDB();

Saturday, 29 March 2008

I'm Not Twenty Yet!

Just time for one last post from my teenage years. It wont be long until the early onsets of gout and rheumatoid arthritis. The once 'Adrian Mole' style of this blog will doubtlessly fade away to reveal the bitterness of an Alan Bennett anacedote. The prospect of loosing the 'teen'is nothing short of horrifying and all the chocolate, terry pratchett books and greeting cards in the world would do nothing to soften the impending blow.

Friday, 21 March 2008

I Have An EEE PC

This is as much an opportunity for me to show off my shiny new Asus EEE PC as it is a chance to review it. There are plenty of reviews out there from people who have 'just ordered their eee pc', 'just opened the box', or for whom writing the review was the first thing they did on their new machine. All of these seem slightly premature. Its equivalent to reviewing a film before you have watched the ending!

So, back to the topic. Unlike most people, I was not 'shocked' by the size of it. Unlike most people I can comprehend the dimensions stated on the Asus website (after all that's what dimensions are for). The screen size is 7in. Whilst the resolution is good, the screen is still only 7in. This means that when you open a program for the first time, it is necessary to spend 15 minutes fidgiting around with the toolbars and settings until every unnecessary pixel is removed. By far the worst offender is Open Office. It is annoying that Asus did not think to customise the programs (which they supply by default) so that they were best suited to the product. I am currently in the process of finding an alternative to Open Office which is not only lightweight but which has a simpler user interface.

For me, the program I will (and have) use(d) most is the PDF viewer. CTRL+L is your friend (fullscreen). Viewing lecture notes during lectures and afterwards is effortless and almost as natural as reading the printed notes.

Thunderbird is great to use and probably the best email client for this device. The split pane can be counter-productive on a small screen but once again, messing around with the settings can help enormously.

Firefox is perfect in fullscreen mode and allows you to view javascript and ajaxy websites as easily as you can on a desktop PC. This brings me on to the wireless. Whilst I have found it requires a strong wireless connection before you can reliably connect to a service, once connected, the range is impressive. Without an internet connection the use of the EEE PC is severely limited. Its minimal capacity solid state drive, means that for the most part you'll want to use some kind of versioning software such as Subversion. This means you need only store temporarily a small number of files, whilst at the same time you have access to a much greater stash of files, much more than could ever be stored locally. The second reason is that transferring files backwards and forwards using flash/usb devices is as it always has been: tedious, and prone to mistakes.

Most screenshots you will see of the EEE PC will illustrate the 'Simple' mode, inwhich the traditional desktop and start menu are replaced by a series of tabs with large icons pointing to all the installed programs. There is no denying that this is the simplest way to navigate programs on the EEE but it is not necessarily intuitive to the average Windows or Linux user. Fortunately Asus made it easy to revert back to the core Xandros distribution with the familiar desktop/start menu/taskbar. There is even the ability to boot directly into this mode or switch between the two.

The swanky black case it comes with

Side view of the Asus EEE PC, probably not its best angle (or my best photo).

Probably its best angle.

Front on. If only the side speakers were replaced by MORE SCREEN!

In Proportion. Because everyone knows how big my hand is!

The welcoming home screen.

Nice Weather For Existential Ducks

A term of university and not a single blog post, laziness or just too busy? A mixture of the two if I'm honest. To make up for it, here are a selection of Easter (or secondary gifting period for the non-religious (myself included (nested brackets! proof, if needed that too much programming is bad for one's grammar))) photos.

For those interested to know whats comming up soon on this blog...
  • Infra red communication link tutorial. Following on from a recent university project, I have learnt a considerable deal about this subject and shall pass on as much as I can remember.

  • USB and AVR programming. I hope to learn how to use firware to directly interface an AVR with a USB port.

  • EEE PC Review. A down-to-earth review of my EEE PC and its impact on my life!

And for those who just want to look at photos:

Backwell Lake (hmm, ok Backwell Duck Pond then)

Some Cute Albino Ducks

Two geese, jealous of the media attention, approach. The Ducks are not startled

At first, on hearing news of the approaching avian flu, Bernard was shocked...

...But his existentialism soon kicked in.

Tuesday, 15 January 2008

LT SPICE - Modelling, Parametrics, Steps and More

For a second year semiconductor project at the University Of Southampton (ECS) I had to investigate the operation of a silicon solar cell manufactured within our institution. As part of my report I wanted to model the electronic properties of the device accurately using a SPICE circuit simulator. My software of choice was LT Spice which is available from Linear Technologies for free. Whilst it is powerful and comprehensive it is much easier to learn to use than its better known cousin - OrCAD / PSPICE. Despite its shallow learning cure I found it difficult to find information on some of the more advanced and interesting features. In this post I will explain how to use some of these features (the ones that I needed for my report, anyway).

Creating IV curves
To view the IV curve of a device/sub-circuit, which is often very interesting and important it is necessary to vary the load resistance and measure the its voltage and current. In LT Spice this can be achieved by changing the load resistance value to a parameter. Parameters can be varied dynamically during the simulation as I will show now:
  • Instead of entering a resistance value for R1, type '{RL}'. RL is the name of the parameter, whilst the '{}' tell LT Spice that you are entering a parameter.
  • Click: EDIT>TEXT
  • Check the 'SPICE Directive box'
  • Type 'STEP param RL 1 1000 1' - increment RL from 1 to 1000, 1Ohm at a time
  • Ensure that the Simulation type selected is 'Operational Point' -.op
  • Run the Simulation
  • Hover mouse over x-axis until it turns into a ruler. Left click and change 'Quantity Plotted' to the voltage node at the top end of resistor (or whichever voltage is of interested)
  • Then add a plot of the current through RL to observe the IV graph
Changing Model Parameters Dynamically - Temperature
LT SPICE has a global parameter for temperature called 'temp'. This is no different from the parameter RL in the previous paragraph, except that it is already defined, (it has to be for components such as diodes and transistors). If you wish to see how temperature affects your circuit, you need first to ensure there are some temperature dependent components in your circuit (else nothing will change).
  • Create another SPICE directive (see above - you can reuse the existing text box if you wish).
  • To set the temperature to a single value, type: 'temp=30' the units are Celsius.
  • To sweep the temperature and observe the effects, type: '.STEP param temp 10 50 1' to raise temp from 10 to 50 Celsius in single degree increments.
To change the way a component behaves with temperature e.g. modelling a thermistor:
  • Replace the components value with a parameter, e.g. replace resistance with {THERM}
  • In a SPICE directive, define the new parameter, e.g. '.param THERM='(temp*0.05)+1000'
  • The parameter can depend upon any other parameter, circuit voltage or current, e.g. THERM has a linear relationship to temperature
Creating bespoke models - Custom diode

Making you own models is as simple as writing a few lines of text and is even easier if you have an understanding of Netlists. For those who don't I will illustrate how to create a simple custom diode model.

  • Add an ideal diode to the circuit (SHORT_CUT=D)
  • Press CTRL and RIGHT-CLICK on the diode
  • Change the box labelled InstName to 'mydiode'. This is the Instance name.
  • Change the 'SpiceModel' box to 'mymodel'. This is the name of the device model.
  • Ensure all the other boxes are empty
  • In a new spice directive text box, we define the model: '.model mymodel D (Is=1.88e-5 N=3.89)'
  • The: '.model' part tells SPICE to expect a model definition.
  • The: 'mymodel' part tells SPICE to link components with a SpiceModel = 'mymodel' to this definition.
  • The: 'D(' part tells SPICE we are defining a diode. L() = Inductor; C() = Capacitor; R() = Resistor etc.
The contents of the brackets are the model's parameters. You do not have to define all of the available parameters, but it is good to check that the default values are appropriate. It is not necessary to use absolute values, parameters can be used too.

More complex models can be built using hierarchical blocks, allowing complex circuits to be viewed as single abstracted component. I will write about this in future posts.

Hopefully you now have enough information to begin creating, editing and designing your own models. Remember to start simple and gradually add extra parameters. Watch out for syntax and try viewing the Netlist file for syntax errors if you have trouble.

Figure One - Example of Parametric Sweep

Figure Two - Example of Temperature Dependence

Figure Three - Example of Custom Diode Model

Sunday, 6 January 2008

Functional Testing of SPICE Simulations

After a second year electronics project, the need to automatically check the function of a large digital circuit arose. The brief was to design an 8-Bit ALU (basic logic, addition and 2's complement functions) with ring oscillator. The circuit then had to be converted to a layout to be manufactured as an integrated chip. The circuit although straightforward to design was difficult to 'route' and the final layout was messy.


Thorough functional testing of our circuit was impossible using just the digital waveform view of PSPICE. To be sure of our layout and circuit designs I created a C program to read the simulation file created by PSPICE and check each clock cycle to ensure correct operation. The final program reads the exported PSPICE output .txt file and checks each line one at a time (actually it only checks one line from each clock, since this is all that's necessary). The program converts the analogue values into 1's or 0's before passing the data into a function to check that the output/input combinations are correct. Although the checking function will vary with every circuit to be tested, I publicise this code as an example of how to make testing large digital circuits easy, well easier.

Simulation files from LTSpice and OrCAD's PSPICE can be used, but the top line of the file (which usually contains the signal names) must be deleted first.

The code can be downloaded from the DocDrop folder 'SPICE Program'. DocDrop can be found at the top of the sidebar on this page.