Problems

13. Divide by N

MediumWrite the moduleAbout 25 min
sequentialcountersclock divisionclock enable

Divide the clock by a number n given on an input (n is 2 to 15; smaller values are not tested). Do not create a new clock: produce two signals that stay in the clk domain.

Keep a counter that runs 0, 1, ..., n - 1 and then returns to 0, so one period is n clock cycles.

  • tick is 1 during the last cycle of each period (when the counter is n - 1). It is a clock enable for logic that should run once every n cycles.
  • sq is a square wave: 1 for the first ceil(n / 2) cycles of each period and 0 for the rest. For even n it has a 50% duty cycle; for odd n it is high one cycle longer than it is low.

If n is lowered while the counter is already at or above the new n - 1, the counter returns to 0 on the next edge. rst (synchronous, active high) sets the counter to 0.

A note on odd n: a true 50% duty cycle for odd n needs logic on the falling clock edge as well. This playground samples outputs once per full clock cycle, so it cannot show half-cycle timing; the problem asks for the single-edge version.

Ports

Module clk_div

PortDirBitsWhat it is
clkin1Clock.
rstin1Synchronous reset, active high.
nin4Divisor, 2 to 15.
tickout11 in the last cycle of each period.
sqout1Square wave, high for the first ceil(n / 2) cycles.

Example

With n = 5, after reset the counter reads 0, 1, 2, 3, 4, 0, ... ; sq is 1, 1, 1, 0, 0 and tick is 0, 0, 0, 0, 1 in those cycles.

Stuck? . Sign in to save your progress. You can solve the free problems without an account.

Verilogclk_div.v
14px
Loading the editor…

Submit your answer to have it graded. The hidden test runs on the server; you see whether it passes and, if not, the first case it gets wrong.

Divide by N: Verilog interview question | breadboardhub