Electronic – Verilog design decision – where should the counter be located

verilog

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

Best Answer

If you have two modules, and you want to use one in the other then you instantiate and connect the desired ports together.

For instance, if you have a top module with the signals clk, rst_count, inc_count and count_out and you are wanting to instantiate a (already written) Counter module with the name "MyCount" and with port names clk, rst, inc and data_out in it:

Counter  MyCount (.clk(clk), 
                  .rst(rst_count), 
                  .inc(inc_count),
                  .data_out(count_out));

An excellent starting book that will take you through Verilog for synthesis (as opposed to the large part of the language which cannot be used in this way, and is primarily for simulation) is Pong Chu's "FPGA Prototyping with Verilog Examples".