【iCore1S 双核心板_FPGA】例程六:状态机实验——状态机使用
核心代码:
module FSM( input CLK_12M, input FPGA_KEY, output FPGA_LEDR, output FPGA_LEDG, output FPGA_LEDB ); //----------------------state--------------------// parameter state_RST = 3'd0; //灯熄灭 parameter state_LEDR = 3'd1; //红灯亮 parameter state_LEDG = 3'd2; //绿灯亮 parameter state_LEDB = 3'd3; //蓝灯亮 parameter state_LED_R_G_B = 3'd4; //灯都亮(接近白光) //----------------------rst_n--------------------// reg rst_n; reg [3:0]cnt_rst; always@(posedge CLK_12M) if(cnt_rst==4'd10) begin cnt_rst <= 4'd10; rst_n = 1'd1; end else cnt_rst <= cnt_rst + 1'd1; //-------------------key in---------------------// reg key; reg [17:0]low_cnt; reg [17:0]hig_cnt; parameter ms_10 =120000; always@(posedge CLK_12M or negedge rst_n) begin if(!rst_n) begin key <= 1'd1; low_cnt <= 18'd0; hig_cnt <= 18'd0; end else if(FPGA_KEY) //检测按键状态为高时,延时10ms,把按键状态提取出来。 begin low_cnt <= 18'd0; if(hig_cnt==ms_10) begin key <= FPGA_KEY; hig_cnt <= hig_cnt; end else hig_cnt <= hig_cnt + 1'd1; end else ////按键状态为低时,延时10ms,把按键状态提取出来。 begin hig_cnt <= 18'd0; if(low_cnt==ms_10) begin key <= FPGA_KEY; low_cnt <= low_cnt; end else low_cnt <= low_cnt +1'd1; end end //----------------led_state------------------// reg [2:0]led_state; //key的下降沿,即按键按下后,进行状态转换 always@(negedge key or negedge rst_n) begin if(!rst_n) begin led_state <= 3'd0; end else begin led_state <= led_state + 1'd1; if (led_state == 3'd4) begin led_state <= 3'd0; end end end //------------------led---------------------// reg ledr,ledg,ledb; always@(posedge CLK_12M or negedge rst_n) begin if(!rst_n) begin ledr <= 1'd1; ledg <= 1'd1; ledb <= 1'd1; end else case(led_state) state_RST: //灯熄灭 begin ledr <= 1'd1; ledg <= 1'd1; ledb <= 1'd1; end state_LEDR: //红灯亮 begin ledr <= 1'd0; ledg <= 1'd1; ledb <= 1'd1; end state_LEDG: //绿灯亮 begin ledr <= 1'd1; ledg <= 1'd0; ledb <= 1'd1; end state_LEDB: //蓝灯亮 begin ledr <= 1'd1; ledg <= 1'd1; ledb <= 1'd0; end state_LED_R_G_B: //灯交替亮 begin ledr <= 1'd0; ledg <= 1'd0; ledb <= 1'd0; end default: //都不亮 begin ledr <= 1'd1; ledg <= 1'd1; ledb <= 1'd1; end endcase end assign FPGA_LEDR = ledr; assign FPGA_LEDG = ledg; assign FPGA_LEDB = ledb; //-----------------endmodule-----------------// endmodule
实验方法及指导书:
链接:http://pan.baidu.com/s/1o8skJCe 密码:var9