记录时钟分频器的Verilog代码编写,主要掌握分频器设计思路
VISIO作图,计数器cnt从0计数到7,计数到7清零从新开始计数。
0-3输出为低电平,4-7输出为高电平。
时钟频率为50MHZ,周期为20ns,八分频即周期扩大八倍,周期为160ns
下面是verilog写的程序代码,包含几种不同的写法,包含组合逻辑,时序逻辑同步与异步
module div_8(
input wire clk,
input wire rst_n,
output reg out1 ,
output wire out2 ,
output reg out3 ,
output reg out4 ,
output reg out5 ,
output reg out6 ,
output reg out7 ,
output reg out8 ,
output reg out9 ,
output reg out10
);
reg[4:0] cnt;
always@(posedge clk or negedge rst_n)
begin
if(~rst_n)
cnt<=4'b0;//8fenp,
else if(cnt==4'd7)
cnt<=4'b0;
else
cnt<=cnt+4'b1;
end //计数器
always@(posedge clk or negedge rst_n)
begin
if(~rst_n)
out1<=4'b0;
else if(cnt==4'd3)
out1<=4'b1;
else if(cnt==4'd7)
out1<=4'b0;
end
assign out2=(cnt<=4'd3)? 4'd0:4'd1;
always@(*) //组合逻辑
begin
case(cnt)
4'd0,4'd1,4'd2,4'd3:out3<=4'd0;
4'd4,4'd5,4'd6,4'd7:out3<=4'd1;
default out3<=4'd0;
endcase
end
always@(posedge clk or negedge rst_n)
begin
if(~rst_n)
out4<=4'b0;
else if(cnt<=4'd2 || cnt==4'd7)
out4<=4'd0;
else
out4<=4'd1;
end
always@(*)
begin
if(~rst_n)
out5<=4'b0;
else if(cnt<=4'd3)
out5<=4'd0;
else
out5<=4'd1;
end
always@(*)
begin
if(~rst_n)
out6<=4'b0;
else if(cnt==4'd4)
out6<=4'd1;
else if(cnt==4'd0)
out6<=4'd0;
end
always@(*)
begin
out7<=(cnt<=4'd3)? 4'd0:4'd1;
end
always@(posedge clk )
begin
if(~rst_n)
out8<=4'b0;
else if(cnt==4'd7 || cnt<=4'd2)
out8<=4'd0;
else
out8<=4'd1;
end
always@(posedge clk )
begin
if(~rst_n)
out9<=4'b0;
else if(cnt==4'd3 || cnt==4'd7)
out9<=~out9;
else
out9<=out9;
end
always@(posedge clk or negedge rst_n)
begin
if(~rst_n)
out10<=4'b0;
else
begin
case(cnt)
4'd0,4'd1,4'd2,4'd7:out10<=4'd0;
default out10<=4'd1;
endcase
end
end
endmodule
仿真文件
`timescale 1ns/1ps
module div_8_tb();
reg clk ;
reg rst_n;
wire out1 ;
wire out2 ;
wire out3 ;
wire out4 ;
wire out5 ;
wire out6 ;
wire out7 ;
wire out8 ;
wire out9 ;
wire out10 ;
initial begin
clk=1'b0;
rst_n=1'b0;
#20
rst_n=1'b1;
end
always #10 clk=~clk;
div_8 div_8(
.clk (clk ),
.rst_n (rst_n),
.out1 (out1),
.out2 (out2),
.out3 (out3),
.out4 (out4),
.out5 (out5),
.out6 (out6),
.out7 (out7),
.out8 (out8),
.out9 (out9 ),
.out10 (out10)
);
endmodule
仿真结果