Saturday, 31 March 2012

You know your circuit analysis has gone wrong ...

...when you're equations look like this:

Original Link:

Saturday, 24 March 2012

Automating VHDL Testbench Creation

I do quite a bit of VHDL development in my job. Most VHDL blocks (entities) that I write are quite short. In my opinion, this is a good thing. It means that you can hold all of the variables in your head at the same time and actually feel confident that you understand how it all works. Smaller blocks are usually easier to reuse. They are also much simpler to test. Having many smaller blocks versus one large block does however mean writing more test benches.  Compounding this additional effort is the fact that VHDL is a very verbose language. My usual approach is to modify a template file which I keep to hand, however this can still take almost as much time and effort as writing the design under test (DUT)!

My goal is to find a better way of writing test benches, so that I can spend more time doing the fun bit, designing the functional design unit! I want to reduce the barrier to setting up a test bench. Ultimately I want to be confident that my design will work before spending time synthesising and testing the design on hardware.

I have found a variety of approaches to automating test bench generation. They seem to fall into the following broad categories:

Test vector based verification

This is the sledgehammer approach. You describe the state of all the input signals for each clock cycle/step of you simulation and then step through each line applying the signals. If you add in assertion statements you can catch errors during simulation. The input test vectors could be a spreadsheet, or generated by hand or by another piece of software. I don't like this approach because it is time consuming, error prone and very hard to read and modify. I can image certain situations where this really may be the best technique, perhaps if you wanted to verify an arithmetic function or a complex checksum calculator.

Transaction based verification

A transaction based simulation relies on using many of the non-synthesisable, sequential features of VHDL to call specific test procedures when certain signal events occur. By using VHDL procedures or components you can write reusable test constructs such as reacting to a read request signal, or the start of a bus transaction. Typically you create a master process which sequences calling each of the processes in turn. You can read more about this in [1] (see sources at end of post). I want to find out more about this style of VHDL and experiment with it to see if it really can expedite the process of writing test benches.

My main concern with this approach is that it requires a completely different style of HDL compared to that which you write when designing the DUT. This makes it quite difficult to switch between writing synthesisable code and writing the testbench. I'm also sceptical because it makes it too easy to forget about how the actual hardware will behave! If your testbench is purely sequential you may end up excluding the consequncies of concurrent events. You may also end up writing asynchronous code which doesn't accurately model the hardware the design under test will be interacting with.

Method 3

This is approach that I take at the moment. I'm not really sure if it has a name. It is simplistic, synchronous and (almost) looks like real, synthesisable VHDL. I typically define a clock and reset as follows:

clk0: process
    Clk <= '0';
    wait for 6 NS;
    Clk <= '1';
    wait for 6 NS;
end process clk0;

rst0: process
    Reset <= '1';
    wait for 12 NS;
    Reset <= '0';
end process rst0;

I then set about writing a VHDL module which mimics the behaviour of the hardware which the DUT will interact with. I usually combine this with a counter which I use to synchronise stimulus to the DUT and to get things kick started. The synchronous counter ensures all events happen on active clock edges, as they will in the final design. It also means its easy to add new events to build up the simulation.

