How to get outputs/pulses when counter reaches two particular values?

Viewed 79

I have created a counter that counts up to 30. I have an output signal out. At two particular counts, i.e., when counter reaches 10 (first) and when counter reaches 15 (second), I want the output to become low. Somehow I'm missing a basic logic here as only at one particular count (either at 10 or 15) I'm able to make the output zero.

Here is the code

module user_def_pulse(
    output integer counter,
    output reg out,
    input clk, reset
    );

    parameter no_of_counts = 30;
    parameter first = 10;
    parameter second = 15;
 
    initial
    begin
        counter = 0;
        out = 1'b0;
    end
        
    always @(posedge clk)
        begin
            if (reset)
            begin
                counter <= 1'b0;
            end
            else if (counter == no_of_counts)
            begin
                counter <= 1'b0;
                out <= 1'b0;
            end
            else
            begin
                if ((counter == first) || (counter == second))
                    out <= 1'b0;
                else
                    begin
                    counter <= counter + 1;
                    out <= 1'b1;
                    $display($time," The value of counter is %d", counter);
                    end
            end
        end
endmodule

Here is the test bench

module user_def_pulse_tb(
);
    parameter time_period = 10;
    
    wire [31:0] COUNTER;
    wire OUT;
    reg CLK, RESET;
    
    user_def_pulse udp1 (.counter(COUNTER), .out(OUT),  .clk(CLK), .reset(RESET));
      
    initial
        begin
            CLK = 1'b0;
            RESET = 1'b1;
            #20 RESET = 1'b0;
        end
    
    always
        #time_period CLK = ~CLK;
  
endmodule

Here is the output waveform.

enter image description here

1 Answers

The problem with your code is that is stops incrementing the counter as soon as it hits the first value. You need to keep incrementing the counter. I moved the increment outside of the if ((counter == first) || ... clause.

always @(posedge clk) begin
    if (reset) begin
        counter <= 1'b0;
    end else if (counter == no_of_counts) begin
        counter <= 1'b0;
        out <= 1'b0;
    end else begin
        counter <= counter + 1;
        $display($time," The value of counter is %d", counter);
        if ((counter == first) || (counter == second)) begin
            out <= 1'b0;
        end else begin
            out <= 1'b1;
        end
    end
end
Related