Reputation: 1
I am trying to create a 4 bit counter using D flip flops in Verilog. I am following this diagram https://i.sstatic.net/XbRAv.png. I got the code for the individual D flip flop. The problem I am having is with D0 in the first clock cycle. I am guessing I have to assume Q0 to be 1 and Q1, Q2, Q3 to be 0 at first. I am not sure how to pass the initial value for D0 only once in the code.
module DFlipFlop(CLK, D, Q);
input CLK, D;
output Q;
reg Q;
always @(posedge CLK) begin
Q <= D;
end
endmodule
module RippleMod(CLK, q0, q1, q2, q3);
input CLK;
output q0, q1, q2, q3;
DFlipFlop d1 (CLK,q3,q0);//not sure about q3 there, think I will get X if i do this.
DFlipFlop d2 (CLK,q0,q1);
DFlipFlop d3 (CLK,q1,q2);
DFlipFlop d4 (CLK,q2,q4);
endmodule
Upvotes: 0
Views: 1936
Reputation: 1
At first you need to initialise the ring counter otherwise output remains in undefined state xxxx. Try out below code, where ffs are explicitly are initialised using an asynchronous load signal...
module shiftreg;
reg [3:0] in;
output [3:0] q;
reg clk, ld, rst;
dff D0 (q[3], clk, rst, 1'b1, q[0]);
dff D1 (q[0], clk, rst, 1'b0, q[1]);
dff D2 (q[1], clk, rst, 1'b0, q[2]);
dff D3 (q[2], clk, rst, 1'b0, q[3]);
initial clk = 0;
initial forever #5 clk = ~clk;
initial begin
$monitor($time, "ld = %b q = %b", ld, q);
#100 $finish;
end
endmodule
module dff (d, clk, rst, ld, q);
input d, clk, ld, rst;
output reg q;
initial if (ld) q <= 1; else q <=0;
always @ (posedge clk)
if (rst == 1)
q <= 0;
else q <=d;
endmodule
Upvotes: 0
Reputation: 12354
verilog initializes all 4-state variables to 'x'. so, you would run an 'x' around the loop forever without any real change. You need to provide an input to your case. something like the following (in SV)
module RippleMod(CLK, en, in, q0, q1, q2, q3);
input CLK, en, in;
output q0, q1, q2, q3;
logic d1in;
always_ff @(negedge clk) begin
if (en)
d1in <= in;
else
d1in <= q3;
end
DFlipFlop d1 (CLK,d1in,q0);
DFlipFlop d2 (CLK,q0,q1);
DFlipFlop d3 (CLK,q1,q2);
DFlipFlop d4 (CLK,q2,q4);
endmodule
Upvotes: 0
Reputation: 10504
You need to do something to set the initial state.
For simulation you can generally use "initial" blocks to set the initial state of registers. Some synthesis tools, especially those targeting FPGAs/CPLDs also support setting initial states in this way. Some synthesis tools that do not support initial blocks may support a tool-specific way of setting initial conditions.
The other option is to build a reset line into your flip-flops. The downside of this is of course that you then need something to trigger the reset line, either your testbench in simulation or some kind of hardware in a real implementation.
Upvotes: 0
Reputation: 389
Using a reset signal will help you. So you just need to reset Q3 to 1 and the rest of the signals to 0.
Upvotes: 2