To implement a counter we can use the Register
primitive and the +
operator. How can we make a more general counter of arbitray width?
In [1]:
import magma as m
from mantle import Register
The generator for a counter is parameterized by the number of bits in the counter, n
.
In [2]:
class Counter(m.Generator):
@staticmethod
def generate(width: int):
class _Counter(m.Circuit):
name = f'Counter{width}'
io = m.IO(O=m.Out(m.UInt[width])) + m.ClockIO()
reg = Register(width, _type=m.UInt)
io.O @= reg(reg.O + 1)
return _Counter
Simulate the counter.
In [3]:
from fault import PythonTester
Counter4 = Counter.generate(4)
tester = PythonTester(Counter4, Counter4.CLK)
tester.eval()
val = tester.peek(Counter4.O)
print(tester.peek(Counter4.O))
assert val == 0
for i in range(1,11):
tester.step() # toggle clock - now High
assert i == tester.peek(Counter4.O)
print(tester.peek(Counter4.O))
tester.step() # toggle clock - now Low
assert i == tester.peek(Counter4.O)
print("Success!")
In [4]:
m.compile("build/Counter4", Counter4, inline=True)
!coreir -i build/Counter4.json -p instancecount
!cat build/Counter4.v
In [ ]: