1. 2分频
module div_2(clk,rst,out);
input clk,rst;
output out;
reg q;
always@(posedge clk or negedge rst)
if(!rst)
q<=1'b0;
else
q<=~q;
assign out=q;
endmodule
2. 偶数分频
module div_8 (clk,rst,out);
input clk,rst;
output out;
reg out;
reg [2:0]cnt;
always@(posedge clk or negedge rst)
if(!rst)
begin
out<=1'b0;
cnt<=3'b0;
end
else if(cnt==3'b3) // 3=8/2-1
begin
cnt<=3'b0;
out<=~out;
end
else
cnt<=cnt+1'b1;
endmodule
3. 奇数分频
module div_even (clk,rst,out);
input clk,rst;
output out;
reg out1,out2;
reg [2:0]cnt1;
reg [2:0]cnt2;
always@(posedge clk or negedge rst)
if(!rst)
begin
out1<=1'b0;
cnt1<=3'b0;
end
else if(cnt1==3'b2) //(5-1)/2
out1<=~out1;
else if(cnt1==3'b4) //5-1
begin
cnt1<=3'b0;
out1<=~out1;
end
else
cnt1<=cnt1+1'b1;
always@(negedge clk or negedge rst)
if(!rst)
begin
out2<=1'b0;
cnt2<=3'b0;
end
else if(cnt2==3'b2) //(5-1)/2
out2<=~out2;
else if(cnt2==3'b4)
begin
cnt2<=3'b0;
out2<=~out2;
end
else
cnt2<=cnt2+1'b1;
assign out=out1|out2;
endmodule
4. PWM(频率,占空比可调)
module pwm (clk,rst,f,p,out);
input clk,rst;
input [7:0] f,p;
output out;
reg out;
reg [7:0]cnt;
always@(posedge clk or negedge rst)
if(!rst)
begin
cnt<=8'b0;
end
else if(cnt>=8'd200)//根据f增量大小,注意溢出
begin
cnt<=8'b0;
end
else
cnt<=cnt+f;
assgin out=(cnt>p)?1:0;
endmodule