Skip to content

Commit 9664b66

Browse files
committed
Deploy preview for PR 17 πŸ›«
1 parent cb60e05 commit 9664b66

209 files changed

Lines changed: 64168 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from amaranth import *
2+
from amaranth.lib import wiring
3+
from amaranth.lib.wiring import In, Out
4+
5+
6+
class UpCounter(wiring.Component):
7+
"""
8+
A 16-bit up counter with a fixed limit.
9+
10+
Parameters
11+
----------
12+
limit : int
13+
The value at which the counter overflows.
14+
15+
Attributes
16+
----------
17+
en : Signal, in
18+
The counter is incremented if ``en`` is asserted, and retains
19+
its value otherwise.
20+
ovf : Signal, out
21+
``ovf`` is asserted when the counter reaches its limit.
22+
"""
23+
24+
en: In(1)
25+
ovf: Out(1)
26+
27+
def __init__(self, limit):
28+
self.limit = limit
29+
self.count = Signal(16)
30+
31+
super().__init__()
32+
33+
def elaborate(self, platform):
34+
m = Module()
35+
36+
m.d.comb += self.ovf.eq(self.count == self.limit)
37+
38+
with m.If(self.en):
39+
with m.If(self.ovf):
40+
m.d.sync += self.count.eq(0)
41+
with m.Else():
42+
m.d.sync += self.count.eq(self.count + 1)
43+
44+
return m
45+
# --- TEST ---
46+
from amaranth.sim import Simulator
47+
48+
49+
dut = UpCounter(25)
50+
async def bench(ctx):
51+
# Disabled counter should not overflow.
52+
ctx.set(dut.en, 0)
53+
for _ in range(30):
54+
await ctx.tick()
55+
assert not ctx.get(dut.ovf)
56+
57+
# Once enabled, the counter should overflow in 25 cycles.
58+
ctx.set(dut.en, 1)
59+
for _ in range(24):
60+
await ctx.tick()
61+
assert not ctx.get(dut.ovf)
62+
await ctx.tick()
63+
assert ctx.get(dut.ovf)
64+
65+
# The overflow should clear in one cycle.
66+
await ctx.tick()
67+
assert not ctx.get(dut.ovf)
68+
69+
70+
sim = Simulator(dut)
71+
sim.add_clock(1e-6) # 1 MHz
72+
sim.add_testbench(bench)
73+
with sim.write_vcd("up_counter.vcd"):
74+
sim.run()
75+
# --- CONVERT ---
76+
from amaranth.back import verilog
77+
78+
79+
top = UpCounter(25)
80+
with open("up_counter.v", "w") as f:
81+
f.write(verilog.convert(top))
177 KB
Loading
179 KB
Loading
177 KB
Loading
51.1 KB
Loading
Lines changed: 18 additions & 0 deletions
Loading
43.3 KB
Loading
134 KB
Loading
227 KB
Loading
56.3 KB
Loading

0 commit comments

Comments
Β (0)