PWM模块(ax_pwm)端口
`
timescale1ns/1ps
module ax_pwm
#(
parameter N =16//pwm bit width
)
(
input clk,
input rst,
input[N -1:0]period, //pwm step value
input[N -1:0]duty, //duty value
output pwm_out //pwm output
);
reg[N -1:0] period_r; //period register
reg[N -1:0] duty_r; //duty register
reg[N -1:0] period_cnt; //period counter
reg pwm_r;
assign pwm_out = pwm_r;
always@(posedge clk orposedge rst)
begin
if(rst==1)
begin
period_r duty_r end
else
begin
period_r duty_r end
end
//period counter, step is period value
always@(posedge clk orposedge rst)
begin
if(rst==1)
period_cnt else
period_cnt end
always@(posedge clk orposedge rst)
begin
if(rst==1)
begin
pwm_r end
else
begin
if(period_cnt >= duty_r) //if period counter is bigger or equals to duty value, then set pwm value to high
pwm_r else
pwm_r end
end
那么如何实现呼吸灯的效果呢?我们知道呼吸灯效果是由暗不断的变亮,再由亮不断的变暗的过程,而亮暗效果是由占空比来调节的,因此我们主要来控制占空比,也就是控制duty的值。
在下面的测试代码中,通过设置period的值,设定PWM的频率为200Hz,PWM_PLUS状态即是增加duty值,如果增加到最大值,将pwm_flag置1,并开始将duty值减少,待减少到最小的值,则开始增加duty值,不断循环。其中PWM_GAP状态为调整间隔,时间为100us。
`timescale1ns/1ps
module pwm_test(
input clk, //25MHz
input rst_n, //low active
output led //high-off, low-on
);
localparam CLK_FREQ =25; //25MHz
localparam US_COUNT = CLK_FREQ ; //1 us counter
localparam MS_COUNT = CLK_FREQ*1000; //1 ms counter
localparam DUTY_STEP =32'd100000; //duty step
localparam DUTY_MIN_VALUE =32'h6fffffff; //duty minimum value
localparam DUTY_MAX_VALUE =32'hffffffff; //duty maximum value
localparam IDLE =0; //IDLE state
localparam PWM_PLUS =1;//PWM duty plus state
localparam PWM_MINUS =2;//PWM duty minus state
localparam PWM_GAP =3;//PWM duty adjustment gap
wire pwm_out; //pwm output
reg[31:0] period; //pwm step value
reg[31:0] duty; //duty value
reg pwm_flag ; //duty value plus and minus flag, 0: plus; 1: minus
reg[3:0] state;
reg[31:0] timer; //duty adjustment counter
assign led =~pwm_out ;//led low active
always@(posedge clk ornegedge rst_n)
begin
if(rst_n ==1'b0)
begin
period timer duty pwm_flag state end
else
case(state)
IDLE:
begin
period state duty end
PWM_PLUS :
begin
if(duty > DUTY_MAX_VALUE - DUTY_STEP) //if duty is bigger than DUTY MAX VALUE minus DUTY_STEP , begin to minus duty value
begin
pwm_flag duty end
else
begin
pwm_flag duty end
state end
PWM_MINUS :
begin
if(duty begin
pwm_flag duty end
else
begin
pwm_flag duty end
state end
PWM_GAP:
begin
if(timer >= US_COUNT*100)//adjustment gap is 100us
begin
if(pwm_flag)
state else
state
timer end
else
begin
timer end
end
default:
begin
state end
endcase
end
//Instantiate pwm module
ax_pwm
#(
.N(32)
)
ax_pwm_m0(
.clk (clk),
.rst (~rst_n),
.period (period),
.duty (duty),
.pwm_out (pwm_out)
);
endmodule
3. 下载验证
生成bitstream,并下载bit文件,可以看到PL LED1灯产生呼吸灯效果。PWM是比较常用的模块,比如风扇转速控制,电机转速控制等等。