module up_down_counter( input clock, input reset, input load, input up_down, //up_down = 1'b1,upcounter; up_down=1'b0,down_counter input [3:0] data, output [3:0] counter );
reg [3:0] counter_reg;
always@(posedge clock or posedge reset) begin
module up_down_counter(
input clock,
input reset,
input load,
input up_down, //up_down = 1'b1,upcounter; up_down=1'b0,down_counter
input [3:0] data,
output [3:0] counter
);
reg [3:0] counter_reg;
always@(posedge clock or posedge reset)
begin
if(reset == 1'b1)
begin
counter_reg <= 4'b0000;
end
else
begin
if (up_down == 1'b1)
begin
if(load == 1'b1)
begin
counter_reg <= data;
end
else
begin
counter_reg <= counter_reg + 4'b0001;
end
end
else
begin
if(load == 1'b1)
begin
counter_reg <= data;
end
else
begin
counter_reg <= counter_reg - 4'b0001;
end
end
end
end
assign counter = counter_reg;
endmodule
end
assign counter = counter_reg;
endmodule
my Test Bench:
module tb_up_down_counter;
reg clock; reg reset; wire [3:0] counter; reg up_down; reg load; reg [3:0] data;
up_down_counter dut( .clock(clock), .reset(reset), .load(load), .data(data), .up_down(up_down), .counter(counter) );
initial begin clock = 1'b0; forever #50 clock = ~clock; end
module tb_up_down_counter;
reg clock;
reg reset;
wire [3:0] counter;
reg up_down;
reg load;
reg [3:0] data;
up_down_counter dut(
.clock(clock),
.reset(reset),
.load(load),
.data(data),
.up_down(up_down),
.counter(counter)
);
initial
begin
clock = 1'b0;
forever #50 clock = ~clock;
end
initial
begin
reset <= 1'b0;
load <= 1'b0;
up_down <= 1'b0;
data <= 4'd0;
repeat(5)
@(posedge clock);
reset <= 1'b1;
repeat(5)
@(posedge clock);
reset <= 1'b0;
repeat(10)
@(posedge clock);
up_down <= 1'b1;
repeat(5)
@(posedge clock);
load <= 1'b1;
repeat(10)
@(posedge clock);
data <= 4'd3;
repeat(5)
@(posedge clock);
up_down <= 1'b0;
repeat(5)
@(posedge clock);
load <= 1'b0;
repeat(5)
@(posedge clock);
load <= 1'b1;
repeat(10)
@(posedge clock);
data <= 4'd5;
repeat(5)
@(posedge clock);
up_down <= 1'b1;
repeat(5)
@(posedge clock);
reset <= 1'b1;
repeat(10)
@(posedge clock);
reset <= 1'b0;
repeat(10)
@(posedge clock);
load <= 1'b1;
repeat(10)
@(posedge clock);
data <= 4'd8;
repeat(10)
@(posedge clock);
data <= 4'd15;
repeat(10)
@(posedge clock);
data <= 4'd12;
#5000 $finish;
end
initial
begin
$shm_open("waves.shm");
$shm_probe(tb_up_down_counter,"AC");
end
endmodule
initial begin $shm_open("waves.shm"); $shm_probe(tb_up_down_counter,"AC"); end
endmodule