veriloghdl

Parity checker in verilog only calculates a result once


I'm trying to write a code to check for even/odd parity in Verilog.

`timescale 1ns / 1ps

module ParityChecker(
input [7:0] bitt,
output reg ans
);

integer count = 0;
integer i = 0;

initial
begin
    count = 0;
    for(i=0; i<=7; i=i+1)
    begin
        if(bitt[i]==1)
        count = count + 1;
    end
    if(count%2==0)  //even parity
    ans = 1;
    else
    ans = 0;
    
end

endmodule

Here's the testbench code:

module ParityChecker_tb;

reg [7:0] bitToSend;
wire answer;

ParityChecker mygate(.bitt(bitToSend), .ans(answer));

initial
begin
$monitor(bitToSend, answer);

bitToSend = 8'b11111101;
#10
bitToSend = 8'b11111100;
#10
bitToSend = 8'b1111111;

end
endmodule

However, I'm only getting one as output for the variable answer, no matter what. There seems to be some problem in the logical part. What could be it?


Solution

  • Because in module ParityChecker you used initial to implement your logic, which is only executed once.

    You can implement it as always@ block, like

    always@(bitt)
    begin
        // All your logic...
        // Or even simpler,
        ans = ~^bitt;
    end
    

    The simplest way would be:

    module ParityChecker(
    input [7:0] bitt,
    output ans
    );
        assign ans = ~^bitt;
    endmodule