硬件电路
代码
my_BCD_counter
//BCD counter
module my_BCD_counter(clk,cin,rst_n,cout,q);
input clk,cin,rst_n;
output cout; //时序变组合 去掉reg
output [3:0] q;
reg [3:0] cnt;
always @ (posedge clk or negedge rst_n)
if(!rst_n)
cnt <= 4'd0;
else if(cin == 1'b1)begin
if(cnt == 4'd9)
cnt <= 4'b0;
else
cnt <= cnt + 1'b1;
end
else
cnt <= cnt;
//产生进位输出信号
//时序逻辑有延迟
/*
always @ (posedge clk or negedge rst_n)
if(!rst_n)
cout <= 1'b0;
else if(cin == 1'b1 && cnt == 4'd9)
cout <= 1'b1;
else
cout <= 1'b0;
if(cin == 1'b1 && cnt == 4'd9)
*/
//产生进位输出信号
//assign cout = (cin == 1'b1 && cnt == 4'd9)?1'b1:1'b0; //两种皆可
assign cout = (cin == 1'b1 && cnt == 4'd9);
assign q = cnt ;
endmodule
my_BCD_counter_top 三次例化
module my_BCD_counter_top (clk,cin,rst_n,cout,q);
input clk,cin,rst_n;
output cout; //不赋值,直接输出 去掉reg
output [11:0] q;
wire cout0,cout1;
wire [3:0] q0,q1,q2;
assign q={q2,q1,q0}; //拼接
my_BCD_counter my_BCD_counter0(
.clk (clk),
.cin (cin),
.rst_n (rst_n),
.cout (cout0),
.q (q0)
);
my_BCD_counter my_BCD_counter1(
.clk (clk),
.cin (cout0),
.rst_n (rst_n),
.cout (cout1),
.q (q1)
);
my_BCD_counter my_BCD_counter2(
.clk (clk),
.cin (cout1),
.rst_n (rst_n),
.cout (cout),
.q (q2)
);
endmodule
激励文件
my_BCD_counter_tb
`timescale 1ns/1ns
`define clock_period 20
module my_BCD_counter_tb;
reg clk,cin,rst_n; //激励信号
wire cout; //输出信号
wire [3:0] q;
my_BCD_counter my_BCD_counter0(
.clk (clk),
.cin (cin),
.rst_n (rst_n),
.cout (cout),
.q (q)
);
//T=20ns 给激励信号
initial clk = 1'b1;
always #(`clock_period / 2) clk = ~clk;
initial begin
rst_n = 1'b0; //初始态
cin = 1'b0;
#(`clock_period * 200);
rst_n = 1'b1;
#(`clock_period * 20);
repeat(30)begin
cin = 1'b1;
#`clock_period ;
cin = 1'b0;
#(`clock_period * 5);
end
#(`clock_period * 5);
$stop;
end
endmodule
my_BCD_counter_top_tb
`timescale 1ns/1ns
`define clock_period 20
module my_BCD_counter_top_tb;
reg clk,cin,rst_n; //激励信号
wire cout; //输出信号
wire [11:0] q;
my_BCD_counter_top my_BCD_counter_top0(
.clk (clk),
.cin (cin),
.rst_n (rst_n),
.cout (cout),
.q (q)
);
//T=20ns 给激励信号
initial clk = 1'b1;
always #(`clock_period / 2) clk = ~clk;
initial begin
rst_n = 1'b0; //初始态
cin = 1'b0;
#(`clock_period * 200); //4000ns
rst_n = 1'b1;
#(`clock_period * 20); //4400ns
cin = 1'b1;
#(`clock_period * 5000); //10_4400ns
$stop;
end
endmodule
需要注意
1>.时序逻辑有时钟的延迟,时钟上升沿触发一次。
always @ (posedge clk or negedge rst_n)
if(!rst_n)
cout <= 1'b0;
else if(cin == 1'b1 && cnt == 4'd9)
cout <= 1'b1;
else
cout <= 1'b0;
2>.组合逻辑无时钟延迟
//产生进位输出信号
//assign cout = (cin == 1'b1 && cnt == 4'd9)?1'b1:1'b0; //两种皆可
assign cout = (cin == 1'b1 && cnt == 4'd9);