Forum Discussion
Altera_Forum
Honored Contributor
15 years agoI paste my code here. It may be helpful.
// PWM Generation. module PWM_Unit ( duty_ratio,pwm_trig, clk, pwm_output, output_b); input [15:0] duty_ratio; input pwm_trig, clk; output pwm_output, output_b; integer a=0; integer b=-1, ref_level=400; integer pwm_level; integer half_cycle=0; reg pwm_output;//output of pwm reg output_b;//for debug, not related to pwm generation. parameter steps=500; always begin pwm_output<=pwm_level; if (b>0) output_b<=1; else output_b<=0; end //initialize the pwm unit at the beginning of each switching cycle always @(posedge pwm_trig) begin ref_level=100; // read the duty ratio. this is constant for test and will be change in future. end //increase variable a at each clk rising edge always @(posedge clk) begin if (a<ref_level) pwm_level=1; else pwm_level=0; if (pwm_trig==1) //control the slope of the triangle wave. b=-1; if (pwm_trig==1) b=1; a=a+b; if (a<1) begin a=0; end if (a>(steps-1)) begin a=steps; end end endmodule