New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How do you make a bounded up-down counter without modulo? #492
Comments
Assuming you are interested in a counter that increments or decrements by 1 each cycle, something like this would give you arbitrary overflow bounds: class BoundedCounter(Elaboratable):
def __init__(self, min, max):
self.min = min
self.max = max
self.up = Signal(1)
self.count = Signal(range(min, max + 1))
def elaborate(self, platform):
m = Module()
with m.If(self.up):
with m.If(self.count == max):
m.d.sync += self.count.eq(min)
with m.Else():
m.d.sync += self.count.eq(self.count + 1)
with m.Else():
with m.If(self.count == min):
m.d.sync += self.count.eq(max)
with m.Else():
m.d.sync += self.count.eq(self.count - 1)
return m |
Does this answer your question? |
I'd suggest to avoid the % and / operators in hardware design (when you divide by a number that is not a power of 2). division is slow and expensive in hardware, it would take more than one clock at a rate users usually want to work, that is why usually backends don't implement that in synthesizable code regardless of what language you would use. |
This answers my question, |
Modulo operators for negative numbers are a known issue, and the operator is not implemented on stable.
What is the work around for a decrement to underflow around an arbitrary bounds?
This test shows the modulo producing strange results on decrement that disappear if you force the range into positive.
The text was updated successfully, but these errors were encountered: