TransWikia.com

Full Adder in Verilog

Code Review Asked on November 8, 2021

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

One Answer

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);

Answered by toolic on November 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP