欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FPGA输出五路PWM

程序员文章站 2022-06-08 20:39:02
...

FPGA开发之输出五路PWM波控制舵机

本人在玩FPGA之前玩了很久的单片机,用stm3的计时器和51的IO口模拟PWM都试过,其实原理都一样,通过设置一个累加器和一个阙值,累加器中的数小于阙值时输出低,大于阙值时输出高,累加器加满的时间即为PWM波的周期

  • 使用环境:ISE14.7和BASYS2开发板

1. 输出标准

标准PWM脉宽调制的频率是50Hz,周期20ms,脉冲宽度在0.5ms到2.5ms之间。
我使用的basys2开发板默认晶振频率为50MHz
设置的脉宽精度为0.01ms,即0.01ms判断一次输出高低

2.verilog代码实现

首先,定义一个周期为0.01ms的时钟信号pwm_clk
计算方法为,0.01ms/20ns=500,故count加到250时清零,使pwm_clk每0.005ms翻转一次

reg [19:0] count_for_pwmclk=0;  //pwm_clk的累加器
reg pwm_clk=0;                  //pwm_clk的信号
always @(posedge clk)   //clk是50Mhz的时钟信号
begin

            if(count_for_pwmclk == 20'b0000_0000_0000_1111_1010-1) begin    // 0.01ms触发一次,故pwm波形精度为0.01ms 
            count_for_pwmclk <= 0;
            pwm_clk <= ~pwm_clk;   //按位取反
        end
        else
            count_for_pwmclk <= count_for_pwmclk + 1;
end

定义pwm输出部分,可通过开关等改变pwm_compare的数值(50~250),即可使脉宽在0.5ms到2.5ms之间变化

reg [11:0] count_pwm=0;
reg [11:0] pwm_compare1=12'b0000_1001_0110;  //初值定在150,即1.5ms,是舵机的中位
reg [11:0] pwm_compare2=12'b0000_1001_0110;
reg [11:0] pwm_compare3=12'b0000_1001_0100; 
reg [11:0] pwm_compare4=12'b0000_1001_0110;
reg [11:0] pwm_compare5=12'b0000_1001_0110;
reg pwm_flag1=0;  
reg pwm_flag2=0;
reg pwm_flag3=0;
reg pwm_flag4=0;
reg pwm_flag5=0;
always @(posedge pwm_clk)    //控制五路pwm信号输出
begin
    count_pwm<=count_pwm+1;

    if (count_pwm < pwm_compare1)   //pwm1
        pwm_flag1<=1;
        else
        pwm_flag1<=0;

    if (count_pwm < pwm_compare2)   //pwm2
        pwm_flag2<=1;
        else
        pwm_flag2<=0;

    if (count_pwm < pwm_compare3)   //pwm3
        pwm_flag3<=1;
        else
        pwm_flag3<=0;

    if (count_pwm < pwm_compare4)   //pwm4
        pwm_flag4<=1;
        else
        pwm_flag4<=0;   

    if (count_pwm < pwm_compare5)   //pwm5
        pwm_flag5<=1;
        else
        pwm_flag5<=0;


    if (count_pwm ==12'b0111_1101_0000-1)  //每0.01ms加一次,加2000次即为20ms的周期
    count_pwm<=0;

end


assign pwm_out[0]=pwm_flag1;   //pwm_flag即为对应到输出口的寄存器
assign pwm_out[1]=pwm_flag2;
assign pwm_out[2]=pwm_flag3;
assign pwm_out[3]=pwm_flag4;
assign pwm_out[4]=pwm_flag5;

3.仿真波形

1.pwm_clk的周期为10us,即0.01ms,通过改变pwm_compare 可使脉宽精度以0.01ms变化
FPGA输出五路PWM

pwm输出的波形周期为20ms,50Hz
FPGA输出五路PWM

相关标签: fpga pwm 舵机