无按键按下时, 全灭;
按键1按下时, 自右向左的流水效果;
按键2按下时, 自左向右的流水效果;
按键3按下时,闪烁;
按键4按下时, 全亮;
//***********Copyright (c)************//
//-------------------------------------
// File name: my_key_led
// Last modified Date: 2020/6/10 22:30
// Last Version: V1.1
// Descriptions: 按键控制LED
// 无按键 全灭
// key0 右-左流水灯
// key1 左-右流水灯
// key2 全闪烁
// key3 全亮
//-------------------------------------
// LED流水灯引脚分配,高电平点亮
// LED0 D11
// LED1 C11
// LED2 E10
// LED3 F9
// sys_clk E1
// sys_rst_n M1
// key0 E16
// key1 E15
// key2 M2
// key3 M16
//-------------------------------------
//*************************************//
module my_key_led
(
input sys_clk, //系统时钟50MHZ
input sys_rst_n, //复位,低电平有效
input [3:0] key, //4个key
output reg [3:0] led //4个LED灯
);
//reg define
reg [23:0] counter ; //定时200ms,需要24位。
reg [1:0] led_ctrl ; //led_ctrl led控制
//计数器对系统时钟计数,计时0.2秒。0.2s/20ns=1000_0000(d)
always @(posedge sys_clk or negedge sys_rst_n) //时钟上升沿,复位下降沿
begin
if (!sys_rst_n) //如果复位
counter <=24'd0; //计数器清0,重新开始计时
else //if嵌套
if (counter<24'd1000_0000) //没有计时到0.2s
counter<=counter+1'b1; //计数器加1
else
counter<=24'd0; //到0.2s,计数器清0
end
//状态计数器[1;0] 两位二进制,用于选择led灯四个状态
always @(posedge sys_clk or negedge sys_rst_n)
begin
if(!sys_rst_n)
led_ctrl<=2'd0;
else
if(counter==24'd1000_0000)
led_ctrl<=led_ctrl+1'b1;
else
led_ctrl<=led_ctrl;
end
//按键改变LED状态
always @(posedge sys_clk or negedge sys_rst_n)
begin
if(!sys_rst_n)
led<=4'b0000;
else
if(key[0]==1'b0) //右-左流水灯
case(led_ctrl)
2'd0: led<=4'b1000;
2'd1: led<=4'b0100;
2'd2: led<=4'b0010;
2'd3: led<=4'b0001;
endcase
else if(key[1]==1'b0) //左-右流水灯
case(led_ctrl)
2'd0: led<=4'b0001;
2'd1: led<=4'b0010;
2'd2: led<=4'b0100;
2'd3: led<=4'b1000;
endcase
else if(key[2]==1'b0) //全闪烁
case(led_ctrl)
2'd0: led<=4'b0000;
2'd1: led<=4'b1111;
2'd2: led<=4'b0000;
2'd3: led<=4'b1111;
endcase
else if(key[3]==1'b0) //全亮
led<=4'b1111;
else
led<=4'b0000; //无按键按下时, LED熄灭
end
endmodule