Skip to content

Commit

Permalink
cores/time/timer: add a timer capable of multiple delays
Browse files Browse the repository at this point in the history
  • Loading branch information
povauboin committed Nov 12, 2024
1 parent e87ae64 commit b3a0141
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lambdalib/cores/time/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,30 @@ def elaborate(self, platform):
m.d.sync += count.eq(count.reset)

return m

class WaitNTimer(Elaboratable):
def __init__(self, ts):
if not isinstance(ts, list):
ts = [ts]
self.ts = ts
self.wait = Signal(len(ts))
self.done = Signal()

def elaborate(self, platform):
m = Module()

count = Signal(range(max(self.ts) + 1))

with m.If(self.wait.any()):
with m.If(~self.done):
m.d.sync += count.eq(count + 1)
with m.Else():
m.d.sync += count.eq(0)

cond = m.If
for i, t in enumerate(self.ts):
with cond(self.wait[i] & (count == t)):
m.d.comb += self.done.eq(1)
cond = m.Elif

return m
62 changes: 62 additions & 0 deletions lambdalib/tests/test_cores_time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# 2024 - LambdaConcept - [email protected]

from amaranth import *
from amaranth.sim import *

from ..cores.time.timer import *


def test_timer():
cycles = 100
timer = WaitTimer(cycles)
sim = Simulator(timer)

def bench():
for i in range(15):
yield
yield timer.wait.eq(1)
for i in range(200):
yield
expect = (i >= cycles)
result = (yield timer.done)
# print(result, expect)
assert(result == expect)

sim.add_clock(1e-6)
sim.add_sync_process(bench)
with sim.write_vcd("tests/test_time_timer.vcd"):
sim.run()


def test_ntimer():
cycles_1 = 100
cycles_2 = 200
timer = WaitNTimer([cycles_1, cycles_2])
sim = Simulator(timer)

def bench():
for i in range(15):
yield


for i, cyc in enumerate(timer.ts):
yield timer.wait[i].eq(1)
for i in range(400):
yield
expect = (i >= cyc)
result = (yield timer.done)
# print(result, expect, cyc)
assert(result == expect)

yield timer.wait.eq(0)
yield

sim.add_clock(1e-6)
sim.add_sync_process(bench)
with sim.write_vcd("tests/test_time_timer.vcd"):
sim.run()


if __name__ == "__main__":
test_timer(); print()
test_ntimer(); print()

0 comments on commit b3a0141

Please sign in to comment.