// led_blinker.sv // Two modules: led_blinker (top) and tick_gen (prescaler). // Lint with: verilator --lint-only -Wall -Wno-DECLFILENAME led_blinker.sv // // Blinks an LED at BLINK_HZ (one full on/off period per 1/BLINK_HZ seconds). // The whole design runs on clk; tick_gen supplies a clock enable that toggles // the LED twice per blink period. module led_blinker #( parameter int CLK_HZ = 100_000_000, parameter int BLINK_HZ = 1 ) ( input logic clk, input logic rst, // synchronous, active high output logic led ); logic tick; tick_gen #( .CLK_HZ (CLK_HZ), .TICK_HZ (2 * BLINK_HZ) ) u_tick ( .clk (clk), .rst (rst), .tick (tick) ); always_ff @(posedge clk) begin if (rst) led <= 1'b0; else if (tick) led <= ~led; end endmodule // Prescaler: produces a one-clock-cycle pulse on tick every CLK_HZ / TICK_HZ // clock cycles. Use tick as a clock enable, never as a clock. // CLK_HZ / TICK_HZ must be an integer of at least 2. module tick_gen #( parameter int CLK_HZ = 100_000_000, parameter int TICK_HZ = 1_000 ) ( input logic clk, input logic rst, // synchronous, active high output logic tick ); localparam int DIV = CLK_HZ / TICK_HZ; // clock cycles per tick localparam int W = (DIV > 1) ? $clog2(DIV) : 1; logic [W-1:0] cnt; always_ff @(posedge clk) begin if (rst) begin cnt <= '0; tick <= 1'b0; end else if (cnt == W'(DIV - 1)) begin cnt <= '0; tick <= 1'b1; end else begin cnt <= cnt + W'(1); tick <= 1'b0; end end endmodule