文章目录
- 一、实验任务
- 二、系统框图
- 三、代码实现
- 四、引脚分配
- 五、总结
一、实验任务
使用开发板上的四个按键控制四个LED灯。按下不同的按键时,四个LED灯显示不同效果。本实验是在EP4CE6F17C8开发板上实现,仿真请用modelsim Altera
二、系统框图
三、代码实现
module key_led (input clk, //时钟周期input rst_n, //复位信号input [3:0] key , //4个按键,提供4个位宽output reg [3:0] key_led //4个led灯,提供4个位宽
);
reg [1:0] state; //两位宽的状态寄存器,存储4个状态
reg [25:0] cnt_1s; //存储1s的寄存器parameter MAX_1s = 26'd49_999_999;//1s的时钟周期//1s计数器
always @(negedge rst_n or posedge clk) beginif (!rst_n) begincnt_1s <= 26'd0;endelse if (cnt_1s == MAX_1s) begincnt_1s <= 26'd0;endelse begincnt_1s <= cnt_1s + 26'd1;end
end//状态每隔1s进行跳转
always @(negedge rst_n or posedge clk) beginif (!rst_n) beginstate <= 2'd0;endelse if (cnt_1s == MAX_1s) begin //每隔1s进入下一个状态state <= state + 2'd1;endelse beginstate <= state;end
end//不同按键不同led灯闪烁方式
always @(negedge rst_n or posedge clk) beginif (!rst_n) beginkey_led <= 4'b0000;endelse if (key[0] == 0) begin //key0键按下,从右往左流水灯case (state)2'd0: key_led <= 4'b0001;2'd1: key_led <= 4'b0010;2'd2: key_led <= 4'b0100;2'd3: key_led <= 4'b1000;default: key_led <= key_led ;endcaseendelse if (key[1] == 0) begin //key1键按下,从左往右流水灯case (state)2'd0: key_led <= 4'b1000;2'd1: key_led <= 4'b0100;2'd2: key_led <= 4'b0010;2'd3: key_led <= 4'b0001;default: key_led <= key_led ;endcaseendelse if (key[2] == 0) begin //key2键按下,led灯闪烁case (state)2'd0: key_led <= 4'b1111;2'd1: key_led <= 4'b0000;2'd2: key_led <= 4'b1111;2'd3: key_led <= 4'b0000;default: key_led <= key_led ;endcaseendelse if (key[3] == 0) begin //key3键按下,灯常亮case (state)2'd0: key_led <= 4'b1111;2'd1: key_led <= 4'b1111;2'd2: key_led <= 4'b1111;2'd3: key_led <= 4'b1111;default: key_led <= key_led ;endcaseendelse beginstate <= state;end
endendmodule
仿真代码:
`timescale 1ns/1ns
module key_led_tb (
);reg clk;reg rst_n;reg [3:0] key;wire [3:0] key_led;parameter MAX_1s = 9;parameter CYCLE = 20;always #(CYCLE/2) clk <= ~clk;initial beginclk = 1'b0;rst_n = 1'b0;#(CYCLE);rst_n = 1'b1;key = 4'b1111;#(4*(MAX_1s + 1)*CYCLE); //4个state的时间key = 4'b1110;#(4*(MAX_1s + 1)*CYCLE); key = 4'b1101;#(4*(MAX_1s + 1)*CYCLE); key = 4'b1011;#(4*(MAX_1s + 1)*CYCLE); key = 4'b0111;$stop;endkey_led #(.MAX_1s(MAX_1s))u_key_led(.clk(clk),.rst_n(rst_n),.key(key),.key_led(key_led));endmodule
四、引脚分配
五、总结
注意:该实验并未进行按键消抖,需一直按着按键才能让该按键所操控的led变化功能实现。