Electronics > FPGA

Variable clock divider

(1/5) > >>

kpow8050:
Hi,

I am having trouble getting the following verilog HDL code to compile. My intent is to make a variable frequency divider. The way it works is you give it a divider number and and clock source, using an internal counter it will then count up until this value matches the divider number and change state of the output clock. The counter is then reset. However the compiler is not happy with my assignment of "assign count = count + 1;". Is this not allowed in HDL? How could I keep track of the count? Thanks

module clock_divider(input wire[12:0] divider, input clk, output reg clk_out);
   // This module will divide an input clock signal by the amount in divider (16 bit register)
   // For finer control of clock divisions change the divider register size
   
   // Internal counter memory
   reg [12:0] count;
   
   always @(posedge clk)
      if (count >= divider) begin
         clk_out <= ~clk_out;
         count = 0;
      end
     
      assign count = count + 1;
     
endmodule

ataradov:
It would be something like this:

--- Code: ---   always @(posedge clk) begin
      if (count >= divider) begin
         clk_out <= ~clk_out;
         count <= 0;
      end else
        count <= count + 1;
end

--- End code ---

fourfathom:
How about this:

 always @(posedge clk) begin
      if (count >= divider) begin
         clk_out <= ~clk_out;
         count <= 0;
      end
     
      else count <= count + 1;
 end

Or like this:
always @(posedge clk) begin
      count <= count + 1;
      if (count >= divider) begin
         clk_out <= ~clk_out;
         count <= 0;
      end
end

BrianHG:

--- Quote from: fourfathom on January 15, 2022, 01:43:11 am ---How about this:

 always @(posedge clk) begin
      if (count >= divider) begin
         clk_out <= ~clk_out;
         count <= 0;
      end
     
      else count <= count + 1;
 end

Or like this:
always @(posedge clk) begin
      count <= count + 1;
      if (count >= divider) begin
         clk_out <= ~clk_out;
         count <= 0;
      end
end

--- End quote ---
Some compilers and simulators will allow you to get away with simultaneously assigning 2 different results to 'count', but this is considered bad practice.  Your first solution and ataradov did it the right way with the 'else'.

ataradov:
I think all tools should accept this. The last assignment wins.

In this case 'else' is better for clarity, but the 'default' value is often necessary in big state machines with a lot of cases and conditions inside them. I use that all the time and never seen any tool complain.

This is a very common practice when evaluating the next state, for example. In most cases you want to stay in the current state, and if you have to do the same assignment to the current state in all the blocks, you will go mad and likely miss something.

Navigation

[0] Message Index

[#] Next page

There was an error while thanking
Thanking...
Go to full version