Write a clock divider counter in Verilog
Divide a 12 MHz board clock to 1 Hz with a parameterised counter and a toggling register in Verilog-2005, so the output stays a registered signal.
A board clock is too fast to see, so the usual first job is dividing it down. On a 12 MHz iCEstick or iCEBreaker the cheap answer is a counter that flips one output register every half period, written in plain Verilog-2005.
module clkdiv #(parameter DIV = 6_000_000) (
input wire clk,
output reg out = 1'b0
);
reg [22:0] count = 0;
always @(posedge clk) begin
if (count == DIV - 1) begin
count <= 0;
out <= ~out;
end else begin
count <= count + 1;
end
end
endmoduleThe counter reaches DIV - 1 after 6,000,000 cycles, which is half a second at 12 MHz, and out toggles each time, so one full period is 1 s and the output is a 1 Hz square wave. The = 0 initial values work as power-up values because the iCE40 loads flip-flop state from the bitstream, and Yosys 0.46 honours them. Twenty-three bits hold up to 8,388,607, enough for 6,000,000.
Keep out as a flip-flop output. Feeding it into another module's clock port is legal, but the fabric then routes a data net as a clock, which gives skew. For a slow enable, use a one-cycle tick and a clock-enable instead of a derived clock.