I'm trying to complete HDLBits' question from circuits/sequential logc/latches and flip flops: DFFs and Gates.
I've found solutions online, but I want to understand why my (much more obstinate) solution isn't working:
module top_module (
input clk,
input x,
output z
);
wire d_xor, d_and, d_or;
wire z1, z2, z3;
wire fb_xor, fb_and, fb_or;
assign d_xor = x ^ fb_xor;
assign d_and = x && fb_and;
assign d_or = x || fb_or;
d_ff(.d(d_xor), .clk(clk), .q(fb_xor));
d_ff(.d(d_and), .clk(clk), .q(z2), .nq(fb_and));
d_ff(.d(d_or), .clk(clk), .q(z3), .nq(fb_or));
assign z = ~|{fb_xor, z2, z3};
endmodule
module d_ff (
input wire d,
input wire clk,
output reg q = 1'b0,
output reg nq = 1'b1
);
always @(posedge clk) begin
q = d;
nq = ~d;
end
endmodule
There was no difference when I use q = d;
vs. q <= d;
, and the output made it seem like my output was delayed 1 cycle behind the correct signal.
The problem is with the HDLBits website, not your code.
One big disadvantage to the site is that they don't show you the Verilog testbench code that is used. You can't see how the testbench drives input signals or how it samples output signals for the comparison. There could be a subtle bug in the testbench code.
Also, the simulation software used by HDLBits (Quartus/Modelsim) may have bugs which cause the mismatch.
I created a simple testbench on EDA Playground, and it shows the expected output waveforms.
Unrelated to your problem...
You should always use nonblocking assignments to model flip flops:
q <= d;
nq <= ~d;
You should also fix the warnings you get on HDLBits:
Critical Warning (10846): Verilog HDL Instantiation warning at top_module.v(14): instance has no name File: /home/h/work/hdlbits.13984440/top_module.v Line: 14
Critical Warning (10846): Verilog HDL Instantiation warning at top_module.v(15): instance has no name File: /home/h/work/hdlbits.13984440/top_module.v Line: 15
Critical Warning (10846): Verilog HDL Instantiation warning at top_module.v(16): instance has no name File: /home/h/work/hdlbits.13984440/top_module.v Line: 16
Add instance names:
d_ff i0 (.d(d_xor), .clk(clk), .q(fb_xor), .nq());
d_ff i1 (.d(d_and), .clk(clk), .q(z2) , .nq(fb_and));
d_ff i2 (.d(d_or ), .clk(clk), .q(z3) , .nq(fb_or));