module d_latch_controlled_counter(
input D, // Data input
input rst, // Reset input
input enable, // Enable input
output reg [3:0] count
);
reg Q; // Internal D latch output
// D latch logic
always @(D or rst) begin
if (rst)
Q <= 1'b0;
else
Q <= enable ? D : 1'b0; // D latch enabled by "enable"
end
// 4-bit counter logic
always @(posedge Q or posedge rst) begin
if (rst)
count <= 4'b0000;
else if (Q) // Counter increments only when Q is high
count <= count + 1;
end
endmodule
module testbench;
reg D, rst, enable;
wire [3:0] count;
// Instantiate the combined module
d_latch_controlled_counter combined (D, rst, enable, count);
// Testbench logic
initial begin
// Initialize VCD dump
$dumpfile("testbench.vcd");
$dumpvars(0, testbench);
// Initialize
D = 0; rst = 1; enable = 0; // Set enable to 0 initially
#20 rst = 0;
// Enable counter by setting D latch with enable
#20 D = 1; enable = 1; // Both D and enable are high, Q follows D
// Run for a while to observe counting
#100;
// Change D while enable is still low to demonstrate holding of Q
#20 D = 0; // D goes low, but enable is still high
#10 enable = 0; // enable goes low after a delay
// Run for a while to observe no counting
#100;
// Enable counter again with enable
#20 enable = 1; // enable goes high, D still low
#10 D = 1; // D goes high after a delay
// Run for a while to observe counting
#100;
// Finish simulation
$finish;
end
endmodule