// Ch10 debounce2.v
// 去彈跳電路 2
//需 Import pin assignments DE2_115_pin_assignments
module DEBO2(
input CLOCK_50, // 50 MHz clock
input [3:0] KEY, // Pushbutton[3:0]
input [17:0] SW, // Toggle Switch[17:0]
output [8:0] LEDG, // LED Green
output [17:0] LEDR // LED Red
);
// Setup clock divider
wire [6:0] myclock;
/*
divide_by_50 d6(clk_1Mhz,CLK,RST);
divide_by_10 d5(clk_100Khz,clk_1Mhz,RST);
divide_by_10 d4(clk_10Khz,clk_100Khz,RST);
divide_by_10 d3(clk_1Khz,clk_10Khz,RST);
divide_by_10 d2(clk_100hz,clk_1Khz,RST);
divide_by_10 d1(clk_10hz,clk_100hz,RST);
divide_by_10 d0(clk_1hz,clk_10hz,RST);
*/
clock_divider cdiv(CLOCK_50,KEY[3],myclock);
assign LEDR[0]=myclock[0]; //for debug
assign LEDR[1]=myclock[1]; //for debug
assign LEDR[2]=myclock[2]; //for debug
assign LEDR[3]=myclock[3]; //for debug
assign LEDR[4]=myclock[4]; //for debug
assign LEDR[5]=myclock[5]; //for debug
assign LEDR[6]=myclock[6]; //for debug
wire [2:1]Ko;
debounce2 (myclock[2],KEY[0],Ko[1],Ko[2]);
assign LEDG[0]=KEY[0];
assign LEDG[1]=Ko[1];
assign LEDG[2]=Ko[2];
endmodule
module debounce2 (Clk100,Ki,Ko1,Ko2);
input Clk100,Ki; // 一位元輸入
output Ko1,Ko2; // 一位元輸出
reg Ko1,Ko2; // 宣告為暫存器資料
reg [1:0] Q1,Q2; // 宣告為暫存器資料
reg S,R; // 宣告為暫存器資料
// 鍵盤信號取樣
always@(posedge Clk100) // 約 100 Hz
begin
Q1[1] = Q1[0]; // 連續取樣二次
Q1[0] = Ki;
if (Q1 == 2'b11) S = 1;
else S = 0;
if (Q1 == 2'b00) R = 1;
else R = 0;
end
// RS 閂鎖器
always@(R or S)
if (S == 1 && R == 0)
Ko1 = 1;
else if (S == 0 && R == 1)
Ko1 = 0;
// 微分取得一週期的脈波
always@(posedge Clk100)
begin
Q2[1] = Q2[0]; // 連續取樣二次
Q2[0] = Ko1;
if (Q2 == 2'b01) Ko2 = 1;
else Ko2 = 0;
end
endmodule
module clock_divider(CLK,RST,clock);
input CLK,RST;
output [6:0] clock;
wire clk_1Mhz,clk_100Khz,clk_10Khz,clk_1Khz,clk_100hz,clk_10hz,clk_1hz;
assign clock = {clk_1Mhz,clk_100Khz,clk_10Khz,clk_1Khz,clk_100hz,clk_10hz,clk_1hz};
divide_by_50 d6(clk_1Mhz,CLK,RST);
divide_by_10 d5(clk_100Khz,clk_1Mhz,RST);
divide_by_10 d4(clk_10Khz,clk_100Khz,RST);
divide_by_10 d3(clk_1Khz,clk_10Khz,RST);
divide_by_10 d2(clk_100hz,clk_1Khz,RST);
divide_by_10 d1(clk_10hz,clk_100hz,RST);
divide_by_10 d0(clk_1hz,clk_10hz,RST);
endmodule
module divide_by_10(Q,CLK,RST);
input CLK, RST;
output Q;
reg Q;
reg [2:0] count;
always @ (posedge CLK or negedge RST)
begin
if (~RST)
begin
Q <= 1'b0;
count <= 3'b000;
end
else if (count < 4)
begin
count <= count+1'b1;
end
else
begin
count <= 3'b000;
Q <= ~Q;
end
end
endmodule
module divide_by_50(Q,CLK,RST);
input CLK, RST;
output Q;
reg Q;
reg [4:0] count;
always @ (posedge CLK or negedge RST)
begin
if (~RST)
begin
Q <= 1'b0;
count <= 5'b00000;
end
else if (count < 24)
begin
count <= count+1'b1;
end
else
begin
count <= 5'b00000;
Q <= ~Q;
end
end
endmodule
沒有留言:
張貼留言