I am coding in Verilog a typical count-to-n-then-reset-to-0 counter. My module has the logic to increment and reset the counter.
My issue is that I don't know where the counter itself should be defined.
I could pass the counter (as inout?) to the module. That's ok, but the counter still has to be defined somewhere so it this doesn't do me any good.
Nothing else except this module should touch the counter, so I'd like to have the counter created within this module, and not passed in or out.
Is this reasonably standard, and if so, will someone point to a reference please on how to instantiate the counter?
(I'm on day 2 of Verilog, so be afraid, heh)
EDIT - Here's my code. As far as I can tell, it works. I haven't implemented DIR == REVERSE yet. Couple of interesting gotchas. The (now commented out) STEPPER=0 line was causing an error in a schematic; it thought that STEPPER was tied to ground as well as other logic.
Also, I use = instead of <= in some places involving counter - I was getting timing problems (I suppose.) The procedural assignment removed (hid?) the problem.
module cam(
input [7:0] DIVISOR,
input DIR,
input SPINDLE,
output reg STEPPER
);
parameter FORWARD = 1'b1;
parameter REVERSE = !FORWARD;
reg[7:0] counter = 0;
always @(posedge SPINDLE) begin
// STEPPER = 0;
if (DIR == FORWARD) begin
counter = counter + 1;
if (counter == DIVISOR) counter = 0;
end
else begin
// counter <= counter - 1;
// if (counter == (-1)) counter <= DIVISOR;
end
end
always @(negedge SPINDLE) begin
STEPPER = (counter == 0) ? 1 : 0;
end
endmodule
= 0
part ofreg[7:0] counter
probably won't translate to the hardware, you will have to use a reset line for that, e.g. in analways @(posedge clk, posedge reset)
you doif(reset) counter <= 1'b0;
One last thing - always define the width of the assigned value (e.g. 8'b00000001 or 8'hFE) otherwise it will default to the systems bitwidth (e.g. 32/64 bit) \$\endgroup\$1'b0
thing - I had a case Sunday where what I expected to be a single line was 32 bits wide. I had some troubles with the non-blocking assignment ofcounter
; it's used in bothalways
sections and had an undependable value. Instead of counting by 10, for example, the circuit would count to 11. \$\endgroup\$