I'm trying to implement the nand2tetris project in verilog and am hitting a wall using icarus verilog. In the book they implement the DFF as so, q(t) = d(t-1). The output at the current time is the input at the previous posedge clk. Here is the DFF I realized.
module Dff (
output reg q,
input data, clk
);
reg p;
reg o;
always @(posedge clk) begin
o <= data;
q <= p;
end
always @(negedge clk) begin
p <= o;
end
endmodule
This DFF seems to work just fine when I test it directly. But when I reused it to create a Bit (a memory cell), it gets crazy. Interestingly, the craziness is different using Icarus Verilog or EDAPlayground (which uses VCS).
module Mux (out, a, b, sel);
input a, b;
input sel;
output reg out;
assign out = ~sel ? a : b;
endmodule
module Bit (
output out,
input data, load, clk
);
Mux m0(in, out, data, load);
Dff d0(out, in, clk);
endmodule
Icarus Verilog output
data | load | clk | out
------+------+-----+-----
0 | 1 | 1 | x
0 | 1 | 0 | x
1 | 1 | 1 | x
1 | 1 | 0 | x
0 | 1 | 1 | 1
0 | 1 | 0 | 1
0 | 0 | 1 | 0
0 | 0 | 0 | 0
1 | 1 | 1 | 0
1 | 1 | 0 | 0
0 | 0 | 1 | 0 # !?!?!
0 | 0 | 0 | 0 # it should be 1 here.
EDAPlayground output
data | load | clk | out
------+------+-----+-----
0 | 1 | 1 | x
0 | 1 | 0 | x
1 | 1 | 1 | x
1 | 1 | 0 | x
0 | 1 | 1 | 1
0 | 1 | 0 | 1
0 | 0 | 1 | 0
0 | 0 | 0 | 0
1 | 1 | 1 | 1 # !?!?!
1 | 1 | 0 | 1 # it should be 0 here.
0 | 0 | 1 | 1
0 | 0 | 0 | 1
The code is testable on EDAPlayground.
initialblock (ieload <= 0, notload = 0, treat it like its coming out of another register somewhere), simulation order of the various blocks in your design (thealwaysin the DFF, theassignin the Mux and thealwaysclocking block andinitialstimulus block) matters. Ie, when the updates from theinitialblock happen are not happening when you want them to due to the blocking assignment.always @(posedge clk) begin q <= data; end. As Unn pointed out, yourdataandloadstimuli should be non-blocking so it doesn't cause a race condition with the clock. Alternatively, add a little delay so the simultaneous. Point being the new values for the stimuli must be updated after the clock.