LIBRARY IEEE; 
USE IEEE.STD_LOGIC_1164.ALL; 
USE IEEE.STD_LOGIC_ARITH.ALL;
USE IEEE.STD_LOGIC_UNSIGNED.ALL; 
ENTITY CTRL IS
PORT (DATA_N: IN STD_LOGIC_VECTOR(3 DOWNTO 0); 
 DATA_F: IN STD_LOGIC_VECTOR(3 DOWNTO 0); 
 FLAG_N: IN STD_LOGIC; 
 FLAG_F: IN STD_LOGIC; 
 CLK: IN STD_LOGIC; 
 ENLOCK: OUT STD_LOGIC; --1: LOCK, 0: UNLOCK
 DATA_BCD: OUT STD_LOGIC_VECTOR (15 DOWNTO 0));
END ENTITY CTRL ; 
ARCHITECTURE ART OF CTRL IS
 SIGNAL ACC, REG: STD_LOGIC_VECTOR (15 DOWNTO 0); 
 --ACC 用于暂存键盘输入的信息，REG 用于存储输入的密码
 SIGNAL NC: STD_LOGIC_VECTOR (2 DOWNTO 0); 
 SIGNAL RR2, CLR, BB, QA, QB: STD_LOGIC; 
 SIGNAL R1, R0: STD_LOGIC; 
 BEGIN
 --寄存器清零信号的产生进程
PROCESS(CLK)
 BEGIN
 IF CLK'EVENT AND CLK='1' THEN
 R1<=R0; R0<=FLAG_F; 
 END IF; 
 RR2<=R1 AND NOT R0; 
 CLR<=RR2; 
 END PROCESS; 
--按键输入数据的存储、清零进程
 KEYIN_PROCESS : BLOCK IS
 SIGNAL RST, D0, D1: STD_LOGIC ; 
 BEGIN 
 RST <= RR2; 
 PROCESS(FLAG_N, RST) IS
 BEGIN
IF RST = '1' THEN 
 ACC <= "0000000000000000" ; --CLEAR INPUT
 NC <= "000" ; 
ELSE
 IF FLAG_N'EVENT AND FLAG_N = '1' THEN 
 IF NC < 4 THEN
 ACC <= ACC(11 DOWNTO 0) & DATA_N ; 
 NC <= NC + 1 ; 
 END IF; 
 END IF ; 
 END IF ; 
END PROCESS ; 
 END BLOCK KEYIN_PROCESS ; 
--上锁/开锁控制进程
 LOCK_PROCESS : BLOCK IS
 BEGIN
PROCESS(CLK, DATA_F) IS
 BEGIN
 IF (CLK'EVENT AND CLK = '1') THEN
IF NC = 4 THEN
 IF DATA_F(2) = '1' THEN 
 --上锁控制信号有效
REG <= ACC ; --密码存储
QA <= '1' ; QB <= '0'; 
 ELSIF DATA_F(0) = '1' THEN --开锁控制信号有效
IF REG = ACC THEN --密码核对
 QA<= '0'; QB <= '1' ; 
END IF ; 
 ELSIF ACC = "1000100010001000" THEN 
 --设置“8888”为万用密码
QA <= '0' ; QB<= '1';
END IF ; 
END IF; 
 END IF ; 
END PROCESS ; 
 END BLOCK LOCK_PROCESS ; 
 --输出上锁/开锁控制信号
 ENLOCK <= QA AND NOT QB ; 
 --输出显示信息
 DATA_BCD<= ACC ; 
END ARCHITECTURE ART;