How to compare in Verilog

verilog

So I am having trouble comparing values in Verilog for a counter module. I have a 16 bit reg 'd' that I use to assign to a output wire count. In the conditional statements, I have an 16 bit input that I use to compare 'd' to. When I use this input, all works well, but I want to use another reg to compare d to. I think I am having trouble understanding how comparing works in Verilog, can I compare two reg variables?

module counter(input clk, 
input [15:0] load, 
input reset, 
input up_down, 
input [15:0] TBPRD_SHDW, 
input [15:0] TBPRD, 
input [1:0] mode, 
output wire [15:0] count, 
output reg CTR_eq_PRD, 
output CTR_dir, 
output reg CTR_eq_MAX, 
output reg CTR_eq_ZERO, 
output reg global_load);
reg [15:0] d;

reg [15:0] TBPRD_SHDW_reg;
reg [15:0] TBPRD_reg;
initial d = 0;
initial TBPRD_SHDW_reg = TBPRD_SHDW;
initial TBPRD_reg = TBPRD;

assign count = d;
always @(posedge clk or posedge reset) begin
    if(mode == 2'b00) begin 
        if(d < TBPRD) 
            d <= d + 1'b1; 
        else if(d >= TBPRD)
            d <= 0;
    end  

This works.

assign count = d;
always @(posedge clk or posedge reset) begin
    if(mode == 2'b00) begin 
        if(d < TBPRD_reg) 
            d <= d + 1'b1; 
        else if(d >= TBPRD_reg)
            d <= 0;
    end 

This does not

Best Answer

There's nothing wrong with the comparison per se. The real problem is how you are assigning values to the signals being compared.

The only assignment to TBPRD_reg that you've shown us is in an initial statement. If this is the only assignment in the design, then that's your problem.

An initial statement is primarily useful in simulation, where it is used to initialize signals before the simulation starts. As such, it cannot be used to copy values from an input port, because in general, those values haven't yet been set.

The initial statement should not be relied upon to do anything at all in the synthesized design, unless you know for sure that the FPGA technology you're using allows initial values for FFs to be stored in the configuration file. Again, even if this is true, it cannot be used to copy dynamic values from an input port.

In general, you should develop the habit of initializing FFs based on the reset signal and nothing else. That way, you can reset your design without power-cycling it to force a reconfiguration.