文章目录
- 一、实验任务
- 二、系统框图
- 三、代码实现
- 四、引脚分配
- 五、总结
一、实验任务
使用开发板上的四个按键控制四个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) begin
if (!rst_n) begin
cnt_1s <= 26'd0;
end
else if (cnt_1s == MAX_1s) begin
cnt_1s <= 26'd0;
end
else begin
cnt_1s <= cnt_1s + 26'd1;
end
end
//状态每隔1s进行跳转
always @(negedge rst_n or posedge clk) begin
if (!rst_n) begin
state <= 2'd0;
end
else if (cnt_1s == MAX_1s) begin //每隔1s进入下一个状态
state <= state + 2'd1;
end
else begin
state <= state;
end
end
//不同按键不同led灯闪烁方式
always @(negedge rst_n or posedge clk) begin
if (!rst_n) begin
key_led <= 4'b0000;
end
else 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 ;
endcase
end
else 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 ;
endcase
end
else 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 ;
endcase
end
else 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 ;
endcase
end
else begin
state <= state;
end
end
endmodule
仿真代码:
`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 begin
clk = 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;
end
key_led #(.MAX_1s(MAX_1s))u_key_led(
.clk(clk),
.rst_n(rst_n),
.key(key),
.key_led(key_led)
);
endmodule
四、引脚分配
五、总结
注意:该实验并未进行按键消抖,需一直按着按键才能让该按键所操控的led变化功能实现。