Running a simulated FPGA Sep 14, 2016

Who needs real hardware?

One of the very nice things you can do with Verilog (and VHDL), is to use it as basis for a simulator. Especially with synchronous designs, which do all their work in lock-step with a central clock, simulators can provide a good insight into what’s going on without having to load the design onto real silicon.

Verilator is a great tool for this, and does something really clever: the Verilog code is first translated into C++, which you then include in a small main loop of your own, compile, and run - preferably on a modern laptop or desktop machine. Such an RTL simulation runs surprisingly fast.

I’ve set up a minimal demo on GitHub to try this out and get started really quickly.

Here is the Verilog code I’ll be trying out:

module top (
    input clk,
    output out
);

// a little 0-to-7 counter
reg [3:0] counter;
always @(posedge clk)
    counter <= counter + 1;
wire in = counter[3];

// mystery circuit...
reg inPrev;
always @(posedge clk)
    inPrev <= in;
assign out = ~in & inPrev;

endmodule

We need a few lines of C++ boilerplate code to “drive” the simulation (and stop at some point!), see the main.cpp file on GitHub.

Here is the Makefile I’m using:

CFLAGS = -Wno-undefined-bool-conversion

all:
    verilator -cc top.v --trace --exe ../main.cpp -CFLAGS "$(CFLAGS)"
    make -C obj_dir -f Vtop.mk

clean:
    rm -rf obj_dir data.vcd

Once compiled and run, we can use the open-source GTKwave application to look at the results as a nice timing diagram.

BTW, I used “brew install verilator gtkwave” on my Mac laptop to get these nice tools. It sure is great to have such an effortless package installer, nowadays!

After typing in “gtkwave data.vcd”, GTKwave opens up in a window. If you now expand the “top” tree and then append all signals to the viewing window, you get this:

Note how all signals defined in Verilog can be inspected. It’s like having an oscilloscope which lets us peek inside the entire circuit.

GTKwave can also export the result to a PDF, which comes out looking like this:

Aha! This circuit is a falling-edge detector!

This is a multiplexed 7-segment LED display, showing “1234” - from this demo:

As you can imagine, simulation is extremely useful to check whether a circuit description is actually doing what you want. The only change to the original Verilog code, is that the clock was “speeded up” by using bits [4:3] instead of [19:18] (twice) from the counter, so that the simulation wouldn’t waste its cycles just to count down time.

For a considerably more advanced example, check out this SDRAM controller, copied from the very nice fpga4fun.com website:

(see this PDF for a detailed view)

It’s not a full-blown implementation, but still a great example of how to design and debug a circuit before building hardware.

Weblog © Jean-Claude Wippler. Generated by Hugo.