Typically I start with a test bench counter:

    -- Generate a test bench counter which we can use to
    -- synchronise events
    process(Clk, Reset)
        if(Reset = '1') then
            TbCounter   <= to_unsigned(0,8);
        elsif(Clk'event and Clk='1') then
            TbCounter <= TbCounter + to_unsigned(1,8);
        end if;
    end process;

I then generate DUT input signals from the count value:

    -- Example write strobe
    Write <= '1' when TbCounter = to_unsigned(5,8) else '0';

    -- Example address counter
    Address <= std_logic_vector(TbCounter(7 downto 4));

Sometimes it is helpful to capture the outputs of the DUT as they would be by subsequent hardware blocks in the final design. For example capturing a register write:

    -- Implement a storage register to capture the output from the DUT
    process(Clk, Reset)
        if(Reset = '1') then
            TbRegData   <= X"00000000";
        elsif(Clk'event and Clk='1') then
            if(Write = '1') then
                TbRegData   <= Data;
            end if;
        end if;
    end process;

With these simple building blocks you can set up simulations which exercise the DUT in realistic ways and which make analysis of simulation waveforms straight forward.

Room for improvement

As I mentioned before, writing test benches is time consuming. It is also fairly repetitive. A lot of the information in the DUT has to be replicated in the test bench, such as defining all the i/o signals, wiring up the port map and generating a clock, reset and test bench counter. I have therefore set about automating these initial stages of test bench generation. My end goal is to be able to embed test bench directives in the comments of the DUT port definitions and then run a script to automatically produce a test bench file which is immediately ready for simulation. This can then be used as a starting point for testing the DUT. In many cases, it would probably be all that is required. This is what I have in mind:

entity DUT is
    Clk    : IN std_logic; -- @clk,6250,6250  
    ClkEn  : IN std_logic; -- @clkpulse,1,4,Clk  
    Reset  : IN std_logic; -- @pulse,10000,1,0
    DUTA   : INOUT std_logic_vector(7 downto 0);   -- @static,255
    DUTB   : INOUT std_logic_vector(7 downto 0);   -- @static,0
    DUTOUT : OUT std_logic;                        -- output only
end entity DUT;

This would create:
Clk - a clock with the specified high and low times in ps.
ClkEn - a synchronous pulse lasting 1 'Clk' period in every 4
Reset - an asynchronous pulse lasting 10000ps, starting at '1' then transitioning to '0'
DUTA - a statically assigned value of 255 b"11111111"
DUTB - a statically assigned value of 0 b"0000000"

I currently have a script, written in Perl, which performs the following stages:
  1. Creates the entity and architecture statments
  2. Defines all the signals necessary to interface with the DUT
  3. Instantiates the DUT entity and sensibly wires up the port map
I'm working on the next stage: interpreting the '@' directives in the comments and generating the VHDL code required to achieve them. I'm looking forward to publishing it when its more...err...complete?! But for now you can download and run the script on any VHDL file and generate your own test benches. I have tested it on Windows and Linux.

The code is here:

Please let me know what you think. If you have your own ways of creating test benches I'd look forward to reading them!

[1] Manual and Automatic VHDL/Verilog Test Bench Coding Techniques

Sunday, 18 March 2012


It is week three of the Massachusetts1 Institute of Technology's inaugural on-line course 6.002x Circuits and Electronics. I'm really impressed!
"6.002x (Circuits and Electronics) is designed to serve as a first course in an undergraduate electrical engineering (EE), or electrical engineering and computer science (EECS) curriculum. At MIT, 6.002 is in the core of department subjects required for all undergraduates in EECS." [source]
The course has so far lived up to the high standards expected of an MIT course. I think what distinguishes this course from those at other universities, including Southampton University's excellent ECS School is the effort they have put into making the on-line learning environment (eurgh) as good as possible. The site has been designed from scratch to suit the needs of an electronics course. This includes:
  • On-line access to relevant sections of course textbooks
  • Lectures split into 10 minute videos, all available from youtube
  • Transcripts of all lectures which can be synchronized with the youtube videos
  • Online tutorials with youtube videos showing, and importantly, explaining the worked solutions
  • Proper homework questions with numerical answers which can be checked and graded instantly
  • Virtual electronics labs. They have invested in a browser based circuit simulator which means you can submit circuit diagrams as solutions to questions
I'm really hopeful that MIT will continue to roll out this type of course to cover other electronics, computer science and perhaps even mathematics modules. Furthermore I hope that other universities in England as well as America take note and step up the quality of their on-line course resources. Simple steps as providing relevant sections of the course texts on-line (using something akin to Google scholar to keep the publishers happy) make a big difference. Breaking long lectures into smaller 'chapters' and posting the videos on-line is really useful. You can skip the bits you already understand and rewind to the point where everything stopped making sense.

Although the course has already started you can still enroll here

I have read sections from the course text: Foundations of Analog and Digital Electronic Circuits (The Morgan Kaufmann Series in Computer Architecture and Design). I really like what I have read so far. As first year electronics text books go I think this is the best I've seen. It has a lot of worked examples. Something which is often missing from course texts.

1How many attempts did it take to spell this correctly? Answer: I don't know 'cos I gave up and copied it from the website.

Sunday, 11 March 2012

British Class

The subject of social class has recently piqued my interest. I don't know why it interests me. I wouldn't (although others might?!) describe myself as being class conscious. I certainly don't have well formed opinions on the subject. I can't make up my mind whether it is good or bad, necessary or out-dated or something we should aspire to eradicate altogether.

I started reading an excellent book by the anthropologist Kate Fox titled Watching the English: The Hidden Rules of English Behaviour. In this book she attempts to define a set of rules which underpin the everyday behaviour of the English. What makes this book so good is that instead of just recycling age-old stereotypes and clich├ęs she has undertaken her own social experiments to really test her hypothesis. This includes what must have totalled weeks of observations in various locations and environments ranging from pubs to railway stations. Beyond mere observations some of her experiments included deliberately bumping into people in the street, jumping queues and interrogating confused tourists, baffled by the nuances of English social habits.

Back to class.

Running throughout this book is the omnipresent subject of class. In almost every social situation we seem to have invented ways of classifying people. Kate Fox goes to great lengths to explain the sometimes bizarre and hypocritical indicators of class and status which we are all somehow aware of yet are bound from explicitly indicating or referencing. Kate Fox is obviously not the first person to write about this. Class and the class system is something that writers, reformists, politicians and historians have observed, opposed, debated and interpreted forever. It is this very fact which has got me thinking. Is there really anything British about Class?

To my girlfriends annoyance I've been pondering this recently and something she said really struck me. She is Canadian and she said something along the lines of:
"Of course you get upper/middle/lower classes in Canada but its not like in Britain where its such a big deal"
There clearly is something different about Class or the way it is perceived in Britain compared to North America or Europe and perhaps the rest of the world but what it is? Every society has people at both extremes of the social scale some kind of distribution in between. The nomenclature of upper, lower & middle as class labels translate readily into other cultures so whatever the difference is, it must be more than just the labels we use.

I can see one difference. The wealth of indicators we have in our repertoire for classification and for describing class is vast. One thing which is certain and which Kate Fox points out many times is that class is determined by more than wealth. It is clearly influenced by your parents and personal aspirations. The method of identifying peoples class must therefore be more complicated and detailed. As we've become more cultured, accumulated more material wealth and removed barriers to class entry through schooling and reform it has become harder to identify someone's class. This is not a bad thing. But just having lots of ways of determining someone's class doesn't explain why we as British people care more than anyone else about it (if in fact we do?). Instead it is just another symptom of its importance in society.

It is my suspicion that class matters as much to the rest of the world as it does to the English. Having only ever lived in England I'm not in a position to test this hypothesis! One stumbling point is that the term class is ambiguous, subjective, ill-defined and often read as class prejudice. The definition you use to describe class is itself influenced by your own class! This whole subject is a quagmire!

In this blog and in my head I define class in the mathematical sense as a collection of people with similar properties. This allows for people to have properties which qualify them as members of more than one class.

Melvyn Bragg, broadcaster, social/scientific historian and author has recently presented an excellent three-part documentary series looking at class and culture in Britain over the last 100 years. You can currently watch all three parts on iplayer (geographical restrictions apply):