Prev Problem
Next Problem

30. PWM with 4-bit Resolution

Back To All Submissions
Previous Submission
Next Submission

Solving Approach

When reset is high, it resets the internal counter cnt and the output pwm_out to 0. When its low, meaning the module is running ,we check if cnt has completed its 16 bit cycle. If yes, cnt and pwm_out are reset to 0. Else, while cnt is lesser than duty, cnt is incremented and pwm_out is high.

 

 

Code

/*Write your code here*/
module pwm4_basic (
    input clk,
    input rst,
    input [3:0] duty,
    output reg pwm_out
);
    reg [3:0] cnt;
    // assign wire cnt = 0;
    always @(posedge clk) begin
        if (rst) begin
            cnt <= 4'b0000;
            pwm_out <= 0;
        end else begin
            if (cnt<4'b1111) begin
                pwm_out <= (cnt<duty)?1:0;
                cnt <= cnt + 4'b0001;
            end else begin
                pwm_out <= 0;
                cnt <= 4'b0000;
            end
        end
    end 
endmodule

 

Was this helpful?
Upvote
Downvote