Microprocessor virtualisation

On one of my web-wanderings I discovered a piece of software called VMLAB. It allows you to build a virtual prototype of a microprocessor circuit, without any actual hardware! Very cool.  Even better - it's freeware.  This had to be downloaded and tried out :-)

Since I have recently been messing about with HD44780 compatible LCD displays, I couldn't resist trying that.  So here is an example I knocked up:

Virtual LCD and microprocessor in VMLAB

Not bad ... an ATmega168 driving an HD44780 compatible LCD all done virtually, without all that mucking about with actual hardware.  I did try sending some user defined characters to the virtual LCD, but that didn't seem to work, maybe that was pushing it.

Simplest ATmega168 program

So how would you know that your code is running?  Just about the simplest thing that you can do with a microprocessor is flash an LED on and off.  So we'll start with that.  You'll need to attach an LED and a resistor in series from pin 28 of the ATmega168 (assuming that you have the DIP format).  So take a wire from pin 28 on the ATmega and attach it to the positive pin of an LED.  Then attach the negative pin of the LED to one  wire of the resistor.  Finally, attach the other wire on the resistor to Ground.  When the program code turns on pin 28, power will flow through the LED through the resistor and then to Ground.  So the LED will come on.  Cool.

Obviously LEDs are diodes, so they only go one way round (the resistor can go any way round).  The purpose of the resistor is to limit the current and prevent the LED from burning out.  The exact resistor value does not matter in this case, anything from 200 to 1,000 (1k) Ohms should be fine.  The lower the value of the resistor the brighter the LED will be.

Don't forget to also wire up the other basic pins on the Atmega (I've blogged about that before).  Now we can get to some code.  I've put the source code here: http://www.codehosting.net/blog/files/led_blink.zip

Extract the contents of the zip file to a folder and open the files using Programmers Notepad from WinAVR.  Connect up your usbtiny programmer, ensure that the power is on and we're ready to go. 

Go to the Tools menu of Programmers Notepad and click on [WinAVR] Program.  The program should compile, get loaded onto the microprocessor and the LED should start to blink!  Woo-hoo.

NOTE: I have also used the "ponyser" serial port programmer.  This can be used as an alternative, by changing these lines of the makefile:

Put a # at the start of line 202 and remove the # from line 201:
AVRDUDE_PROGRAMMER = ponyser
#AVRDUDE_PROGRAMMER = usbtiny

Remove the # at the start of line 206 and make sure that the COM port matches the one you're using:
AVRDUDE_PORT = COM1

Finally remove the # from the start of line 227:
AVRDUDE_FLAGS += -P $(AVRDUDE_PORT)

You should now be able to use a serial port programmer instead (my example uses COM1).

Programming the ATmega168

There are several ways to get your program onto an ATmega168, the way I'm doing it is with one of these programmers and some jumper wires  - essentially I followed the SparkFun tutorial here.  This is something that I'm working on at the moment:

 

But you could also use one of these Olimex development boards, which is another way I have tried (and means that you can dispense with all those jumper wires).

The AVR pocket programmer is good because pretty much any PC has USB these days (you can also use serial or parallel ports to program an ATmega).  But the pocket programmer can also provide a 5v power supply from USB.

If you want to build your own programmer (which would probably be the cheapest option) then take a look that this, which should get you able to build a programmer for the cost of some wire, resistors and a parallel port connector (assuming that you have a PC with a parallel port).  For me, I found it easiest to just buy something from SparkFun.  In my experience the pocket programmer only works when attached to a USB hub, I've never managed to get it to work when plugged directly into the USB port of my PC - I've never bothered to find out why.

Of course, the other thing you'll need is a development tool, so that you can compile your source code and get the resulting output file copied to the processor.  I'm using WinAVR, or more specifically the portable version which is here.  The portable version means that I can put my development environment on a memory stick and use it on whatever computer I happen to be sat in front of.  Very nifty.

So when you're armed with 1) a programmer, and 2) a copy of WinAVR ...you should be ready to go.  You'll need some code to compile!  I'm going to post that next.

Optimising StringBuilder Appending

