FPGA學習過程(一)
阿新 • • 發佈:2021-08-25
前言
終於有時間折騰這塊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) beginif (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