Prev Problem
Next Problem

30. PWM with 4-bit Resolution

module pwm4_basic(
  input  wire       clk,
  input  wire       rst,
  input  wire [3:0] duty,
  output reg        pwm_out
);
  reg [3:0] cnt;
  always @(posedge clk) begin
    pwm_out <= rst ? 1'b0 : (cnt < duty);
    cnt     <= rst ? 4'd0 : (cnt + 4'd1);
  end
endmodule

💡 Remember

  • A 4-bit free-running counter defines a 16-clock frame; pwm_out is high exactly when cnt < duty.
  • duty=0 gives 0%, duty=8 gives 50%, duty=15 gives 15/16 ≈ 93.75%.
  • Registering both the counter and compare makes a clean, edge-aligned waveform.
  • Reset realigns the frame to start at cnt=0.