SONIC3D

Verilog按键消抖(button debounce)

Nov 1st, 2023
3,274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VeriLog 1.93 KB | Gaming | 0 0
  1. // Verilog简易按键消抖(button debounce)(假设clk为50MHz,持续按下或弹起1/25秒,即40ms,才确认按键状态)
  2. // 51个MacroCell,可按需简化
  3. // 2023.Nov.02
  4. module button_debounce (
  5.     input           clk,
  6.     input           button,             // 按钮输入,0表示按下,1表示弹起
  7.     output          button_debounced    // 按钮消抖后的输出,0表示按下,1表示弹起
  8. );
  9.  
  10. // 消抖状态相关寄存器
  11. reg [24:0]  counter_pressed;        // 按钮持续按下状态计数器
  12. reg [24:0]  counter_not_pressed;    // 按钮持续弹起状态计数器
  13. reg button_state = 1'b1;            // 按钮消抖结果状态(1表示弹起,0表示按下)
  14.  
  15. assign button_debounced = button_state; // 按钮结果状态输出
  16.  
  17. // 赋初值,注意这些初始化不会综合进最终硬件,仅用于模拟仿真
  18. initial begin
  19.     counter_pressed <= 25'b0;
  20.     counter_not_pressed <= 25'b0;
  21. end
  22.  
  23. // 时钟上升沿时进行消抖计数(假设时钟为50MHz,以下代码在2M周期后,即1/25秒后作消抖结果采样)
  24. always @ (posedge clk)
  25. begin
  26.     // 按钮按下,且按钮现有消抖结果状态为弹起状态
  27.     if(!button & button_state) begin
  28.         counter_pressed <= counter_pressed + 1'b1;  // 消抖计数
  29.     end else begin
  30.         counter_pressed <= 25'b0;   // 重置消抖流程
  31.     end
  32.  
  33.     // 按下持续2M周期后,更新消抖结果值
  34.     if(counter_pressed == 25'd2000000) begin
  35.         counter_pressed <= 25'b0;
  36.         button_state = 1'b0;
  37.     end
  38.  
  39.     // 按钮弹起,且按钮现有消抖结果状态为按下状态
  40.     if(button & !button_state) begin
  41.         counter_not_pressed <= counter_not_pressed + 1'b1;
  42.     end else begin
  43.         counter_not_pressed <= 25'b0;
  44.     end
  45.  
  46.     if(counter_not_pressed == 25'd2000000) begin
  47.         counter_not_pressed <= 25'b0;
  48.         button_state = 1'b1;
  49.     end
  50. end
  51.  
  52. endmodule
  53.  
Tags: verilog
Advertisement