Prev Problem
Next Problem

30. PWM with 4-bit Resolution

Back To All Submissions
Previous Submission
Next Submission

Solving Approach

How do you plan to solve it?

Implement a 4-bit synchronous PWM by driving a free-running 4-bit counter that cycles from 0 to 15.
On each rising edge of clk, the counter increments and wraps naturally.
When rst is high at a rising edge, both the counter and the output are synchronously cleared.
At every clock edge, generate the PWM level by comparing the current counter value to duty:
pwm_out is high only while cnt < duty, giving a high interval of duty counts within each 16-cycle frame.

Code

/*Write your code here*/
module pwm4_basic(
    input        clk,
    input        rst,
    input  [3:0] duty,
    output reg   pwm_out
);

    reg [3:0] cnt;

    always @(posedge clk) begin
        if (rst) begin
            {cnt,pwm_out} <= {4'd0,1'b0};
        end else begin
            cnt <= cnt + 4'd1;       
            pwm_out <= (cnt < duty); 
        end
    end
endmodule

 

Was this helpful?
Upvote
Downvote