Search code examples
veriloghdlflip-flop

HDLBits Dff8p - Reset not working when using a generate loop


I'm trying to solve this HDLBits question, and my problem occurs when submitting the following code:

module top_module (
    input clk,
    input reset,
    input [7:0] d,
    output [7:0] q
);
    
    genvar i;
    generate for(i = 0; i < 8; i = i + 1)
        begin: DFF
            dFlipFlop instance_i(.clk(clk), .reset(reset), .d(d[i]), .q(q[i]));
        end
    endgenerate

endmodule

module dFlipFlop(input clk, input reset, input d, output q);
    always@(negedge clk) begin
        if(reset) q <= 8'h34;
        else q <= d;
    end
endmodule

Submitting this code gives me the hint "Your reset doesn't seem to be working.", and it is an unsuccessful attempt.

This error is fixed by removing the use of the generate loop and implementing a single, 8-bit flip flop as follows:

module top_module (
    input clk,
    input reset,
    input [7:0] d,
    output [7:0] q
);
    
    always@(negedge clk) begin
        if(reset) q <= 8'h34;
        else q <= d;
    end

endmodule

Why does the use of a generate loop cause issues?


Solution

  • The problem is not with the generate loop.

    The problem is this line:

        if(reset) q <= 8'h34;
    

    When you declare output q, q is 1-bit wide, but you attempt to assign an 8-bit value to it (8'h34). This is the same as 8'b0011_0100. q is always assigned to the LSB of the value, which is 0. The 7 MSBs are ignored. This means that all 8 instances of dFlipFlop are reset to the same value (0). The code behaves as though you used this line:

        if(reset) q <= 0;
    

    When you declare q as 8-bit (output [7:0] q), you successfully reset the 8-bit q to the desired value.

    When I run your code on the HDLBits website, I see this warning when I click on the "Show Quartus messages..." link:

    Warning (10230): Verilog HDL assignment warning at top_module.v(19): truncated value with size 8 to match size of target (1) File: /home/h/work/hdlbits.14193329/top_module.v Line: 19