Pulse Width Generator Model
PWM.v
module pwm(clk_in,sw0,rst,sine_ampl,div_factor_freqhigh,div_factor_freqlow,pwm_out);
parameter width_p = 10'd12;
input clk_in;
input rst;
input sw0;
input [width_p-1:0] sine_ampl;
input [31:0] div_factor_freqhigh;
input [31:0] div_factor_freqlow;
output reg pwm_out;
parameter load_new_ampl = 3'd0;
parameter pwm_high = 3'd1;
parameter pwm_low = 3'd2;
wire ce_w;
reg [2:0]state_r;
reg [2:0]n_state;
reg [12:0]treshold_r =20'd0;
reg [12:0]count_r = 20'd0;
frequency_trigger freq_ce (clk_in, sw0, div_factor_freqhigh, div_factor_freqlow, ce_w);
always @ (posedge clk_in or posedge rst)
begin
if(rst)
state_r<=load_new_ampl;
else
state_r 0)
n_state <= pwm_high;
else if (sine_ampl == 0)
n_state <= pwm_low;
end
pwm_high:
begin
count_r = count_r + 1;
if ((count_r <((2**width_p)-1)) && (count_r < treshold_r))
n_state <= pwm_high;
else if (count_r == (2**width_p)-1)
n_state <= load_new_ampl;
else if (count_r < ((2**width_p)-1) && (count_r == treshold_r))
n_state <= pwm_low;
end
pwm_low:
begin
count_r = count_r +1;
if (count_r < ((2**width_p)-1))
n_state <= pwm_low;
else if (count_r == ((2**width_p)-1))
n_state <= load_new_ampl;
end
endcase
end
always @(posedge clk_in)
begin
case (state_r)
load_new_ampl: pwm_out = 0;
pwm_high: pwm_out = 1;
pwm_low: pwm_out = 0;
endcase
end
endmodule
===================================
frequency_trigger.v
frequency_trigger(clk_in,sw0,div_factor_freqhigh,div_factor_freqlow,freq_trig);
input clk_in;
input sw0;
input [31:0] div_factor_freqhigh;
input [31:0] div_factor_freqlow;
output reg freq_trig;
integer freq_cnt=12'd0;
always @(posedge clk_in)
begin
freq_trig = 1'b0;
freq_cnt = freq_cnt + 1;
if (sw0 == 0)
begin
if (freq_cnt >= div_factor_freqlow -1)
begin
freq_trig = 1'b1;
freq_cnt = 'd0; //reset
end
end
else
begin
if (freq_cnt >= div_factor_freqhigh - 1)
begin
freq_trig = 1'b1;
freq_cnt = 'd0; //reset
end
end
end
endmodule
==============================
Finally we need test bench to run the simultions and check the functionality of the designpwm_testbench.v
module pwm1_tb();
parameter cntampl_value_p = 8'hff;
parameter depth_p = 8'd8;
parameter width_p = 10'd12;
reg clk_in_r;
reg rst_r;
reg sw0_r;
reg [(width_p-1):0] sine_out_w;
wire pwm_out_w;
pwm dut2 (clk_in_r, sw0_r,rst_r,sine_out_w, 1, 2, pwm_out_w);
initial
begin
rst_r=1'b1;
clk_in_r = 1'b1;
end
always #10 clk_in_r = ~clk_in_r;
initial
begin
#50000 rst_r=1'b0;
sw0_r = 1'b0;
sine_out_w=3000;
#163860 sine_out_w=4220;
#163860 sine_out_w=2376;
#163860 sine_out_w=5856;
#163860 sine_out_w=1237;
#163860 sine_out_w=5856;
#163860 sine_out_w=5984;
#163860 sine_out_w=5598;
#163860 sine_out_w=4763;
#163860 sine_out_w=3624;
#163860 sine_out_w=2376;
#163860 sine_out_w=1237;
#163860 sine_out_w=402;
#163860 sine_out_w=16;
#163860 sine_out_w=147;
#163860 sine_out_w=771;
#163860 sine_out_w=1780;
#163860 sine_out_w=3000;
end
initial
#200000000 $finish;
endmodule
================================