1 from nmigen
import Signal
, Value
, Elaboratable
, Module
, Cat
, Const
2 from nmigen
.build
import Platform
5 from nmigen
.back
import verilog
7 from nmigen
.sim
import Simulator
, Delay
, Settle
, Tick
, Passive
9 from nmutil
.gtkw
import write_gtkw
12 class UpCounter(Elaboratable
):
14 A 16-bit up counter with a fixed limit.
19 The value at which the counter overflows.
24 The counter is incremented if ``en`` is asserted, and retains
27 ``ovf`` is asserted when the counter reaches its limit.
29 def __init__(self
, limit
):
37 self
.count
= Signal(16)
39 def elaborate(self
, platform
):
42 m
.d
.comb
+= self
.ovf
.eq(self
.count
== self
.limit
)
46 m
.d
.sync
+= self
.count
.eq(0)
48 m
.d
.sync
+= self
.count
.eq(self
.count
+ 1)
52 from nmigen
.sim
import Simulator
57 # Disabled counter should not overflow.
61 assert not (yield dut
.ovf
)
63 # Once enabled, the counter should overflow in 25 cycles.
67 assert not (yield dut
.ovf
)
69 assert (yield dut
.ovf
)
71 # The overflow should clear in one cycle.
73 assert not (yield dut
.ovf
)
77 sim
.add_clock(1e-6) # 1 MHz
78 sim
.add_sync_process(bench
)
79 with sim
.write_vcd("up_counter.vcd"):
82 # GTKWave doc generation
85 'in': {'color': 'orange'},
86 'out': {'color': 'yellow'},
87 'pad_i': {'color': 'orange'},
88 'pad_o': {'color': 'yellow'},
89 'core_i': {'color': 'indigo'},
90 'core_o': {'color': 'blue'},
91 'debug': {'module': 'top', 'color': 'red'}
99 ('count[15:0]', 'out')
103 write_gtkw("up_counter.gtkw", "up_counter.vcd", traces
, style
, module
="bench.top")
106 with
open("up_counter.v", "w") as f
:
107 f
.write(verilog
.convert(top
, ports
=[top
.en
, top
.ovf
]))