You are on page 1of 3

程序主体:

`timescale 1ns/1ps;
module Count(clk,rst_n,updown,cnt);// Use updown to decide whether it is an addition or a subtraction
counter
input clk,rst_n,updown;
output reg [3:0] cnt;
reg [3:0] q;

initial
begin
q = 4'b0;
end

always@(posedge clk)
begin
if(!rst_n)
q = 4'b0;
else begin
if(!updown)//updown=0 means an addition counter
begin
if(q == 4'd12)
q = 4'b0;
q = addr(q);
end
else
begin//updown=1 means a subtraction counter
if(q == 4'b0)
q = 4'd12;
q = subr(q);
end
end

cnt = q;
end

function [3:0] addr;//the function of an addition counter


input reg [3:0] cnta;
begin
addr = cnta + 4'b1;
end
endfunction

function [3:0] subr;//the function of a subtraction counter


input reg [3:0] cnts;
begin
subr = cnts - 4'b1;
end
endfunction

endmodule

测试文件:
module Count_tst();
reg clk;
reg rst_n;
reg updown;
wire [3:0] cnt;
Count wt(.clk(clk),.rst_n(rst_n),.updown(updown),.cnt(cnt));
initial
begin
clk = 0;
updown = 0;
#5 rst_n = 0;
#6 rst_n = 1;
forever
#1 clk = ~clk;
end
always
begin
#200 updown = 1;
#500 updown = 0;
#700 updown = 1;
end
endmodule

仿真结果:
12 进制计数器加法段:
12 进制计数器减法段:

You might also like