Skip to content

Commit b3a0141

Browse files
committed
cores/time/timer: add a timer capable of multiple delays
1 parent e87ae64 commit b3a0141

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

lambdalib/cores/time/timer.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,30 @@ def elaborate(self, platform):
1818
m.d.sync += count.eq(count.reset)
1919

2020
return m
21+
22+
class WaitNTimer(Elaboratable):
23+
def __init__(self, ts):
24+
if not isinstance(ts, list):
25+
ts = [ts]
26+
self.ts = ts
27+
self.wait = Signal(len(ts))
28+
self.done = Signal()
29+
30+
def elaborate(self, platform):
31+
m = Module()
32+
33+
count = Signal(range(max(self.ts) + 1))
34+
35+
with m.If(self.wait.any()):
36+
with m.If(~self.done):
37+
m.d.sync += count.eq(count + 1)
38+
with m.Else():
39+
m.d.sync += count.eq(0)
40+
41+
cond = m.If
42+
for i, t in enumerate(self.ts):
43+
with cond(self.wait[i] & (count == t)):
44+
m.d.comb += self.done.eq(1)
45+
cond = m.Elif
46+
47+
return m

lambdalib/tests/test_cores_time.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# 2024 - LambdaConcept - [email protected]
2+
3+
from amaranth import *
4+
from amaranth.sim import *
5+
6+
from ..cores.time.timer import *
7+
8+
9+
def test_timer():
10+
cycles = 100
11+
timer = WaitTimer(cycles)
12+
sim = Simulator(timer)
13+
14+
def bench():
15+
for i in range(15):
16+
yield
17+
yield timer.wait.eq(1)
18+
for i in range(200):
19+
yield
20+
expect = (i >= cycles)
21+
result = (yield timer.done)
22+
# print(result, expect)
23+
assert(result == expect)
24+
25+
sim.add_clock(1e-6)
26+
sim.add_sync_process(bench)
27+
with sim.write_vcd("tests/test_time_timer.vcd"):
28+
sim.run()
29+
30+
31+
def test_ntimer():
32+
cycles_1 = 100
33+
cycles_2 = 200
34+
timer = WaitNTimer([cycles_1, cycles_2])
35+
sim = Simulator(timer)
36+
37+
def bench():
38+
for i in range(15):
39+
yield
40+
41+
42+
for i, cyc in enumerate(timer.ts):
43+
yield timer.wait[i].eq(1)
44+
for i in range(400):
45+
yield
46+
expect = (i >= cyc)
47+
result = (yield timer.done)
48+
# print(result, expect, cyc)
49+
assert(result == expect)
50+
51+
yield timer.wait.eq(0)
52+
yield
53+
54+
sim.add_clock(1e-6)
55+
sim.add_sync_process(bench)
56+
with sim.write_vcd("tests/test_time_timer.vcd"):
57+
sim.run()
58+
59+
60+
if __name__ == "__main__":
61+
test_timer(); print()
62+
test_ntimer(); print()

0 commit comments

Comments
 (0)