Advertisement
SONIC3D

Verilog按键消抖(button debounce)

Nov 1st, 2023
1,069
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. // sonic3d@gmail.com
  4. // 2023.Nov.02
  5. module button_debounce (
  6.     input           clk,
  7.     input           button,             // 按钮输入,0表示按下,1表示弹起
  8.     output          button_debounced    // 按钮消抖后的输出,0表示按下,1表示弹起
  9. );
  10.  
  11. // 消抖状态相关寄存器
  12. reg [24:0]  counter_pressed;        // 按钮持续按下状态计数器
  13. reg [24:0]  counter_not_pressed;    // 按钮持续弹起状态计数器
  14. reg button_state = 1'b1;            // 按钮消抖结果状态(1表示弹起,0表示按下)
  15.  
  16. assign button_debounced = button_state; // 按钮结果状态输出
  17.  
  18. // 赋初值,注意这些初始化不会综合进最终硬件,仅用于模拟仿真
  19. initial begin
  20.     counter_pressed <= 25'b0;
  21.     counter_not_pressed <= 25'b0;
  22. end
  23.  
  24. // 时钟上升沿时进行消抖计数(假设时钟为50MHz,以下代码在2M周期后,即1/25秒后作消抖结果采样)
  25. always @ (posedge clk)
  26. begin
  27.     // 按钮按下,且按钮现有消抖结果状态为弹起状态
  28.     if(!button & button_state) begin
  29.         counter_pressed <= counter_pressed + 1'b1;  // 消抖计数
  30.     end else begin
  31.         counter_pressed <= 25'b0;   // 重置消抖流程
  32.     end
  33.  
  34.     // 按下持续2M周期后,更新消抖结果值
  35.     if(counter_pressed == 25'd2000000) begin
  36.         counter_pressed <= 25'b0;
  37.         button_state = 1'b0;
  38.     end
  39.  
  40.     // 按钮弹起,且按钮现有消抖结果状态为按下状态
  41.     if(button & !button_state) begin
  42.         counter_not_pressed <= counter_not_pressed + 1'b1;
  43.     end else begin
  44.         counter_not_pressed <= 25'b0;
  45.     end
  46.  
  47.     if(counter_not_pressed == 25'd2000000) begin
  48.         counter_not_pressed <= 25'b0;
  49.         button_state = 1'b1;
  50.     end
  51. end
  52.  
  53. endmodule
  54.  
Tags: verilog
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement