FPGA:按键
本帖最后由 划句顾 于 2023-2-4 21:29 编辑注意:引脚记得定义哦
如果代码中有注释,那么说明那个是另外一种方法{:10_282:}
一、按键扫描的代码【在正式的案例中被调用】
/*
Time:2022/11/14
author:LaoGu
function:按键扫描函数,给其他的按键函数调用
*/
module key_scan(clk,rst,key_in,flag);
input clk,rst;
input key_in;
output reg flag;
reg cnt;
always@(posedge clk,negedge rst)
if(!rst)
cnt <= 0;
else if(key_in==0&&cnt==100_0000)
cnt <= cnt;
else if(key_in)
cnt <= 0;
else cnt <= cnt + 1;
always@(posedge clk,negedge rst)
if(!rst)
flag <= 0;
else if(cnt==100_0000-1)
flag <= 1;
else
flag <=0;
endmodule
例一:初始时,只有LED0点亮,当KEY1按下LED右移,KEY2按下LED左移。
/*
Time:2022/11/14
author:LaoGu
function:调用按键函数,按下key1,实现灯依次点亮
*/
module key_test(clk,rst,key,led);
input clk,rst;
input key;
output reg led;
reg cnt;
wire flagl;
wire flag2;
//显示例化
key_scan key1(.clk(clk),.rst(rst),.key_in(key),.flag(flag1));
key_scan key2(.clk(clk),.rst(rst),.key_in(key),.flag(flag2));
always@(posedge clk,negedge rst)
if(!rst)
led <= 1;
else if(flag1) begin
/* 法一:
led <= led << 1;
led<= led; */
led<= led; //法二
led<= led;
end
else if(flag2)begin
/* 法一:
led <= led >> 1;
led<= led; */
led<= led; //法二
led<= led;
end
endmodule
例二:实现按键识别,每次按下按键KEY1,LED多点亮一只,如果按下KEY2,LED暗一只。
/*
Time:2022/11/14
author:LaoGu
function:调用按键函数,按下key1,实现灯逐个叠加点亮
*/
module key_work(clk,rst,key,led);
input clk,rst;
input key;
output reg led;
reg cnt;
wire flagl;
wire flag2;
key_scan key1(.clk(clk),.rst(rst),.key_in(key),.flag(flag1));
key_scan key2(.clk(clk),.rst(rst),.key_in(key),.flag(flag2));
always@(posedge clk,negedge rst)
if(!rst)
led <= 1;
else if(flag1) begin
//led = ~led;
//led = led<<1;
//led =~led;
led = led << 1;
led = led + 1;
end
else if(flag2)begin
led = led >> 1;
end
endmodule 本帖最后由 划句顾 于 2023-2-4 21:49 编辑
{:10_256:}大家放心领,前一百个肯定可以领到。我就是来送币的哈哈哈哈 领币 支持楼主{:7_146:} 谢谢分享,已收藏{:10_254:} 我来领币 支持!!!!!!!!!!!! 支持楼主 支(领)持楼主(币) 好 {:10_254:}{:10_254:} 感谢分享~ 领币
学习了 {:10_275:} {:10_275:} {:7_146:} {:5_90:} 好 {:10_257:}