module dac_test(clock,key,wr_act,wr_data,seg,dig);
input clock; //系统时钟(48MHz)
input[4:0] key; //按键输入(KEY1~KEY5)
output wr_act; //发送数据使能
output[10:0]wr_data; //要发送的数据
output[7:0]seg; //数码管段码输出
output[7:0]dig; //数码管位码输出
//I/O寄存器
reg[10:0]wr_data;
reg wr_act;
reg[7:0]seg;
reg[7:0]dig;
//内部寄存器
reg[16:0]count; //时钟分频计数器
reg[4:0]dout1,dout2,dout3; //消抖寄存器
reg[4:0]buff; //边沿检测寄存器
reg[1:0] cnt; //数码管扫描计数器
reg[3:0]disp_dat; //数码管扫描显存
reg div_clk; //分频时钟
wire[4:0] key_edge;
//时钟分频部分
always @(posedge clock)
begin
if (count < 17'd120000)
begin
count <= count + 1'b1;
div_clk <= 1'b0;
end
else
begin
count <= 17'd0;
div_clk <= 1'b1;
end
end
//按键消抖部分
always @(posedge clock)
begin
if(div_clk)
begin
dout1 <= key;
dout2 <= dout1;
dout3 <= dout2;
end
end
//按键边沿检测部分
always @(posedge clock)
begin
buff <= dout1 | dout2 | dout3;
end
assign key_edge = ~(dout1 | dout2 | dout3) & buff;
always @(posedge clock) //按键1
begin
if(key_edge[0]) //下降沿检测
wr_data[10:9] <= wr_data[10:9] + 1'b1;
end
always @(posedge clock) //按键2
begin
if(key_edge[1]) //下降沿检测
wr_data[7:4] <= wr_data[7:4] + 1'b1;
end
always @(posedge clock) //按键3
begin
if(key_edge[2]) //下降沿检测
wr_data[3:0] <= wr_data[3:0] + 1'b1;
end
always @(posedge clock) //按键4
begin
if(key_edge[3]) //下降沿检测
wr_data[8] <= ~wr_data[8];
end
always @(posedge clock) //按键5
begin
if(key_edge[4]) //下降沿检测
wr_act <= 1'b1;
else
wr_act <= 1'b0;
end
//数码管扫描显示部分
always @(posedge clock) //定义上升沿触发进程
begin
if(div_clk)
cnt <= cnt + 1'b1;
end
always @(posedge clock)
begin
if(div_clk)
begin
case(cnt) //选择扫描显示数据
2'd0:disp_dat = wr_data[10:9] + 4'd1; //第一个数码管
2'd1:disp_dat = wr_data[7:4]; //第三个数码管
2'd2:disp_dat = wr_data[3:0]; //第四个数码管
2'd3:disp_dat = {3'b0,wr_data[8]}; //第八个数码管
endcase
case(cnt) //选择数码管显示位
2'd0:dig = 8'b01111111; //选择第一个数码管显示
2'd1:dig = 8'b11011111; //选择第三个数码管显示
2'd2:dig = 8'b11101111; //选择第四个数码管显示
2'd3:dig = 8'b11111110; //选择第八个数码管显示
endcase
end
end
always @(disp_dat)
begin
case(disp_dat) //七段译码
4'h0:seg = 8'hc0; //显示0
4'h1:seg = 8'hf9; //显示1
4'h2:seg = 8'ha4; //显示2
4'h3:seg = 8'hb0; //显示3
4'h4:seg = 8'h99; //显示4
4'h5:seg = 8'h92; //显示5
4'h6:seg = 8'h82; //显示6
4'h7:seg = 8'hf8; //显示7
4'h8:seg = 8'h80; //显示8
4'h9:seg = 8'h90; //显示9
4'ha:seg = 8'h88; //显示a
4'hb:seg = 8'h83; //显示b
4'hc:seg = 8'hc6; //显示c
4'hd:seg = 8'ha1; //显示d
4'he:seg = 8'h86; //显示e
4'hf:seg = 8'h8e; //显示f
endcase
end
endmodule