可通过period_div和duty这两个输入信号控制PWM波占空比
module PWM(
input clk,
input rst_n,
input [6:0]duty,
input [12:0]period_div,
output reg pwm
);
//parameter MAX_NUM=24'd500;
reg [23:0]cnt;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)begin
cnt<=1'b0;
end
else if(cnt==period_div-1)begin
cnt<=24'd0;
end
else cnt<=cnt+1'b1;
end
always @(posedge clk or negedge rst_n)begin
if(!rst_n)begin
pwm<=1'b0;
end
else if(cnt<period_div*duty/100)
pwm<=1'b1;
else pwm<=1'b0;
end
endmodule
`timescale 1ns / 1ns
//
// Company:
// Engineer:
//
// Create Date: 2020/05/30 12:06:15
// Design Name:
// Module Name: tb_pwm
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//
module tb_pwm(
);
reg clk;
reg rst_n;
reg [6:0]duty;
wire pwm;
reg [12:0]period_div;
PWM u1(.clk(clk),.rst_n(rst_n),.pwm(pwm),.duty(duty),
.period_div(period_div));
initial begin
clk<=1'b0;
period_div<=13'd5000;
duty<=7'd50;
rst_n<=1'b0;
#20 rst_n<=1'b1;
#100000 period_div<=13'd2000;
#50000 duty<=7'd10;
end
always #5 clk<=~clk;
endmodule