FPGA 按键key

异或符号 ^ 可以用来取反

一级文件

`timescale 1 ns / 1 ps

module key_test(
	clk,
	rst_n,
	key_in,
	led_out
);

parameter led_num = 3;

input clk, rst_n;
input [led_num - 1:0] key_in;
output[led_num - 1:0] led_out;

key #(
	.led_num(led_num)	
)
key_inst(
	.clk(clk),
	.rst_n(rst_n),
	.key_in(key_in),
	.led_out(led_out)
);

endmodule

二级文件

`timescale 1 ns / 1 ps

module key(
	clk,
	rst_n,
	key_in,
	led_out
);

parameter led_num = 4;

input  clk , rst_n;
input  [led_num - 1:0] key_in;
output [led_num - 1:0] led_out;

reg  [7:0] cnt;
reg  [led_num - 1:0]  led_out;
reg  [led_num - 1:0]  key_scan_1;
reg  [led_num - 1:0]  key_scan_2;
wire [led_num - 1:0]  key_flag;

always @(posedge clk or negedge rst_n)
begin
	if(~rst_n)
	begin
		cnt <= 8'd0;
		key_scan_1 <= {led_num{1'b1}};
	end
	else
	begin
		if(key_in != {led_num{1'b1}})
		begin
			if((cnt >= 8'd0) && (cnt < 8'd199))
			begin
				cnt <= cnt + 8'd1;
				key_scan_1 <= key_scan_1;
			end
			else if(cnt == 8'd199)
			begin
				cnt <= 8'd0;
				key_scan_1 <= key_in;
			end
			else
			begin
				cnt <= 8'd0;
				key_scan_1 <= {led_num{1'b1}};
			end
		end
		else
		begin
			cnt <= 8'd0;
			key_scan_1 <= {led_num{1'b1}};
		end
	end	
end 

always @(posedge clk or negedge rst_n)
begin
	if(~rst_n)
		key_scan_2 <= {led_num{1'b1}};
	else
		key_scan_2 <= key_scan_1;
end

assign key_flag = key_scan_2 & (~key_scan_1);

always @(posedge clk or negedge rst_n)
begin
	if(~rst_n)
		led_out <= {led_num{1'b0}};
	else
		led_out <= led_out ^ key_flag;  //当按键按下对应的LED等反转
end

endmodule
上一篇:基于 FPGA 的高级数字电路设计(9)数学形态学设计


下一篇:FPGA神经网络部署 Zynq Ultrascale Yolov3-tiny VGG16