buzzer_pwm_4khz_tb.v 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. `timescale 1ns/1ps
  2. // Unit testbench for buzzer_pwm_4khz:
  3. // Verifies exact 4000 Hz, 80% duty square wave at 25 MHz
  4. // (6250 clks period, 5000 clks HIGH, 1250 clks LOW) and strict LOW
  5. // when disabled or reset.
  6. module buzzer_pwm_4khz_tb;
  7. reg clk = 1'b0;
  8. reg rst_n = 1'b0;
  9. reg enable = 1'b0;
  10. wire buzzer_out;
  11. always #20 clk = ~clk; // 25 MHz (40 ns period)
  12. buzzer_pwm_4khz #(
  13. .PERIOD_CLKS(6250),
  14. .HIGH_CLKS(5000)
  15. ) dut (
  16. .clk(clk),
  17. .rst_n(rst_n),
  18. .enable(enable),
  19. .buzzer_out(buzzer_out)
  20. );
  21. integer i, high_cnt, low_cnt, cyc;
  22. initial begin
  23. // Reset check
  24. repeat (5) @(posedge clk);
  25. #1;
  26. if (buzzer_out !== 1'b0) $fatal(1, "FAIL: buzzer_out not 0 during reset");
  27. // Post-reset disabled check
  28. @(negedge clk); rst_n = 1'b1;
  29. repeat (200) begin
  30. @(posedge clk); #1;
  31. if (buzzer_out !== 1'b0) $fatal(1, "FAIL: buzzer_out high while disabled");
  32. end
  33. // Enable: verify 3 full consecutive periods (exact 5000 HIGH + 1250 LOW each)
  34. @(negedge clk); enable = 1'b1;
  35. for (cyc = 0; cyc < 3; cyc = cyc + 1) begin
  36. high_cnt = 0;
  37. low_cnt = 0;
  38. for (i = 0; i < 6250; i = i + 1) begin
  39. @(posedge clk); #1;
  40. if (i < 5000) begin
  41. if (buzzer_out !== 1'b1)
  42. $fatal(1, "FAIL: cyc=%0d tick=%0d expected HIGH, got %b", cyc, i, buzzer_out);
  43. high_cnt = high_cnt + 1;
  44. end else begin
  45. if (buzzer_out !== 1'b0)
  46. $fatal(1, "FAIL: cyc=%0d tick=%0d expected LOW, got %b", cyc, i, buzzer_out);
  47. low_cnt = low_cnt + 1;
  48. end
  49. end
  50. if (high_cnt != 5000 || low_cnt != 1250)
  51. $fatal(1, "FAIL: cyc=%0d high=%0d low=%0d", cyc, high_cnt, low_cnt);
  52. end
  53. // Mid-high disable check (simulates SET_ALL buzzer=0 or watchdog expiry)
  54. repeat (1000) @(posedge clk); #1;
  55. if (buzzer_out !== 1'b1) $fatal(1, "FAIL: expected HIGH mid-cycle before disable");
  56. @(negedge clk); enable = 1'b0;
  57. repeat (200) begin
  58. @(posedge clk); #1;
  59. if (buzzer_out !== 1'b0) $fatal(1, "FAIL: buzzer_out stayed HIGH after disable");
  60. end
  61. // Re-enable must restart cleanly from phase 0 (5000 HIGH then 1250 LOW)
  62. @(negedge clk); enable = 1'b1;
  63. for (i = 0; i < 6250; i = i + 1) begin
  64. @(posedge clk); #1;
  65. if (i < 5000 && buzzer_out !== 1'b1)
  66. $fatal(1, "FAIL: restart tick=%0d expected HIGH", i);
  67. if (i >= 5000 && buzzer_out !== 1'b0)
  68. $fatal(1, "FAIL: restart tick=%0d expected LOW", i);
  69. end
  70. $display("PASS buzzer_pwm_4khz_tb (4000Hz 80%% duty: 5000 HIGH / 1250 LOW / 6250 period)");
  71. $finish;
  72. end
  73. endmodule