1
\$\begingroup\$

I want to count number of "clock enable" signal inside flip flop.

I learn from tutorials that the output value should be assigned for all combinations of input.

However I don't know how to add counter that counter should be updated only if clk_enable = 1.

Please advise.

module count_ce (
  input logic reset_n, 
  input logic clk, 
  input logic clk_enable,
  output logic[63:0] counter
);

always_ff @(posedge clk or negedge reset_n) begin
  if (!reset_n) begin
    counter <= 64'd0;
  end else begin
    if (clk_enable) begin
      counter <= counter + 1;
    end else begin
      //counter <= counter; // ?
      counter <= 64'd0; // have to assign counter for else-case otherwise infer latch?
    end
  end
end

endmodule
\$\endgroup\$
0
\$\begingroup\$

In this case you do want to infer a latch. More correctly, you want to infer 64 edge-triggered flip-flops. Since that is your intent, you do not need to have an action for all input cases, or you can use the statement where the current value of counter is just assigned back to counter.

\$\endgroup\$
0
\$\begingroup\$

You code likes reasonable except:

  1. You can not generate latches in an always_ff or @(pos/neg edge always statement. As such can/may drop the whole else section.

  2. In fact here I would drop the else section because as soon as the clk_enable goes away your counter is reset and your count is lost.

  3. Your counter is 64 bit which is a bit big. It limits your maximum operating speed. Even running at 3GHz it will take ~195 years to overflow.

  4. It just looks a bit weird to have counter running since reset and not being able to clear or re-start it.

\$\endgroup\$
0
\$\begingroup\$

I learn from tutorials that the output value should be assigned for all combinations of input.

This is true for combinational logic, but you certainly intend to implement edge-triggered sequential elements (flip-flops).

In case you use always_ff and/or posedge clk, there is no possibility to infer latches. You will certainly have flip-flops.

always_ff @(posedge clk or negedge reset_n) begin
  if (!reset_n)
    counter <= 64'd0;
  else begin
    if (clk_enable)
      counter <= counter + 1;
  end
end

The always block above is safe even if there is no else condition. The counter will increment if clock_enable is HIGH, it will preserve its value if clock_enable is LOW.

The following code has the same behavior, the else part is just redundant.

always_ff @(posedge clk or negedge reset_n) begin
  if (!reset_n)
    counter <= 64'd0;
  else begin
    if (clk_enable)
      counter <= counter + 1;
    else
      counter <= counter;
  end
end
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.