module UpDownCounter(
input wire clock_pulse,
input wire mode,
output reg [2:0]counter
);
reg [2:0]next_counter;
always @(posedge clock_pulse) begin
if(mode == 1'b1) begin
if(counter == 3'b111) begin
next_counter <= 3'b000;
end
else begin
next_counter <= counter + 1;
end
end
else begin
if(counter == 3'b000) begin
next_counter <= 3'b111;
end
else begin
next_counter <= counter - 1;
end
end
end
initial begin
counter <= 3'b000;
end
always @(*) begin
counter <= next_counter;
end
endmodule
Testbecnch code for simulation
module UpDownCounter_TB;
reg CLK;
reg MODE;
wire [2:0]COUNTER;
UpDownCounter
counter_instance(.clock_pulse(CLK), .mode(MODE), .counter(COUNTER));
always begin
#10 CLK = ~CLK;
end
initial begin
MODE = 1'b0;
CLK = 1'b0;
#800;
$finish;
end
always @(posedge CLK) begin
$display("CLK = %b, MODE = %b, COUNTER = %b", CLK, MODE, COUNTER);
end
endmodule