110a5fd8d684e07fc0b3887a00b13edf543048b0
2 from nmigen
import Signal
, Value
, Elaboratable
, Module
, Cat
, Const
3 #from nmigen import ClockDomain, ClockSignal
4 from nmigen
.build
import Platform
5 #from nmigen.cli import main_parser, main_runner
6 #from nmigen.asserts import Assert, Assume, Cover, Past
9 from nmigen
.back
import verilog
11 from nmigen
.sim
import Simulator
, Delay
, Settle
, Tick
, Passive
13 from nmutil
.gtkw
import write_gtkw
16 class UpCounter(Elaboratable
):
18 A 16-bit up counter with a fixed limit.
23 The value at which the counter overflows.
28 The counter is incremented if ``en`` is asserted, and retains
31 ``ovf`` is asserted when the counter reaches its limit.
33 def __init__(self
, limit
):
41 self
.count
= Signal(16)
43 def elaborate(self
, platform
):
46 m
.d
.comb
+= self
.ovf
.eq(self
.count
== self
.limit
)
50 m
.d
.sync
+= self
.count
.eq(0)
52 m
.d
.sync
+= self
.count
.eq(self
.count
+ 1)
56 from nmigen
.sim
import Simulator
61 # Disabled counter should not overflow.
65 assert not (yield dut
.ovf
)
67 # Once enabled, the counter should overflow in 25 cycles.
71 assert not (yield dut
.ovf
)
73 assert (yield dut
.ovf
)
75 # The overflow should clear in one cycle.
77 assert not (yield dut
.ovf
)
81 sim
.add_clock(1e-6) # 1 MHz
82 sim
.add_sync_process(bench
)
83 with sim
.write_vcd("up_counter.vcd"):
86 # GTKWave doc generation
89 'in': {'color': 'orange'},
90 'out': {'color': 'yellow'},
91 'pad_i': {'color': 'orange'},
92 'pad_o': {'color': 'yellow'},
93 'core_i': {'color': 'indigo'},
94 'core_o': {'color': 'blue'},
95 'debug': {'module': 'top', 'color': 'red'}
103 ('count[15:0]', 'out')
107 write_gtkw("up_counter.gtkw", "up_counter.vcd", traces
, style
, module
="bench.top")
110 with
open("up_counter.v", "w") as f
:
111 f
.write(verilog
.convert(top
, ports
=[top
.en
, top
.ovf
]))