Verilog时钟分频(偶数分频、奇数分频、小数分频、半整数分频)
偶数分频
偶数分频最容易实现,可以用计数器实现。计数值小的时候也可以使用DFF直接完成。这里使用计数器实现,计数达到分频系数一半的时候进行翻转(占空比为50%)。对应: 牛客 VL37 时钟分频(偶数)
/**
使用计数方式实现了8分频
*/
module even_div(
input wire rstn,
input wire clk,
output reg clk_out
);
reg [1:0] count;
/**
count operation
*/
always @(posedge clk or negedge rstn) begin
if(~rstn) begin
count <= 2'b0;
end
else begin
count <= count + 1'b1;
end
end
always @(posedge clk or negedge rstn) begin
if(~rstn) begin
clk_out <= 1'b0;
end
else if(count == 2'b00) begin
clk_out <= ~clk_out;
end
end
endmodule
仿真结果如下
奇数分频
不要求占空比为50%的奇数分频
不要求占空比为50%,可以与偶数分频一样,根据计数值进行波形翻转。
对应: 牛客 VL42 无占空比要去的奇数分频
/**
不要求占空比的奇数分频
5分频 3低电平2高电平
占空比 2/5
*/
module odd_div (
input wire rstn,
input wire clk,
output reg clko
);
parameter N = 5;
reg [2:0] count;
always @(posedge clk or negedge rstn) begin
if(~rstn) begin
count <= 3'd0;
end
else if(count == N - 1) begin
count <= 3'd0;
end
else begin
count <= count + 1'b1;
end
end
always @(posedge clk or negedge rstn) begin
if(~</