1.用verilog实现PWM控制呼吸灯。呼吸周期2秒:1秒逐渐变亮,1秒逐渐变暗。系统时钟24MHz,pwm周期1ms,精度1us。
====
```verilog
`timescale 1ns/1ps
module pwm(
input Sys_clk,//24Mhz, 42ns
input Sys_reset,
output Pwm_o//T=1ms/1us
);
parameter T1ns = 5'd24;
parameter T1000us = 10'd1000;
reg [9:0] cnt_us;
reg [4:0] cnt_ns;
reg iscount;
//****************************************
always @ (posedge Sys_clk or negedge Sys_reset)
if(!Sys_reset)
cnt_ns <= 5'd0;
else if(iscount & cnt_ns == T1ns)
cnt_ns <= 5'd0;
else if(!iscount) cnt_ns <= 5'd0;
else
cnt_ns<= cnt_ns+1'b1;
//******************************************
always @ (posedge Sys_clk , negedge Sys_reset)
if(!Sys_reset)
begin
cnt_us <= 9'd0;
end
else if(iscount & cnt_ns ==T1ns)
cnt_us <= cnt_us + 1'b1;
else if(cnt_us == T1000us)
begin
cnt_us <= 9'd0;
end
else if(!iscount)
cnt_us <= 9'd0;
//********************************8
//T1000
reg [9:0] T1000;
reg [9:0] step;
always @ (posedge Sys_clk , negedge Sys_reset)
if(!Sys_reset)
begin
T1000 <= 10'd0;
step <= 10'd0;
end
else if(iscount & cnt_us == T1000us )
begin
step <= step+ 10'd100;
T1000<= T1000+1'b1;
end
else if(T1000 == 10'd1000)
begin
T1000 <= 10'd0;
end
else if(step == 10'd1000) step <= 10'd0;
else if(!iscount)
T1000<= 10'd0;
//*****************************
reg pwm_r;
reg [1:0] i;
always @ (posedge Sys_clk , negedge Sys_reset)
if(!Sys_reset)
begin
iscount <= 1'b0;
pwm_r <= 1'b1;
i <= 2'd0;
end
else case(i)
2'd0:
begin
iscount <= 1'b1;
i <= i + 1'b1;
end
2'd1:
begin
if(cnt_us == (T1000us-step) | (cnt_us == T1000us))
pwm_r <= ~pwm_r;
if(T1000==T1000us)
begin
i <= i +1'b1;
pwm_r <= 1'b0;
end
end
2'd2:
begin
if(cnt_us == (T1000us-step) | ( cnt_us == T1000us))
pwm_r <= ~pwm_r;
if(T1000==T1000us)
begin
i <= 1'b0;
pwm_r <= 1'b1;
iscount <= 1'b0;
end
end
default: iscount <= 1'b0;
endcase
assign Pwm_o =pwm_r;
endmodule
```

本文介绍了使用Verilog实现PWM控制呼吸灯的过程。系统时钟为24MHz,呼吸周期为2秒,其中1秒逐渐变亮,1秒逐渐变暗,PWM周期设定为1ms,精度达到1us。
1106

被折叠的 条评论
为什么被折叠?



