You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Verilog(Quartus Prime Lite)中生成PWM信号遇异常

PWM信号占空比不符合预期问题排查

尝试用Verilog实现PWM信号,通过duty参数控制输出占空比,但仿真结果未得到对应比例的PWM波形,以下是相关代码、测试平台及仿真输出,排查问题原因如下:

Verilog实现代码

module pwm_generator (
    input wire clk,          // Clock input
    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) begin
    if (counter < duty) 
        pwm_out <= 1; // Set output high
    else 
        pwm_out <= 0; // Set output low

    counter <= counter + 1; // Increment counter
end

endmodule

测试平台代码

module pwm_generator_tb;

reg clk;
reg [7:0] duty;
wire pwm_out;

// Instantiate the PWM generator
pwm_generator uut (
    .clk(clk),
    .duty(duty),
    .pwm_out(pwm_out)
);

// Clock generation
initial begin
    clk = 0;
    forever #5 clk = ~clk; // 10 time units clock period
end

// Test cases
initial begin
    duty = 8'h128; // 50% duty cycle
    #100; // Wait for 100 time units

    duty = 8'd64; // 25% duty cycle
    #100;

    duty = 8'd192; // 75% duty cycle
    #100;

    $stop; // Stop the simulation
end

endmodule

Modelsim仿真输出

Modelsim仿真输出

问题原因分析

  1. 计数器未初始化:代码中counter寄存器没有初始值,仿真时会处于未知态(x),导致counter < duty的比较结果不确定,输出波形混乱。
  2. 测试时间过短:8位计数器的完整周期是256个时钟周期,对应2560时间单位(时钟周期10时间单位),但测试平台每个测试点仅等待100时间单位,不足以观察完整的PWM周期,无法验证占空比是否正确。
  3. 占空比参数赋值错误:测试平台中duty = 8'h128超出8位数据范围(8位最大值为8'hFF=255),会导致数值溢出,实际赋值为错误的8'h28(十进制40),根本不是预期的50%占空比。

修复方案

  1. 初始化计数器:添加复位逻辑或仿真初始赋值,确保计数器从0开始计数。例如修改计数器逻辑:
always @(posedge clk) begin
    if (counter == 8'd255)
        counter <= 8'd0;
    else
        counter <= counter + 1;

    pwm_out <= (counter < duty) ? 1'b1 : 1'b0;
end

或者在仿真时添加initial赋值:

initial begin
    counter = 8'd0;
end
  1. 延长测试时间:将测试平台中的#100修改为#3000,确保每个测试点能覆盖至少一个完整的PWM周期。
  2. 修正占空比参数:将8'h128改为8'h80(十进制128,对应50%占空比),避免数值溢出。

内容的提问来源于stack exchange,提问作者Subzee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 02:50:13