Verilog Code Example for Generating PWM Signal with Adjustable Duty Cycle

Answered using ChatGPT 4o by ChatGPT4o

Question:

can u write a verilog code for generating pwm signal

Answer:

Certainly! Below is an example of a Verilog code to generate a PWM (Pulse Width Modulation) signal. This example assumes a simple PWM generator where the duty cycle can be adjusted via an input signal.

module pwm_generator (
    input wire clk,          // System clock
    input wire reset,        // Asynchronous reset
    input wire [7:0] duty,   // Duty cycle (0-255)
    output reg pwm_out       // PWM output
);

    reg [7:0] counter;       // 8-bit counter

    always @(posedge clk or posedge reset) begin
        if (reset) begin
            counter <= 8'b0;
            pwm_out <= 1'b0;
        end else begin
            if (counter < duty) begin
                pwm_out <= 1'b1;
            end else begin
                pwm_out <= 1'b0;
            end

            counter <= counter + 1'b1;
        end
    end

endmodule

Explanation:

  1. Inputs and Outputs:

    • clk: The system clock signal.
    • reset: An asynchronous reset signal to initialize the counter and PWM output.
    • duty: An 8-bit input representing the duty cycle (0-255).
    • pwm_out: The PWM output signal.
  2. Counter:

    • An 8-bit counter is used to generate the PWM signal. The counter increments on each clock cycle.
  3. PWM Generation:

    • On each clock cycle, the counter is compared to the duty cycle value.
    • If the counter value is less than the duty cycle, the pwm_out signal is set to high (1).
    • If the counter value is greater than or equal to the duty cycle, the pwm_out signal is set to low (0).
  4. Reset:

    • When the reset signal is high, the counter and pwm_out are reset to 0.

Usage:

  • The duty cycle can be adjusted by changing the value of the duty input.
  • For example, if duty is set to 128, the PWM signal will have a 50% duty cycle (since 128 is half of 255).

This is a basic example and can be extended or modified based on specific requirements, such as different counter widths, different clock frequencies, or additional features like phase control.