function in Verilog

About the function keyword in Verilog

In Verilog, a function is similar to a function in a traditional programming language. A function takes zero or more input arguments, and produces a single output. Unlike a task, we use a function to perform a single numerical or binary operation.

Consider the reverse_bits task: since it produces a single output vector, it can be implemented as a function instead of a task:

   function [7:0] reverse_bits_function;
      
      input [7:0] in;
      
      integer     idx;
      begin
        for (idx=0; idx<8; idx=idx+1)
           reverse_bits_function[7-idx] = in[idx];
      end
   endfunction

Notice a couple of key differences compared to tasks:

  1. The function is declared as an 8-bit vector, indicating the bit-width of the return value.
  2. The output is assigned into a vector with the same name as the function.

In addition to those obvious differences, a function differs from a task in that it cannot consume time. No delay operations are permitted. Only blocking assignments (=) are allowed. A function cannot call a task, but can call other functions.

Assigned Tasks

Create reverse_bits_function

   q = reverse_bits_function(a);

Implement, Program and Test

Implement the modified design and verify on the Basys3 board.

Take photos for two cases:

  1. a=8'b0110_0010 and
  2. b=8'b1101_0101

Save the photos in your working directory as case1 and case2 with the appropriate graphics extensions.

Turn in Your Work

Turn in your work using git:

git add test_result.txt *.bit *.rpt case* inc/*.v src/*.v
git commit . -m "Complete."
git push origin main

Lastly, indicate on Canvas that your work is complete.