FPGA学习过程(一)


前言

  终于有时间折腾这块fpga开发板了,不知不觉又熬夜了。

正文

  实现一个呼吸灯的项目

  打开quartus ii 建立工程 步骤就不讲了

  新建一个pwm.v文件内容

module PWM ( 

    input sys_clk,      
    input sys_rst_n,   
    input [WIDTH-1:0] duty_cycle,
     
    //output ports
    output wire pwm
 
);
 
//reg define 
 
reg pwm_out;
reg [19:0] counter; // 最大值 1048575,PWM频率最低可以设置到 48HZ
 
//parameter define 
parameter WIDTH = 7;
 
/*
设PWM频率为 f,晶振频率为F
则计数器的最大值为 counter_max = (1/f)/(1/F) = F/f = 50M / 2K = 25*10^3
*/
parameter PWM_FREQUENCY = 2_000; //2K
parameter OSC_FREQUENCY = 50_000_000; //50M
parameter COUNTER_MAX = OSC_FREQUENCY/PWM_FREQUENCY;
 
// 主程序
always @(posedge sys_clk or negedge sys_rst_n) begin 
        if (sys_rst_n ==1'b0)
            counter <= 20'b0;
        else if (counter>=COUNTER_MAX)
            counter <= 20'b0;
        else 
            counter  <= counter + 20'b1;
end
 
always @(posedge sys_clk or negedge sys_rst_n) begin 
        if (sys_rst_n ==1'b0) begin 
            pwm_out <= 1'b0;
        end
        else if (counter <= COUNTER_MAX*duty_cycle/100)  
            pwm_out  <= 1'b1;
        else 
            pwm_out  <= 1'b0;
end
 
 
assign pwm = !pwm_out;
 
endmodule     

   建立LED.V设为顶层文件

module LED
(
    input  wire                 clk                 ,
    input  wire                  rst_n               ,
    output wire                   led
);

wire [6:0] dyc;

reg [6:0] dyc_value;
reg [25:0] cnt;
reg state;

initial dyc_value = 0;
initial state = 0;

parameter delay_ms = 50_000 * 10;

always @(posedge clk or negedge rst_n)begin
        if(! rst_n)begin
            cnt <= 0;
            dyc_value <= 0;
            state <= 0;
        end
        
        else begin
        
            if(cnt == delay_ms  -1)begin
                cnt <= 0;
                if(state == 0)
                    dyc_value <= dyc_value + 1;
                else
                    dyc_value <= dyc_value - 1;
            end
            
            else begin
                cnt <= cnt + 1;
            end
                
            if(dyc_value == 100)
                state <= 1;
            else if(dyc_value == 0)
                state <= 0;                            
        end
end

assign dyc = dyc_value;

PWM U_PWM(
    .sys_clk(clk),
    .sys_rst_n(rst_n),
    .duty_cycle(dyc),
    .pwm(led)
);

endmodule