1

I am trying to create a second clk counter using a 100 MHz clk input, but when I simulate the clk divider, it just shows the output as an X even though the clk input is correct. What could I be doing wrong?

1 second clk divider:

module clkdiv(
    input clk,
    input [25:0] terminalcount,
    output reg clk_div
);

reg [25:0] count;
wire tc;

assign tc = (count == terminalcount);

always @ (posedge(clk)) begin
    if (tc) count <= 0;
    else count <= count + 1;
end

always @ (posedge(clk)) begin
    if (tc) clk_div = !clk_div;
end

endmodule

Test Bench:

module clockdivTB;

// inputs 
reg clk; // make 100 MHz -- T = 10 ns

// outputs
wire newclk;

// second clock -- connect test signals to clkdiv
clkdiv slowclkCUT (
    .clk(clk),
    .terminalcount(50000000-1), // 1 Hz
    .clk_div(newclk)
);

// initialize inputs
initial begin 
    clk = 0;    
    
    // create input clock 100MHz
    forever #5 clk = ~clk;
end

endmodule

Result:

Shows 100MHz clk but no output 1Hz clk

toolic
  • 57,801
  • 17
  • 75
  • 117
  • sounds right. Your `tc` gets active only when counter reaches certain value. Till that time it is `0`. As such, *counter* cannot be reset and stays at `x`. In other words, it will never exit this state. You need to think about resetting the counter at a reset signal. – Serge Dec 23 '21 at 01:36

1 Answers1

0

The output is X because reg types are initialized to X (unknown). You need to initialize the output to a known value. For simulation purposes, you can set clk_div and count to 0 as follows:

module clkdiv(
    input clk,
    input [25:0] terminalcount,
    output reg clk_div = 0
);

reg [25:0] count = 0;

However, if you want to synthesize your logic, you likely need to add a reset input. You can drive the input from your testbench.

module clkdiv(
    input reset,
    input clk,
    input [25:0] terminalcount,
    output reg clk_div
);

reg [25:0] count;
wire tc;

assign tc = (count == terminalcount);

always @ (posedge(clk)) begin
    if (reset) count <= 0;
    else if (tc) count <= 0;
    else count <= count + 1;
end

always @ (posedge(clk)) begin
    if (reset) clk_div <= 0;
    else if (tc) clk_div <= !clk_div;
end

endmodule
toolic
  • 57,801
  • 17
  • 75
  • 117