6
\$\begingroup\$

I'll be teaching Computer Architecture at the undergraduate level this fall and want to make sure that my example Verilog code follows best practices. I welcome any suggestions, however minor, for improving this code, which runs at EDA Playground.

Our textbook is Computer Organization and Design by Hennessy and Patterson. It doesn't say much about Verilog, and I will only be taking a small piece of code from an appendix, so there is no style to be consistent with.

Testbench

module test;
  reg   a;
  reg   b;
  reg   c_in;
  wire  sum;
  wire  c_out;

  ADDER adder(a, b, c_in, sum, c_out);
          
  initial begin
    // Dump waves
    $dumpfile("dump.vcd");
    $dumpvars(1);
    
    for (int i = 0; i < 8; i++) begin
      {a, b, c_in} = i;
      display;
    end
  end
  
  task display;
    #1;
    $display("%b + %b + %b = %b%b", a, b, c_in, c_out, sum);
  endtask
  
endmodule

Design

module ADDER (a, b, c_in, sum, c_out);
  input     a;
  input     b;
  input     c_in;
  output    sum;
  output    c_out;

  assign c_out = (a & b) | (a & c_in) | (b & c_in);
  assign sum = a ^ b ^ c_in;
endmodule
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

In the design module, use ANSI-style port declarations to reduce redundant port lists (refer to IEEE-Std 1800-2017, section 23.2.1 Module header definition):

module ADDER (
  input     a,
  input     b,
  input     c_in,
  output    sum,
  output    c_out
);

In the testbench, use connections-by-name instead of connections-by-order:

ADDER adder (
    .a     (a),
    .b     (b),
    .c_in  (c_in),
    .sum   (sum),
    .c_out (c_out)
);

This involves more typing, but it avoids common connection errors, and it makes the code easier to understand (more self-documenting). Refer to Std section 23.3.2.2 Connecting module instance ports by name.

I usually find it helpful for debugging to also display the time:

$display($time, " %b + %b + %b = %b%b", a, b, c_in, c_out, sum);

I also find it easier to debug if the signal values are displayed when they are stable (away from signal edges). This can be accomplished by adding a small delay after the $display as well as before it:

  task display;
    #1;
    $display($time, " %b + %b + %b = %b%b", a, b, c_in, c_out, sum);
    #1;
  endtask
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.