I have been working on some C# code optimisation, for speed.  The code in question does a lot of work with strings, so we already use StringBuilder to make it more efficient.  But what is the fastest way to append stuff to the StringBuilder?  In this instance, we're building a lot of comma seperated lists, and even with StringBuilder there are several ways, for example:

 

Method 1, AppendFormat:

sb.AppendFormat("{0},",myStr);

 

Method 2, Multiple Append:

sb.Append(myStr);

sb.Append(",");

 

Method 3, Multiple Append (with a comma already in a string):

string sep = ",";

...

sb.Append(myStr);

sb.Append(sep);

 

Method 4, Single Append:

sb.Append(myStr+sep);

 

... so I decided to check it out.  Here are the results (in seconds), after using each technique one hundred million times (I did five tests and then averaged the results):

 

 

#1

#2

#3

#4

#5

Average

1 AppendFormat

17.20

17.56

17.36

17.58

17.55

17.45

2 Multiple Append

6.61

7.27

6.70

7.27

7.28

7.03

3 Multiple Append (comma in string)

6.65

7.20

6.75

7.20

7.20

7.00

4 Single Append

8.13

8.34

8.31

8.34

8.34

8.29

 

I was quite surprised at how much slower AppendFormat was (although I can understand why).  But it's also worth remembering that the lazy coders way of using a single Append with the + operator to attach the comma is quite a bit slower than calling two Append methods (again, you can understand why when you think about it).

 

Here is the code that I used to test:

 

static void Main(string[] args)

{

    DateTime start = DateTime.Now;

    StringBuilder sb = new StringBuilder();

    string myStr = "hi";

 

    for (int t = 0; t < 100000000; t++)

    {

        sb.AppendFormat("{0},",myStr);

        if ((t % 1000)==0) sb.Remove(0, sb.Length - 1); 

    }

    TimeSpan gap = DateTime.Now - start;

    Console.WriteLine("AppendFormat takes: {0}", gap);

    sb.Remove(0, sb.Length - 1);

 

    start = DateTime.Now;

    for (int t = 0; t < 100000000; t++)

    {

        sb.Append(myStr);

        sb.Append(",");

        if ((t % 1000) == 0) sb.Remove(0, sb.Length - 1);

    }

    gap = DateTime.Now - start;

    Console.WriteLine("Multiple Appends takes: {0}", gap);

    sb.Remove(0, sb.Length - 1);

 

    string sep = ",";

    start = DateTime.Now;

    for (int t = 0; t < 100000000; t++)

    {

        sb.Append(myStr);

        sb.Append(sep);

        if ((t % 1000) == 0) sb.Remove(0, sb.Length - 1);

    }

    gap = DateTime.Now - start;

    Console.WriteLine("Multiple Appends (comma in string) takes: {0}", gap);

    sb.Remove(0, sb.Length - 1);

 

    start = DateTime.Now;

    for (int t = 0; t < 100000000; t++)

    {

        sb.Append(myStr+sep);

        if ((t % 1000) == 0) sb.Remove(0, sb.Length - 1);

    }

    gap = DateTime.Now - start;

    Console.WriteLine("Single Append (comma in string) takes: {0}", gap);

    sb.Remove(0, sb.Length - 1);

 

    Console.ReadKey(); 

}

Sorting a jagged array

This week, I had a need to sort a jagged array of integers, and this is the solution that I came up with:

 

public class IntArraySorter

{

    public static void ExampleSorting()

    {

        int[] a = new int[5] { 1,2,3,4,0 };

        int[] b = new int[4] { 1,2,3,0 };

        int[] c = new int[3] { 1,2,0 };

        int[] d = new int[2] { 1,0 };

        int[] e = new int[1] { 1 };

 

        // sort a 2 dimensional array of integers

        int[][] multi = new int[5][] {a,b,c,d,e};

        Array.Sort(multi, CompareIntArrays);

 

        // we can also use it to sort a List of integer arrays

        List<int[]> list = new List<int[]>();

        list.AddRange(new int[][] {a,b,c,d,e });

        list.Sort(CompareIntArrays);

        int your_breakpoint_here = 0;

    }

 

    public static int CompareIntArrays(int[] x, int[] y)

