| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- `timescale 1ns/1ps
- // Unit testbench for buzzer_pwm_4khz:
- // Verifies exact 4000 Hz, 80% duty square wave at 25 MHz
- // (6250 clks period, 5000 clks HIGH, 1250 clks LOW) and strict LOW
- // when disabled or reset.
- module buzzer_pwm_4khz_tb;
- reg clk = 1'b0;
- reg rst_n = 1'b0;
- reg enable = 1'b0;
- wire buzzer_out;
- always #20 clk = ~clk; // 25 MHz (40 ns period)
- buzzer_pwm_4khz #(
- .PERIOD_CLKS(6250),
- .HIGH_CLKS(5000)
- ) dut (
- .clk(clk),
- .rst_n(rst_n),
- .enable(enable),
- .buzzer_out(buzzer_out)
- );
- integer i, high_cnt, low_cnt, cyc;
- initial begin
- // Reset check
- repeat (5) @(posedge clk);
- #1;
- if (buzzer_out !== 1'b0) $fatal(1, "FAIL: buzzer_out not 0 during reset");
- // Post-reset disabled check
- @(negedge clk); rst_n = 1'b1;
- repeat (200) begin
- @(posedge clk); #1;
- if (buzzer_out !== 1'b0) $fatal(1, "FAIL: buzzer_out high while disabled");
- end
- // Enable: verify 3 full consecutive periods (exact 5000 HIGH + 1250 LOW each)
- @(negedge clk); enable = 1'b1;
- for (cyc = 0; cyc < 3; cyc = cyc + 1) begin
- high_cnt = 0;
- low_cnt = 0;
- for (i = 0; i < 6250; i = i + 1) begin
- @(posedge clk); #1;
- if (i < 5000) begin
- if (buzzer_out !== 1'b1)
- $fatal(1, "FAIL: cyc=%0d tick=%0d expected HIGH, got %b", cyc, i, buzzer_out);
- high_cnt = high_cnt + 1;
- end else begin
- if (buzzer_out !== 1'b0)
- $fatal(1, "FAIL: cyc=%0d tick=%0d expected LOW, got %b", cyc, i, buzzer_out);
- low_cnt = low_cnt + 1;
- end
- end
- if (high_cnt != 5000 || low_cnt != 1250)
- $fatal(1, "FAIL: cyc=%0d high=%0d low=%0d", cyc, high_cnt, low_cnt);
- end
- // Mid-high disable check (simulates SET_ALL buzzer=0 or watchdog expiry)
- repeat (1000) @(posedge clk); #1;
- if (buzzer_out !== 1'b1) $fatal(1, "FAIL: expected HIGH mid-cycle before disable");
- @(negedge clk); enable = 1'b0;
- repeat (200) begin
- @(posedge clk); #1;
- if (buzzer_out !== 1'b0) $fatal(1, "FAIL: buzzer_out stayed HIGH after disable");
- end
- // Re-enable must restart cleanly from phase 0 (5000 HIGH then 1250 LOW)
- @(negedge clk); enable = 1'b1;
- for (i = 0; i < 6250; i = i + 1) begin
- @(posedge clk); #1;
- if (i < 5000 && buzzer_out !== 1'b1)
- $fatal(1, "FAIL: restart tick=%0d expected HIGH", i);
- if (i >= 5000 && buzzer_out !== 1'b0)
- $fatal(1, "FAIL: restart tick=%0d expected LOW", i);
- end
- $display("PASS buzzer_pwm_4khz_tb (4000Hz 80%% duty: 5000 HIGH / 1250 LOW / 6250 period)");
- $finish;
- end
- endmodule
|