一 偶分频:
这个是最简单的分频操作
// 偶数分频
module oushufenpin(
input clk,
input rst,
output reg div
);
reg [2:0] counter;
always @(posedge clk) begin
if (rst)
counter <= 3'd0;
else begin
if (counter == 3'd1)
counter <= 3'd0;
else
counter <= counter + 3'd1;
end
end
always @(posedge clk) begin
if (rst)
div <= 0;
else begin
if (counter == 3'd1)
div <= ~div;
else
div <= div;
end
end
endmodule
测试代码:
module oushufenpin_tb;
reg clk;
reg rst;
wire div;
initial begin
clk = 0;
rst = 1;
#100 rst = 0;
end
always #10 clk = ~clk;
oushufenpin u0(
.clk(clk),
.rst(rst),
.div(div)
);
endmodule
modelsim仿真:
二 奇分频:
5分频:
module jifenpin(
input clk,
input rst,
output reg div_clk
);
reg[2:0] count = 3'd0;
always @(posedge clk or negedge clk) begin
if (rst)
count <= 3'd0;
else begin
if (count == 3'd3)
count <= 3'd0;
else
count <= count + 3'd1;
end
end
always @(posedge clk or negedge clk) begin
if (rst)
div_clk <= 0;
else begin
if (count == 3'd3)
div_clk <= ~div_clk;
else
div_clk <= div_clk;
end
end
endmodule
modelsim:
三 小数分频:
0.8分频,一个周期中4个1,1个0
主程序:
// 0.8分频
module xiaoshufenpin(
input clk,
input rst,
output reg div_clk
);
// 5个周期中4个周期为1,一个为0
reg[3:0] count = 4'd0;
always @(posedge clk) begin
if (rst)
count <= 4'd0;
else begin
if (count == 4'd4)
count <= 4'd0;
else
count <= count + 4'd1;
end
end
always @(posedge clk) begin
if (rst)
div_clk <= 0;
else begin
if (count == 4'd0)
div_clk <= 1;
else if (count == 4'd4)
div_clk <= 0;
end
end
endmodule
测试程序:
module xiaoshufenpin_tb;
reg clk;
reg rst;
wire div_clk;
initial begin
clk = 0;
rst = 1;
#100
rst = 0;
end
always #10 clk = ~clk;
xiaoshufenpin u0(
.clk(clk),
.rst(rst),
.div_clk(div_clk)
);
endmodule