    {

        int length = x.Length > y.Length ? x.Length : y.Length;

        int diff = 0;

        for (int t = 0; t < length; t++)

        {

            diff = safeGet(x, t) - safeGet(y, t);

            if (diff != 0) return diff;

        }

        return x.Length - y.Length;

    }

    private static int safeGet(int[] arr, int element)

    {

        return (element > arr.Length - 1) ? 0 : arr[element];

    }

}

 

...this technique will work with 2 dimensional arrays of integers if they are jagged or not.  So I thought that it was the type of thing that was worth posting up here for future reference.

Improved Annoyatron Schematic

I have been starting to learn to use Eagle, so that I can document my circuit diagrams.  Being quite new to designing hardware I'm learning that it's not good enough to just keep a copy of the source code anymore!  So, here is the very simple circuit that makes up my improved Annoyatron:

It's very simple to knock this up on a small breadboard, you just need the ATMega168, a speaker and a battery, just like this:

Obviously, the ATmega168 is overspecified, but I have a few of them and it's easier to mess around with one type of processor.  I really will try to post the source code and some notes on how to get the source code onto the processor as a program.  Honest.

New Soldering Iron

I've just bought one of these soldering irons.  I don't know why I didn't do it ages ago!  It's been useful since I've been taking things apart again, for example here is an infrared receiver that I've just removed from an old set-top box:

de-soldered IR receiver

The new iron made a nice job of it, I set the temperature to a reasonably high level and heated the pins at the back of the board whilst tugging the otherside with a pair of pliers.  Each pin came away very easily.  I've only had it for a day, but so far it has been fantastic.  Plus it's great to have an iron without a power cable, it's much less fiddly.

Windows 7 has arrived!

It's here!  Finally, Lenovo have sent my upgrade.  It installed without a hitch and I'm very pleased with my new OS.  They never did answer any of my recent e-mails chasing it up though.

Lenovo the third

OK, so I thought that I was finally making some progress with my "free" Windows 7 upgrade that comes with my new Lenovo PC.  It took a very long time for them to validate my purchase - they check to see that you really have bought a Lenovo PC that qualifies for the free upgrade.  I have no problem with that, but why did it take so long? In the end they validated my purchase 44 days after I registered for the upgrade.

So now they have actually taken my money, yes that’s right there is a £16 "shipping" charge.  Don’t get me started – it does not cost £16 to send out a piece of software.  Anyway, I have paid, they have taken the money off my card.  In fact, they took the money 12 days ago.  Their e-mail confirming the payment said: "A notification email with the shipping details will be sent to you when your order has been shipped".  Guess what?  Nothing.   So they have taken my £16 and not shipped anything.  So I thought that I would drop them a line via their Windows 7 Upgrade website.  So far all I have got is an automated response: "This is to acknowledge the receipt of your enquiry and you will hear from us within 10 business days".  Whoa! Two weeks to answer an e-mail?  What’s interesting is that before they took my money their responses said: "This is to acknowledge the receipt of your enquiry and you will hear from us within 1-3 business days".  Fascinating how they lose interest in you once they have taken your money, eh?

Running the ATmega168

...so like me you've gone and got an ATmega168 from somewhere like http://www.sparkfun.com (which is where I get a lot of my stuff).  It probably cost you about £2.50. Obviously you'd like to get it to do something meaningful, so what do you need to do?  Take a look at this pinout for the processor:

Drop the processor into a breadboard, making sure that it straddles the middle row.  All we need to do is connect pins 1, 7 and 20 to a +5v DC supply and pins 8 and 22 to Ground.  That's all there is to it.  It's useful to note that the purpose of supplying power to pin 1 is to tell the microprocessor that it is not being reset.  Not supplying power to this pin will prevent any code from running, it will remain in reset mode.  We could use this pin like a reset button on a PC by adding a button and a resistor, but we won't worry about that right now.  I'm saying use a 5v supply because it's a nice easy voltage to find (for example, USB will supply 5v with 1A current, which is fine), but the processor should work with a supply between 2.7v and 5.5v (see the datasheet here if you're interested).  I often use a spare PC power supply, because they normally have a 5v output and are not expensive.

 

OK, so the processor may be running - but we've not put any code onto it yet.  So that's the next thing on our todo list.