Wednesday, December 2, 2009


You thought Black Friday and Cyber Monday had good deals...well take a gander at Free Day at SparkFun which takes place on January 7th.

You get one shopping cart with $100 in credit. So you can buy 100 bucks of electronics and all you have to pay for is shipping. They even take rain checks.

Tuesday, November 24, 2009

SSH X11 Forwarding

Here's a nice little trick for SSH users. Did you know that you can forward X11 traffic through an SSH connection? All you got to do is this:

If your SSH'ing to a linux machine from a linux machine just issue the command:

# ssh -X username@ipaddress

If your SSH'ing to a linux machine from a Windows machine you need get the following:
Xming X Server

You might also need to install some fonts found here (I however didn't need to do this):

  • Now just install Xming and the Fonts (if the Fonts are needed) into the default directory.
  • Then launch PuTTY and enter in the username@ipaddress into the "Host Name" field
  • Go to the Connection>SSH>X11 section in PuTTY and check the "Enable X11 forwarding" option
  • Also, if needed, set the "X display location" to localhost:0

Once you connect you will be able to issue commands in the command line as you would normally but also run programs that have a GUI. A really cool feature is that the windows are created in your local OS unlike VNC and RDP where the windows are bound inside the Remote Desktop Application window.

Note: The SSH Deamon running on the server might need to be configured to allow X11 Forwarding. Just do a google search to get this information (it generally just requires you to uncomment a line in a configuration file).


Wednesday, November 18, 2009

Neural Networks: Kohonen SOM Presentation

I just wanted to post a presentation I did in my first semester of Graduate school. This presentation was on a Neural Network algorithm called the Kohonen SOM (Self-Organizing Map). Developed by Mr. Kohonen, the Kohonen self-organizing map is an unsupervised, competative learning neural network. This means that the neural network organizes itself from the inputs it receives. The neurons in the network update themself on a winner-take-all basis; however, many Kohonen SOM systems extend this winner-take-all to a winner & neighbors take-all, where the winner gets a full update and the neighbors get a "weighted" update. Instead of me reiterating a lot that is mentioned in the presentation, take a look for yourself.

View the Presentation

This presentation is also highlighted on eceblogger.

Sunday, November 15, 2009


Looking to start a new project, or get some components to re-fill your supply? I would like to recommend going to SparkFun.

Be warned though...there are a lot of cool things that have a tendency of draining your wallet. I went there with the intention of just grabbing a couple IR sensors and I left with about 20 other things...OUCH!

I will be posting the result of this purchase within the week...hopefully.

Wednesday, October 28, 2009

Update: Xilinx Simulation

With the recent official release of Windows 7, I decided to update my laptop to 64-bit Windows 7 instead of Vista 32-bit. The process was for the most part, completely painless. But by switching to a 64-bit OS an interesting problem (or more correctly, an annoyance) showed up when trying to simulate some HDL code I have been working on.

It turns out that Xilinx ISE does not have much support for 64-bit asside from generating bit files. When trying to simulate in ISE in 64-bit mode you will notice that you are limited to ModelSIM which I am not that familiar with, but I definiately didn't have much luck with it.

If you are looking to simulate some HDL in the 64-bit ISE, your best chances for success is to use the 32-bit ISE instead. Luckilly, Xilinx was nice and installed the 32-bit programs when you installed 64-bit ISE. Just go to your Program Files Xilinx Folder and locate the 32-bit ISE. It will launch with your current project and settings which makes it a little more bareable when switching between the two ISE programs.

Before you can actually start simulating, you will need to go into your Project settings and change your simulator to ISim (ISE Simulator program). To do this just go to:

Project -> Design Properties -> Simulator -> ISim (VHDL/Verilog)

And your done.

Now if you switch to Behavioral Simulation Mode, you can select your corresponding HDL file you wish to simulate and you will see the "Simulate Behavioral Model" Option appear.

Wednesday, October 14, 2009

Image Processing: Dithering Presentation

Here is another presentation I made a couple years ago for my class in Digital Image Processing. I presented on a very interesting concept called dithering. In this presentation, I discussed several methods of dithering (one of the more interesting methods being "error diffusion"). Check it out.

Dithering Presentation

Hopefully in the near future I will actually post my code for this project, so that people with interest in the topic can play around with the code. My matlab code had support for all the popular, well known, dithering algorithm out there, as well as some more interesting concepts such as image fusion via dithering.

Thursday, October 8, 2009

Matlab FFT Frequency Axis Reconstruction

Time and time again, I find myself needing to remember how to accurately reconstruct the frequency axis of an FFT in Matlab. This is one of the ways that I have documented as being a pretty close approximation of the frequency axis. This code will also properly compute the magnitude of each frequency component.

The code below uses the signal below as an example:

Now the Code:

Now the result:

Hope you find this useful.

Monday, October 5, 2009

Eclipse C/C++ IDE File/Folder Restore

Well, I am only human and it was only a matter of time before I slipped and deleted a precious piece of code from my thesis source code folder...I was definitely freaking out because I remembered struggling to get that particular piece of code working the way I needed it.

Luckily Eclipse has a bunch of smart programmers to realize such a case. As you may or may not know, when you delete a file in Eclipse, it does not go into the trash. So if you accidentally delete something in eclipse you might initially think "I am screwed...". Little did I know, I had absolutely nothing to worry about. If you need to restore a deleted file in Eclipse just go to the project's source folder and right click on it and select:

"Restore From Local History..."

You will get a friendly window showing you several restore points for the folder.

Thursday, October 1, 2009

Matlab TightAxis Function

During one of my graduate classes I decided to create a function that makes a window that turns off all the Matlab figure toolbars and makes the axis fill the window AND scales the window to fit the image's native resolution so that no pixilization or aliasing occurs. If the image does not fit in the monitor's native resolution then the function will keep the current window size. When calling the TightAxis function make sure the current axis is the axis you want to modify as I use:

If the axis you are currently interacting with is the one you want to modify just issue the command:

Where FIGURENAME is a string that will be used to label the figure window.
Here is the function:

function TightAxis(title)
%First create an axis if
%the user doesn't have a gca
%and get the handle
%Best Image Fit Algorithm
%Check for over sized images
%IF the native resolution of
%the image fits in the screen resolution
%AND the image does not contain a
%1-pixel dimension
%THEN scale the image to be displayed
%at 1x Resolution
if (imageSize(1)<=monitorRes(3)
&& imageSize(1)>1
&& imageSize(2)<=monitorRes(4)
&& imageSize(1)>1)
zoom on;

Monday, September 28, 2009

Matlab's Find Function

Throughout my entire undergraduate studies at UNH there was a great deal of interaction with MATLAB; however, I was never exposed to one of the nicest functions in MATLAB until grad school. The function I am referring to is:


Find, is a very powerful function that can be used to help you search for certain elements in an array. Lets start off with a practical application of "find". Suppose you have a voltage signal that is stored in two arrays. The first array contains all the sampled voltages (lets call this array vArray) and the second array contains the timing information (lets call this array tArray). Suppose we want to determine where all the zero-crossings are in the signal and then pull the corresponding timing information from it. Just follow this code:

And Here is a plot of the Results

As you can see, I detected every zero crossing point in the signal. Now if this was a real system, I probably wouldn't want to detect the zero crossings with the noise that I have; in which case I would want to apply a low-pass filter of some sort that restricts the detection to the intended signal, but that is out of the scope of this topic.

Now it's your turn to play around with "find".

Matlab Performance Benchmarking

Matlab has a lot of interesting little functions/programs that you will come to discover along the way. One of the interesting functions that matlab has is an evaluation timer. By using the "tic" and "toc" commands, you can get an idea of where your inefficiencies are in your coding. I learned about this feature during a course I took in my graduate studies called Introduction to Neural Networks. Neural Networks are a very process intensive and it is important to be as efficient as possible if you want to have some sort of practical application. In neural networks it is common to see algorithms displayed in two forms: iterative/looping or vector-matrix form. I was playing around with these two forms and was interested in how one method performed over the other so I started search for a way to benchmark my functions; thats when I came across tic-toc. I already knew Matlab was particularly friendly with matrix operations versus looping operations but I wanted to quantify that speculation.


By encapsulating your code between tic and toc Matlab can output a timer that keeps track of how long it took to evaluate that segment of code. Try it out for yourself and you might find some better methodologies for coding in Matlab.

Also, if you are just looking to benchmark your computers performance try:


Tuesday, September 22, 2009

Xilinx Chipscope

Chipscope is an excellent tool for debugging your HDL code. Unlike the simulation tools that attempt to simulate the hardware, Chipscope is code that is physically implemented in your FPGA. This allows you to physically and precisely examine the functionality of your code. Note: This is not available in the WebPack (free version) of ISE.

To use chipscope you will need to first create your chipscope cores:
1. Create a new coregen core
-- If you make a subfolder for the cores (say in a folder called "coregen" in the project directory) make sure to use the command:
--- -sd ./coregen
--- Place this command in the Command Line Options under the Synthesize properties as well as the Implement properties
--- This tells ISE to look in the subfolder called "coregen" for missing cores/modules
2. Now make the "ila" core and the "icon" core inside coregen
3. Add these cores to your project. The files to add will either be .v or .vhd depending on you language preference.
4. Next you will need to instantiate them inside your module/architecture
-- If you are using VHDL, you should just be able to instantiate the icon and ila after the "begin" statement in the architecture design.
-- If you are using Verilog, your safest bet is to instantiate it at the end of the module before the "endmodule" statement
-- Here is an example of instantiation of the icon and ila in verilog:

//Wires used to map the IOs of the ila and icon
//to the current module

//The control mechanism between the icon and ila.
//Just leave this alone
wire [35:0] chipscope_control;

//The data you will be monitoring.
//These bits can be distributed among many
//variables in your design
wire [31:0] chipscope_data;

//An optional trigger. If left unassigned,
//chipscope will by default start acquiring
//instantly and stop once memory has filled.
//I.e. you might want to trigger on a
//pushbutton switch.
wire [7:0] chipscope_trig;
chipscope_ila_v1_02_a ila(
//internal control between ila and icon

//The clock that chipscope will run at

//The data chipscope will monitor

//The event chipscope will trigger on.
chipscope_icon_v1_03_a icon(
//Internal control between ila and icon
.CONTROL0(chipscope_control) );

These instantiations can be found inside the core's .v and .vhd files. You just need to worry about the wire/signals you want to use locally in your module.


Xilinx iMPACT

So you have finished your HDL coding and generated the bit file, but now you need to write that file to your FPGA; your next step is to get familiar with iMPACT.

iMPACT is Xilinx's method of programming their FPGAs through a JTAG interface. Most of the time you will need a JTAG to serial/parallel/usb cable. These are generally expensive (approx. $100-200) but are not necessarily required. Check with your boards documentation on what is needed to program it. Most likely if it doesn't need one of these cables, they will have their own tool that you should use.

Loading up iMPACT

1. When you load up iMPACT it will prompt you create or load a new project
2. If this is your first time you will want to create a new project
3. Many people don't save this project and just create a new one each time it opens. Its up to you how you want to handle this.
4. The next screen relates to detecting the device at hand
5. You should make sure your board is connected to the computer and powered up before going any further.
6. Generally you should select the Boundary-Scan option. This will scan the common interfaces for your board.
7. After the scan has been completed you will see your FPGA part number show up in the program window.
8. The next screen(s) will prompt you for the .bit

Monday, September 14, 2009

HDL Functions

If you need to create a function in HDL you're in luck, cause I had to learn it myself last week. And lucky for me it was very simple.

In my particular case I was using an enumerated signal type and I needed to convert that signal back to a std_logic_vector signal such that I could output that signal for debugging purposes. Below is the code I used to convert two enumerated inputs to a single logic vector signal. Notice that the syntax is very similar to "process" definitions. The only key difference is the "return" declaration after the function declaration. This return declaration only requires the data type. It does not need to know what size the vector is (if it is a vector). This is nice since it potentially allows the user to have variable sized inputs...although I have not tried this myself, so it might not be synthesize-able.

function enum2std_logic(
return std_logic_vector is
variable val: std_logic_vector(3 downto 0);
case arg1 is
when IDLE =>
val(3 downto 1):="000";
when READ1 =>
val(3 downto 1):="001";
when READ2 =>
val(3 downto 1):="010";
when WRITE1 =>
val(3 downto 1):="011";
when WRITE2 =>
val(3 downto 1):="100";
when others =>
val(3 downto 1):="000";
end case;
case arg2 is
when Processing =>
when Waiting =>
end case;
return val;
end function enum2std_logic;

Hope this helps.

HDL Enumerations

If you are like me and have trouble remembering what bits correspond to what setting or action in your code then enumerated types are your best friend.

To create an enumerated type just follow this syntax:
attribute ENUM_ENCODING of STATE_TYPE:type is "000 001 010 011 100";

This creates a data type called STATE_TYPE that contains the enumerations: IDLE, READ1, READ2, WRITE1, WRITE2

These enumerations use the following encoding respectively: 000, 001, 010, 011, 100

All you have to do to create a signal that uses such an enumerated type is specify STATE_TYPE (or whatever you choose to call it) as the data type in your signal declaration.

Hope this helps.

HDL Statemachines

Often times in HDL programming we need to describe what is know as a statemachine. For those unfamiliar with what statemachines are please refer to:

State machines require the use of both combinational logic and registers. The registers are used to hold the state variable information that is required to make the decision in the "next" clock cycle. The combinatorial logic is used to set the criteria for transitioning from one state to the next.

In this article I will show an example of how you might choose to implement a statemachine. This is not necessarily the best or most efficient way to implement one, but it is the way that I found easiest to understand.

If you have been following my HDL articles up to this point you probably noticed that I have only shown an architecture containing a single process. In the case of a statemachine, you must have at least 2 processes defined.
  • One process controls the updating of the state variables
  • One process handles the logic and navigation to the "next" state
Suppose we have a system that requires the use of a statemachine that contains two states, 0 and 1, which are mapped to a signal called "state". Also, suppose a logic variable that is used to navigate from one state to the next is define as "input" which can also take on the value of 0 or 1. Finally, lets suppose the logic that this statemachine follows is:

If state=0
If input=0
stay in state 0
go to state 1
End if;
If input=1
state in state 1
go to state 0
End if;
End if;

To create this system using a statemachine is quite simple. First lets create the state update process:

update_states: process (clk)
if(clk'EVENT and clk='1') then
current_state<=next_state; end if; end process;

The process above uses 3 signals.
  1. clk = This is the clk to the system, and in this case we are operating on the positive edge of the clock; however, you can make it operate on whatever part of the clock signal you wish.
  2. current_state = This is the current state we are in. This is to be used in the combinational logic.
  3. next_state = This is the next state that we will transition to in our statemachine.
You might be wondering, why do we have two state variables when you clearly defined having just one?

First, think of a REAL system that operates on clock edges; lets just say we have 2 casscaded positive edge triggered D-Flip Flops. What happens when you try to grab a value at the output of the first flip flop (which is the input to the second flip flop) and simultaneously try to write a new value at the input to 2nd flip flop?

The problem is, trying to simulateously read and write on a signal (or line) is undeterministic. We must remember that HDL uses concurrency, so we don't know whether the read or the write operation occurred first. Because of this, we must define two signals, one which is used to indicate the current state, that we can use to "read" from, and we define another signal that indicates the next state, that we can "write" to.

Now that we have our update_states process defined we can now work on the logic. In this example our logic is VERY simple.

    state_machine: process (clk)
    if(clk'EVENT and clk='1') then
    if (current_state='0') then
    if (input='0')
    next_state<=next_state; else next_state<='1'; end if; else if (input='1') next_state<=next_state; else next_state<='0'; end if; end if; end if; end process;

    And there you have it...your two processes that make the simple statemachine we defined. Of course, for this to work in an actual design, you will need to define the clk, current_state, next_state, and input signals. Which I am sure you can do if you read my previous tutorials.

    Wednesday, August 26, 2009

    OpenRC Runtime Script: Dual<-->Single Display Switching

    This runtime script should work on any system that uses OpenRC (namely gentoo and sabayon). Instead of me reposting an article that I wrote up on Sabayon's Wiki, I will just link to it.

    Friday, July 17, 2009

    Digital Image Processing

    Are you interested in Digital Image Processing (DIP), but don't know where to start? Well, I have good news there are two routes that just might suite your needs. First is Matlab's Toolbox for Image Processing. The DIP Toolbox is a very powerful set of commands that will make image processing as easy as pie. Not to mention that Mathworks has excellent documentation on all its functions. However this might not be an option for some, since it does cost money if your university doesn't have access to it.

    The other highly regarded option is to get OpenCV. OpenCV is the "Open Computer Vision" library written in C, meaning maximum performance. This library was originally created and developed by Intel Corp. which focused on optimizing the code as much as possible, and I have to say, they did a very good job, however, doing certain tasks that you take for granted in Matlab might not be an easy task for OpenCV and C/C++. If you want to learn more about OpenCV, I suggest using the Yahoo! Group called OpenCV. This group is a very active community of imaging experts and novices that discuss anything OpenCV/imaging related. There is also a very nice book by O'Reilly that serves as an aid in learning OpenCV. Here are some links that I have found useful for OpenCV:

    Thursday, July 16, 2009

    Computer Architectures: Neurocomputing Presentation

    Do you have an interest in neurocomputing architectures, or want to get some basics on neural networks? Check out the presentation I had done in Fall Semester 2008, where I presented on a couple papers that focus on neurocomputing architectures using FPGAs.

    Topic #2 (Part2): Matlab GUI Callbacks

    Last time we discussed the very basics of Matlab GUI. We learned what "handles" are and some of the primary functions that one would use to interact and gain additional functionality from a handle. In this section, I would like to discuss callback functions. Callback functions are a very important element to GUI programming. One of the key mindsets to GUI programming is to understand that they are "event-based" programs. Event based programs are programs that if left untouched do absolutely nothing, the only time when they execute functions is when the user interacts with it.

    As we discussed last time there are some very fundamental functions that we must understand to use a graphical object. One of the is the "get" function. Say we create a window that contains a pushbutton by using the following code:

    pb=uicontrol('Style', 'pushbutton');

    Not much going on in the above statements. If we want to give the pushbutton some task to do, we would want to specify the callback function. To see all the attributes that can be set on the pushbutton, issue the command:


    Which will return something like this:

    BackgroundColor = [0.941176 0.941176 0.941176]
    Callback =
    CData = []
    Enable = on
    Extent = [0 0 4 4]
    FontAngle = normal
    FontName = MS Sans Serif
    FontSize = [8]
    FontUnits = points
    FontWeight = normal
    ForegroundColor = [0 0 0]
    HorizontalAlignment = center
    KeyPressFcn =
    ListboxTop = [1]
    Max = [1]
    Min = [0]
    Position = [20 20 60 20]
    String =
    Style = pushbutton
    SliderStep = [0.01 0.1]
    TooltipString =
    Units = pixels
    Value = [0]

    BeingDeleted = off
    ButtonDownFcn =
    Children = []
    Clipping = on
    CreateFcn =
    DeleteFcn =
    BusyAction = queue
    HandleVisibility = on
    HitTest = on
    Interruptible = on
    Parent = [1]
    Selected = off
    SelectionHighlight = on
    Tag =
    Type = uicontrol
    UIContextMenu = []
    UserData = []
    Visible = on

    As you can see, "Callback" is not set to anything by default. Lets say we want it to compute x=sqrt(2) whenever we push the button. There are two ways we can set the callback.

    Generally, the best way to handle a callback function is to make a function that does what you want the callback to do. In this case we would make and save a function like:

    function rootTwo

    And we would set the callback using:


    To make things even more trackable in your code you could make a single function that contains all the callback functions. For example, if you make a callback function called callbackFcn you could do this:

    function callbackFcn(ID)
    switch ID
    case 1
    disp('ID=1, pb1 pressed...')
    disp('Incorrect Callback ID...')
    disp('Doing nothing.')

    And you would set the Callback with the specific ID you want the function to be passed:


    However, since this is such a simple task, instead of making another file that can make it difficult to navigate through your code, you may want to just emmbed that function into the callback string. This can be done using:


    Note: that if the function you are trying to use contains a string and you want to embed the function inout the callback string, then you need to use a second quotation for every single quote in the statement. For example, if I want to use the statement below in my callback:


    The I would have to use the "set" function like this:


    These second quotation marks act as a sort of "escape character" that prevents the callback function from being misinterpreted.

    I think this is all I will discuss about callback functions for now. But be sure to use the "Product Help" in Matlab (search for uicontrol properties) to get more information.

    But before I conclude this post I want to discuss two properties that are sort of overlooked by the average user. When you get more advanced in GUI design using Matlab, it isn't uncommon to have 100 handles that you need to interact with. Managing these handles can be a nightmare if you done understand some of the options that Matlab has set forth for such occassions. Two of the most useful properties that can be used are "Tag" and "UserData". The "Tag" is generally understood to be a unique name to that uicontrol. Say for instance you have three pushbuttons, it might be logical to give them Tag names: "pb1", "pb2", and "pb3". What this does is it gives the user a means to find a handle that a function does not have stored locally in its memory space. This is where the power of the function "findobj" comes in. Findobj takes in a couple arguments, the first is a property name and the second is the corresponding property value to look for. If I want to find the handle of the pushbutton with the Tag='pb2', I would issue the command:


    The second and more interesting property is the 'UserData' property. Matlab documentation says that this has no inherent function or purpose, so what we can do is exploit this and use it as a sort of heirarchy for graphical objects. Say you have several objects that you would like to operate on in the same exact manner. Instead of individually referencing their unique Tag names you can make a group name using UserData. If I want pb1, pb2, and pb3 to all get set to invisible it might be nice to group them first so that in the future the number of statements I have to code are reduced. Here is a full example of how one could use UserData:

    for i=1:length(handles)

    This is a very primative example but it should get the point across that you can keep using Tags to individually reference a handle and you can use UserData to reference a collection of handles. You can even get fancy with the UserData and have a function that reads the UserData and checks to see if an object belongs to more than one grouping and operate on that object accordingly.

    I think this is enough for now. Eventually, I will post a videoclip that will showcase some GUIs that I made that use the features I have outlined above.

    Tuesday, July 14, 2009

    Topic #1 (Part 5): HDL - User Constraint File

    If everything has been working out for you then you are probably ready to test the HDL code on a real device. But before we can generate the binary file used to program the FPGA we need to tell Xilinx ISE exactly how to connect the I/Os to the FPGA.

    Xilinx ISE generates an optimal solution for the internal wiring; technically you can be a terrible coder yet at the end of the day if the code compiles, then it will work just like any other code designed to do the same task. The reason for this is that ISE detects all unused bits, signals, variables, and removes them from the physical implementation. The one thing that ISE can't determine on its own from the HDL code, is how the module's I/O ports connect to the physical FPGA pins. This is where the UCF file comes in. The UCF, or User Constraint File, is a file that lists the module's port mappings to the physical FPGA pins. The most generic form of a UCF statement is as follows:


    A UCF statement always starts with NET and ends with ";"; comments can be used by using the the hash symbol "#". The PORT_NAME variable should be replaced with one of your module's ports. For instance, the most common port name would be the clock. In our previous posts we have been using a module that was defined as:

    module dff(clk,d,q,qn);  

    This means that we will need exactly 4 NET statements. This will lead us to:

    NET "clk" LOC = "PIN_NAME"; # Clock signal, 24MHz oscillator
    NET "d" LOC = "PIN_NAME"; # Data input signal, a pushbutton
    NET "q" LOC = "PIN_NAME"; # Output signal, an LED
    NET "qn" LOC = "PIN_NAME"; # Inverted output signal, an LED

    So the above preps us for how the module will interact with the FPGA board. I have an FPGA board with a 24MHz oscillator, a pushbutton switch, and a couple LEDs, all of which will interact with this code. The next step would be to specify the location that these ports will be mapped to on the physical FPGA. This is done by using the keyword LOC and replacing PIN_NAME with the pin name that your FPGA uses. To determine what the pin name is, you can either look in your FPGA's documentation or you can look on the board's silkscreen as they most likely label them correctly on the board. Below is a picture of the board I am using (from

    As you can see, the pins, LEDs, and pushbutton are all labeled; it is generally a good idea though to skim through your documentation first as there could be silkscreen errors that would cause you to map a port to the wrong pin. Also, some FPGA boards want additional parameters other than just the NET and LOC. These parameters can be attatched by using the "|" character . One common parameter that you might define is the IOSTANDARD as can be seen below:

    NET "LED"  LOC = "p146" | IOSTANDARD = LVCMOS33 ;

    In the case above, the IOSTANDARD is set to a low-voltage CMOS (3.3Volts). Your board may differ so make sure to consult your board's documentation. The final UCF file for my board using the dff module is:

    # Clock
    NET "clk" LOC = "p181" | IOSTANDARD = LVCMOS33 ;
    # Pushbutton
    NET "d" LOC = "p148" | IOSTANDARD = LVCMOS33 ;
    # LED
    NET "q" LOC = "p146" | IOSTANDARD = LVCMOS33 ;
    # LED
    NET "qn" LOC = "p147" | IOSTANDARD = LVCMOS33 ;

    Now that we have the UCF we can continue with generating the bit file. To do this all you need to do is double click on the "Generate Programming File" inside the Processes window. It will first Synthesize the HDL code and check the syntax, then it will implement the design (check for any physical routing problems and check the UCF) and then generate the bit file.

    Once the bit file has been generated we are ready to launch iMPACT. Stay tuned for more...

    Monday, July 13, 2009


    Want to start learning more about FPGAs? Check out
    This site will cover lots of small projects for FPGAs ranging from the basics to very advanced projects that involve state machines.

    Also check out KNJN which is a website that accompanies FPGA4Fun that sells their FPGA boards. They carry really cheap, small, low-power FPGA boards. My next post on HDL will show case one of their high-end boards.

    Topic #1 (Part 4): HDL - Simulation

    Ok, so say your HDL design did not work out as planned. What can you do? Well, it turns out there are several options. The first and most primitive method is to physically interact with your FPGA and try to determine what the root cause of the bug is. Maybe you decide to slow down the input clock to your system and turn on a few LEDs as indicators of important variables.
    The second and most advanced method is to implement a Chipscope "core" on your FPGA. Chipscope is a program Xilinx offers that allows you to physically analyze HDL code directly on your FPGA. Unfortunately if you want this feature you will have to dish out some cash, as it is licensed. But the really nice thing about it is the fact that it gives you the "actual" results as apposed to the third option below. A "core" is an IP (intellectual property) that you can instantiate into your HDL code to give the FPGA additional functionality. Think of cores as mini-programs for your FPGA.
    The third and last method is to simulate in software. A major plus is that Xilinx and Altera provide these features for free. To simulate, you need to design what is called a "testbench", testbenches are additional snippets of HDL code that stimulate the input signals (i.e. clock signals) such that the actual HDL code that you are trying to test has a clue as to when and how frequent to update signals and registers.

    I will give you a step by step procedure for setting up a testbench in Xilinx ISE using the previous dff (D Flip Flop) HDL code, which I re-posted below for clarity.

    module dff(clk,d,q,qn);
    input clk, d;
    output q, qn;
    reg q=0;
    reg qn=1;
    always @(posedge clk)

    It should be noted that it DOES NOT matter which variant you choose for your HDL code (i.e. Verilog or VHDL). As long as the I/O ports and variables are the same you can simulate the exactly the same way.

    Step 1: Add the testbench module.
    You have the choice to add a VHDL testbench or Verilog testbench. Choose which ever one you are more comfortable with. To do this you:

    • Right click on your module name in the "Sources" window with the "Sources for:" set to "Implementation".
    • Select "New Source".
    • Select either the "Verilog Test Fixture" or the "VHDL Testbench" (I used the Verilog Test Fixture in this example)
    • If you have more than one module in your project you will be prompted for which module to associate this test bench with. Select the appropriate one.
    • Finish up with the rest of the prompts and Xilinx will make a template for you. It will look like:

    module testbench;

    // Inputs
    reg clk;
    reg d;

    // Outputs
    wire q;
    wire qn;

    // Instantiate the Unit Under Test (UUT)
    dff uut (

    initial begin
    // Initialize Inputs
    clk = 0;
    d = 0;

    // Wait 100 ns for global reset to finish

    // Add stimulus here



    Step 2: Add the stimulation code
    By definition all inputs will need some stimulation and all outputs, registers, signals need to be initialized. To do this you will need to do something like this:

    module testbench;
    // Inputs
    reg clk;
    reg d;

    // Outputs
    wire q;
    wire qn;

    // Instantiate the Unit Under Test (UUT)
    dff uut (

    initial begin
    // Initialize Inputs
    clk = 0;
    d = 0;
    // Wait 100 ns for global reset to finish
    // Add stimulus here

    // Input Generation
    #10 d = 1;
    #10 d = 0;
    #10 d = 1;
    #10 d = 0;
    #10 d = 1;
    #100 d = 0;
    #50 d = 1;
    #60 d = 0;

    // Console Output
    $display(" Time Clk pushbutton");
    $monitor("%t %b %b", $realtime, clk, d);

    // Declare a clock period constant.
    parameter clockPeriod = 100;

    // Clock Generation
    initial begin
    forever clk = #(clockPeriod / 2) ~ clk;


    • So the code that was added to the testbench achieves several functions that we need/want.
    • First, we declare a clockPeriod parameter. You don't necessarily need a clock period parameter, it is mainly to help keep things verbose. Most parameters, if they deal with time, are generally measured in nanoseconds. In this case we created a parameter called "clockPeriod" that is given a value of 100. The value is technically unitless at this point in time but when applied to timing constraints it will gain the unit "ns"
    • Next we generate the clock signal. More specifically, we generate the clock edges. First we use "initial begin" to indicate another process that will continually execute each iteration and then follow that with the "forever" keyword. This says that we re-execute the statement after a period of time each iteration. The syntax is a little strange but what this says is:

    During each iteration, after clockPeriod/2 nanoseconds take the clock signal and invert it.

    This is one of the most basic clock generation schemes you can use in a testbench. The "#" is a "WAIT" operator that waits a period of time until executing the next sequential statement.

    • By using the wait operator we can make a more interesting signal for the input signal d (instead of using a periodic signal). By using a sequence of these wait statements followed by d=0; and d=1; statements, we can create any sequence we need to help prove that the code is working as expected.
    • The last thing that we might want to add is some output to the console window that gives you the results in text format. To do this we use console functions by using the console operator "$". There are many functions that you may want to use, in this testbench, I used $timeformat, $display, and $monitor. The $timeformat function allows you to specify the format of the realtime simulation, $display allows you to output text to the console, and $monitor allows you to output simulation variables to the console window.

    Step 3: Simulate
    Now that the test bench has been coded, we can now move on to the actual simulation! To simulate, go to the "Processes" window and select the "Processes" tab if it isn't selected already and double click "Simulate Behavioral Model". If all went according to plan, you will see some output in the console window and a plot of a nice timing diagram as seen below.

    If you see some of your signals crossed out such that you can't observed their transitions, then chances are you have not initialized some registers in your primary HDL code. If a signal depends on another signal that has not been set to an initial value, then the simulation will not be able to determine a starting point. The interesting part about this is that this does not matter to a physical system. Most systems will assume a logic low or high upon power up.

    Hopefully everything went to plan and you have a working simulation of your DFF. There is a lot to the simulation that I did not explain or touch, go ahead and explore what other functionalities the simulator contains.

    Coming up shortly, I will discuss how to create the "ufc" file, generate the "bit" file, and program your FPGA in iMPACT.

    Wednesday, July 8, 2009

    Topic #1 (Part 3): HDL - VHDL

    Well, I suppose I should get back to the first topic concerning HDL. We left off discussing the basic syntax of Verilog. Now I would like to create the same dff module in VHDL so that we can compare the two. Below is the module, or as it is called in VHDL, the architecture:

    library IEEE;
    use IEEE.STD_LOGIC_1164.ALL;
    entity dff is
    Port (     clk, d: in  std_logic;
                q, qn: out std_logic);
    end dff;
    architecture Behavioral of dff is
        if clk'EVENT and clk='1' then
           q<=d;         qn<=not d;      end if;     end process; end Behavioral;

    The first 4 statements describe typical libraries that Xilinx ISE uses when you create a new VHDL module. Technically in this specific design the first two would only be needed as we are not doing anything with unsigned or arithmetic operations.

    VHDL breaks the code into two sections, an "entity" and an "architecture". The job of the entity is to define the I/O ports and the data types that are to be use in the architecture. At the top level of the design (commonly denoted as the TLE), these ports are supposed to be physically accessible on your FPGA and are associated with some form of user constraint file (Xilinx called this the UCF) that defines the pin/pad mappings to these ports and additional timing and signalling characteristics/constraints. In other words, if I were to define a counter that is 8 bits long then each of those bits could be be assigned to some physical location on the FPGA (this could be a package pin or a physical locations that is within the FPGA fabric). If you want to use a signal but don't want to physically represent it on your FPGA, then keep reading as I will be briefly covering where this is done. All statements that are to be defined in the entity should be described between the "entity is" (where is the module name that you are using) and "end " statement. To define the ports we must describe them inside a function called "Port();". Inside Port(), we define the name of the ports, the type of the ports (i.e. "in", "out", "inout"), and the data type of the ports. VHDL has a fairly large number of data types to choose from in comparison to Verilog, but in reality there really are only two data types you need, std_logic and std_logic_vector. As the names suggest, one is a single logic bit and the other is an array of logic bits. Below are some other data types that are built into VHDL
    • Bit
    • Bit_vector
    • Boolean
    • Integer
    • Real
    • Time
    • Character
    • String

    After the entity is defined comes the architecture. The architecture defines the underlying function of the VHDL module (in other words, it defines what the module does). The beginning of the architecture is indicated by the keyword "architecture" followed by a name for the architecture this should be unique, by default Xilinx ISE uses "Behavioral" which indicates that the architecture is following a "Behavioral Model". Another common name for an architecture is "Structural" which indicates that a "Structual Model" is being used. This name purely serves to improve readability and understanding of the design as a whole; you could name it whatever you want, but it is recommended that it is an informative name. Note, if you have a design/project with multiple VHDL architectures, you will need to be aware of the name used for each and make sure that each architecture is unique. 

    After the architecture name is the keyword "of" which followed by the name of some entity; by having this option is allows you to use a single entity to define multiple architectures. So say you have a D Flip Flip, and a T Flip Flip, they both have the same ports but the inner function differs, this allows you to reuse the entity and keeps the code MUCH MUCH cleaner. This reuse of entities and the fact that all the ports are fully defined in a centralized location is one of the key elements that make VHDL nice, especially when it comes time to debug/troubleshoot.

    After declaring what entity the architecture is to use, we use the keyword "is". After the "is" you have an option, you can define additional signals to be used that are internal to the architecture or if you have everything you need you can issue the keyword "begin". In this case we don't need any additional signals so we go right into the architecture description.

    In VHDL, you define a "process" that indicates that some sort of process is to be executed on an event general caused by a state change of a signal (such as a clock edge). In this case we use "process(clk)" that says that code will be executed during each clock edge. The contents within the parenthesis is generally refered to as the sensitivity list. Multiple signals/nets can be places in the sensitivity list which basically means if any of the nets within the list change then the process fires off; this allows a designer to describe both synchronous and asynchronous systems/processes. Again each process that is defined should be followed by the "begin" keyword. In this design we want to update the D Flip Flop during each positive edge. In Verilog, this was accomplished by "always @(posedge clk)", in VHDL we use the if statement below:

    if clk'EVENT and clk='1' then

    This statement says that whenever the clk changes (which is indicated by clk'EVENT ) AND clk is logic high (which is indicated by clk='1') then we update q and qn. Likewise, if we want to update only on negative clk edges we would just change clk='1' to clk='0'. After the q and qn update we just need to end our "if", "process" and "Behavioral" architecture.

    Well there you have it, hopefully you got something out of this VERY VERY brief tutorial of Verilog and VHDL. Which one you choose is a matter of preference; sometimes the module is easier to code in Verilog other times it is easier to code in VHDL. VHDL is generally seen to be much more powerful, but it is also very strict in when and where you declare/instantiate signals or other modules.

    Coming up next time, I will discuss how to create the bit file to physically program a Xilinx FPGA, how to physical map I/O ports to FPGA pins using a "ucf" file, and how to simulate your design using a testbench.

    Monday, July 6, 2009


    For those that haven't heard yet. Check out:

    This is a "search engine" of sorts. However, instead of searching for youtube videos, company info, or the latest tech, this engine is purely computational. Wolfram|Alpha was made by the same genius that designed "Mathematica", a popular and powerful math tool to solve all sorts of math related problems.

    Currently, I don't fully understand its capabilities, but I do recognize it as a very useful tool. Here are some examples:

    • Say you search for "Jonathan", my first name. It will return a very nice statistical overview of that name, informing you of its decline in popularity in US births in 1990 and an estimated age distribution.
    • Say you search for "Durham, NH". It will return information about Durham such as population, current local time, longitude and latitude, current weather conditions, and distance to popular larger cities.
    • Say you search for "sin(x)/x". It will return all sorts of information about the expression. First giving you some nice plots of the function, the derivative, the integral, the series expansion, and alternative representations of the expression.
    • Say you search for "FT(sin(x)/x)". It will return the Fourier Transform of the Sinc function, which is a square pulse.

    Its your turn to experiment, give it a try.

    Setup a C/C++ Environment in Windows

    Unix operating systems have been around for a long time, and one great feature they have had for years, was the ease of setting up a programming environment. However, Windows has pretty much caught up with the recent addition of Eclipse C/C++ IDE. All it takes now is the installation of 2 or 3 programs.

    How to setup a C/C++ programming environment in Windows

    First download and install the latest version of MinGW

    I suggest taking the easy route and download the "Automated MinGW Installer" it is just a .exe that does everything for you. This link should bring you to the correct place, you just need to search in the long list of downloads for "Automated MinGW Installer" and get the latest version (i.e. MinGW-5.1.4.exe).

    By installing this package you will now have the essential compiling commands that most Unix developers/programmers know and love (i.e. gcc and g++). MinGW will also provide their implementation of "make" called mingw32-make.exe. Also MinGW will provide you with essential library/header files and others that you probably have never heard of.

    The Second and last step to setting up your environment is to download and install Eclipse C/C++ IDE and/or MSYS.

    MSYS can be found in the same link above. Look for "MSYS Base System" and download the most recent version (there should be an exe that you can download). After specifying the install location and finishing the primary installation, the installer will bring up a cmd prompt window and will ask you some questions. It will want to know if you have MinGW installed and what path it was installed at (by default it should be in c:/MinGW, but just double check that is where the folder resides). The installer will update some path variables and will link the evironment to your MinGW install. After it has finished you will have a perfectly healthy MSYS install that works just like a basic unix environment.

    Some notes about MSYS unix environment. You will notice that if you issue the command "pwd" after launch the program, it will output /home/, where is your username in windows. The root path "/" is really a folder in the MSYS install directory. For example if my user is "Administrator", pwd would output /home/Administrator which in the windows environment means C:\msys\1.0\home\Administrator. As a result you cannot access your windows filesystem by ordinary means. If you want to access code that is somewhere else on your windows partition you will need to place it in this folder.

    Another note, all commands in MSYS will show up as .exe files however you can omit the .exe file extention in the command and MSYS will automatically translate it.

    If you prefer a more graphic programming environment you can install Eclipse IDE. Just head over to:

    And download an install the "Eclipse IDE for C/C++ Developers". There isn't really an installation to this program, just run the .jar in the folder and start your project. If everything was installed properly Eclipse should automatically select MinGW in your project options, giving your complete C/C++ programming environment.


    Friday, July 3, 2009

    Topic #2 (Part1): Matlab GUI

    Taking a little detour from HDL, I would like to discuss the second topic, which concerns the engineering programming/scripting language called Matlab. Practically all electrical/computer engineers have encountered Matlab at some point of their studies. For those less familiar with it, Matlab is a Matrix laboratory that serves as an excellent tool for visualization of engineering problems. Having a strong background can be a huge benefit when it comes to applying for a job concerning research/developement in an electrical/computer engineering field. In this topic, I would like to discuss the methods of creating a GUI without the aid of Matlab's GUI creator GUIDE.

    The most fundamental component to creating a GUI in Matlab is the "handle". It is critcal to GUI creation that you fully understand what a handle is, so I will take this very slow. As the name suggests, a handle is a component of an object that you "can grab onto", basically meaning it serves as a unique identifier in the environment that you can call, set, and get different properties. Each time a handle is created Matlab generates a new value that is not in use. In the simplest case you might create a figure by issuing the command:


    By dowing this, Matlab creates a handle value of 1 that is used to control the newly created figure window. If two other windows are created after this, where the handle value is not set, matlab will auto-increment to the next unused value. Thus, issueing the command figure twice after figure(1) would yeild two new figure windows one which has a value of 2 and the other a value of 3. If however, before calling that third figure window I were to close/delete the first figure (which has a handle value of 1), that third figure command would recreate the handle value of 1 instead of continuing with the incrementing scheme. Note: these integer handle values are generally reserved for figure windows, other object will generally use floating point but you can manually assign a handle of either integer or double depending on your needs/preference. Whenever an object is being created, such as a figure, an axes, a uicontrol, etc the programmer can choose to store the handle value into a variable to easily reference that object at a later time. For instance:


    The commands above would create a figure of some handle value that gets stored into the variable 'a' and an axes figure inside that figure with a handle value storing in b. This makes referenceing each individual object much more simple than finding parent/daughter objects.

    Now that we have a good idea of how handles can be used lets introduce some of the most usefull commands that can be used with these handle values.

    The "get" command: used to grab all object properties from a handle, or a specific property value.

    The "set" command: used to set a property value of a handle.

    The "findobj" command: used to find all handles that have a property set to a specific value.

    The "uicontrol" command: used to create I/O objects such as radio buttons, pushbuttons, textboxes, etc.

    Use the "help" command to learn more about these functions. This is all for now. Next time, I will discuss callback functions and how to create an event based GUI.

    Wednesday, July 1, 2009

    Topic #1 (Part 2): HDL - Verilog

    When someone is introduced to HDL the common question of "which variant should I choose?" comes up. Verilog and VHDL have a lot of similarities and differences, these differences may make this question simple to answer. Verilog is a variant of HDL that was designed to cater towards people with a background in C, the syntax and keywords are very familiar with only slight differences. If a person was tasked with creating a D register (flip flop) in Verilog, this would be the corresponding code:

    module dff(clk,d,q,qn);
    input clk, d;
    output q, qn;

    reg q=0;
    reg qn=1;

    always @(posedge clk)
    q<=d; qn<=~d; end endmodule
    The resulting simulation:

    When analyzing this code line by line we first see the "module" statement. A module is similar to a function in C where once the function has been properly defined it can later be using in other projects to perform a specific task. After the name of the module (dff was used as the name since this is a D flip flop module) we list the inputs and outputs. These I/Os can be listed in any order. Notice also that statements, just like in C, are terminated with semicolons.

    The following two statements, define whether each port is an input port, an output port, or an inout port ("inout" is rarely used).

    The next two statements define q and qn (the data output and the inverted data output port) as registers. There are two primary variable types that can be used, reg and wire. A variable of type register, can be updated at specific events. A register can also be defined as an array of values. For instance:

    reg [7:0] counter;

    This statement would define a register called counter with an 8-bit depth thus giving it 256 unique values. Uses of arrays will be discussed later. A "wire" by definition can only be a single bit as it attempts to replicate the function of a physical wire (meaning at any point in time a wire can only contain one physical value). Unlike the reg the wire does not make use of the assignment operator "<=", a wire uses the keyword "assign" and the "=" operator. The difference between these two are very important when considering timing. HDL has two methods of statement execution: sequential and concurrency. Sequential statements just as the name describes executes statement sequential in the order they appear in the code. Although you can write a lot of code sequentially, it is actually not synthesize-able. Concurrent statements are statements that occur at the end of a clock cycle. The interesting and painful part of concurrency is that you don't necessarily know which register was updated first. Because of this, it is impossible to physically realize a module that updates a register more than once at any point in time. This may sound obvious to most, but from the standpoint of someone with C programming, where sequential statements are the only option. Looking back at the snippet of code, the next statement shows one possible way to control when a register is updated. The "always" keyword says to always perform the following statement(s) "at" (denoted as @) some event.
    The "begin" and "end" keywords are Verilog's way to encapsulate multiple statements that are to follow the event rule.

    Well, this is it for now. I will give an identical example using VHDL

    Tuesday, June 30, 2009

    Topic #1 (Part 1): HDL - Intro

    I have been recently learning about FPGAs (Field Programmable Gate Arrays) and HDL. Since I was an EE major at UNH, I didn't have the opportunity to add an HDL course into my tightly packed undergraduate studies. The concept of the FPGA has always intrigued me and I saw a lot of promise with applying my interests in DIP (digital image processing) and Neural Networks to an FPGA.

    For those unfamiliar with FPGAs, the name refers to the fact that these chips contain an array of gates that can act as logic or memory and they are programmable out in the field (as opposed to only being configured at the manufacturing site). FPGAs use hardware description languages (HDL) such as VHDL and Verilog to define the physical routing in the chip. So instead of designing a circuit that is static and has a specific range of applications, an FPGA can be totally reconfigured/programmed to do virtually anything that is physically realizable.

    Anyways, this has been an on going project for myself that I started last summer. I have learned a considerable amount but there is still A LOT more to learn. Stay tuned for more on this. I will be providing some information on both VHDL and Verilog; hopefully, I will have adaquate information to give a brief comparison between the two languages. Also, in the furture I will be discussing one of my larger projects that I have been working on in HDL.

    Here are some wiki links to get you up to speed on this topic:

    And it begins...

    Well I have finally decided to start a blog due to some request by my friends wanting me to share my knowledge. My goal for this blogger will be to provide tech savvy people or people that are just interested in technology with what is going on with me and some of my projects, as well as a helpful reminder to myself how to do certain things (i.e. special Matlab commands that have proven useful). I am usually very active with technology and constantly exploring areas. I hope this will be very informative and technical enough to provide insight to new electrical engineers but verbose enough to give an every day geek enough information to get started on his/her project.