Home > Enterprise >  How to use case statement instead of for-loop in verilog
How to use case statement instead of for-loop in verilog

Time:10-21

The following is a seven-person voting program described in verilog, but due to the efficiency of the for loop, I would like to change the for loop into a case statement.

module voter7(pass, vote);

output pass;
input[6:0] vote;
reg[2:0] sum;

integer i;
reg pass;

always @(vote) 
    begin
        sum = 0;
        for(i=0; i<=6; i=i 1)
            if(vote[i]) sum = sum 1;
        if(sum[2]) pass = 1;
        else pass = 0;
    end

endmodule

This is the assignment left by my professor. Exactly, I would like to use case statement to rewrite the code below.

for(i=0; i<=6; i=i 1)
  if(vote[i]) sum = sum 1;

CodePudding user response:

Unlike different high-level programming languages like 'C', the Verilog case statement includes implicit break statements. verilog-case-statement in Verilog Tutorial

In my experience, your professor maybe made a mistake that he think Verilog can sequentially execute multiple case statements but actually it can not do that. So, you may use a awkward method which is as follow to response your professor.

module voter7(pass, vote);

output pass;
input[6:0] vote;
reg[2:0] sum;

integer i;
reg pass;

always @(vote) 
    begin
        sum = 0;

        casez(vote)
            7'b??????1: sum = sum   1;
        endcase
        casez(vote)
            7'b?????1?: sum = sum   1;
        endcase
        casez(vote)
            7'b????1??: sum = sum   1;
        endcase
        casez(vote)
            7'b???1???: sum = sum   1;
        endcase
        casez(vote)
            7'b??1????: sum = sum   1;
        endcase
        casez(vote)
            7'b?1?????: sum = sum   1;
        endcase
        casez(vote)
            7'b1??????: sum = sum   1;
        endcase
        
        if(sum[2]) pass = 1;
        else pass = 0;
    end

endmodule

CodePudding user response:

The for loop is not necessarily less efficient than a case statement. The issue is the ' ' operator. Synthesis can try to generate 7 sequential adders in your case, affecting number of gates and timing.

One of the ideas is to create a huge case statement which lists all possible combination of 4 bits. This will improve timing, not necessarily the number of gates.

casez(vote)
7'b???1111,
7'b??1?111,
7'b??11?11,
.... : pass = 1;

defalut: pass = 0;

The only problem is to list all possible combinations of 4 bits in a 7 bit system. I'll leave it up to you. The suggestion is to create a test bench and to compare results from the loop and the case statement.

BTW, use always @* instead of always @(vote). make it a habbit, it will save yo from many mistakes later.

  • Related