设计一个4位串行数字密码锁,要求如下:开锁密码为4位二进制,当输入密码与锁内给定的密码一致时,方可开锁。否则进入“错误”状态,发出报警信号。锁内的密码可调。串行数字密码锁的报警,直到按下复位开关,才停下。此时,数字密码锁又自动等待下一个开锁状态。
b1~b4 密码输入
alter_key更改密码标志位
alarm密码出错报警
ok确认键
open已开锁标志位
主模块代码:
module codedlock(reset,b1,b2,b3,b4,alarm,alter_key,open,ok);
input reset,b1,b2,b3,b4,alter_key,ok;
output alarm,open;
reg[1:0] alarm=0;
reg[1:0] open=0;
reg[4:0] key=4'b1111;
reg[4:0] code;
//Enter password and convert from serial to parallel
always @(ok,reset,b1,b1,b3,b4)
begin
if(reset)
begin
code<=b1*8+b2*4+b3*2+b4;
end
else
begin
alarm<=0;
open<=0;
end
end
///
always @(code,ok)
begin
if(ok==1)
begin
if(code==key)
begin
open<=1;
alarm<=0;
end
else
begin
open<=0;
alarm<=1;
end
end
end
///Modify password
always @(alter_key,ok)
begin
if(alter_key)
begin
if(reset)
begin
if(open)
begin
if(ok)
begin
key<=b1*8+b2*4+b3*2+b4;
end
end
end
end
end
//
endmodule
测试模块代码:
module codedlock_test;
reg reset;
reg b1,b2,b3,b4;
reg alter_key,ok;
wire[1:0] alarm;
wire[1:0] open;
codedlock u(.reset(reset),.b1(b1),.b2(b2),.b3(b3),.b4(b4),.alarm(alarm),.alter_key(alter_key),.open(open),.ok(ok));
initial
begin
reset=0;b1=0;b2=0;b3=0;b4=0;alter_key=0;ok=0;
//错误密码测试
#20 reset=1;
#20 b1=1;b2=1;b3=1;b4=0;ok=1;//1110
#20 ok=0;
#20 reset=0;
///正确密码开锁|更改密码
#100 reset=1;
#20 b1=1;b2=1;b3=1;b4=1;ok=1;//1111
#20 ok=0;
#100 alter_key=1;
#20 b1=1;b2=0;b3=1;b4=0;ok=1;//1010新密码
#20 ok=0;
#20 alter_key=0;
#20 reset=0;
//错误密码测试
#100 reset=1;
#20 b1=1;b2=0;b3=0;b4=0;ok=1;//1001
#20 ok=0;
#20 reset=0;
//新密码开锁测试
#100 reset=1;
#20 b1=1;b2=0;b3=1;b4=0;ok=1;//1010
#20 ok=0;
#20 reset=0;