diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/main/scala/chisel3/util/Counter.scala | 18 | ||||
| -rw-r--r-- | src/test/scala/chiselTests/Counter.scala | 17 |
2 files changed, 32 insertions, 3 deletions
diff --git a/src/main/scala/chisel3/util/Counter.scala b/src/main/scala/chisel3/util/Counter.scala index fa1bb80c..603ebeb6 100644 --- a/src/main/scala/chisel3/util/Counter.scala +++ b/src/main/scala/chisel3/util/Counter.scala @@ -57,7 +57,7 @@ class Counter private (r: Range, oldN: Option[Int] = None) { def this(n: Int) { this(0 until math.max(1, n), Some(n)) } /** The current value of the counter. */ - val value = if (r.length > 1) RegInit(r.head.U(width.W)) else r.head.U + val value = if (r.length > 1) RegInit(r.head.U(width.W)) else WireInit(r.head.U) /** The range of the counter values. */ def range: Range = r @@ -91,6 +91,11 @@ class Counter private (r: Range, oldN: Option[Int] = None) { true.B } } + + /** Resets the counter to its initial value */ + def reset(): Unit = { + value := r.head.U + } } object Counter @@ -118,14 +123,21 @@ object Counter * * @param r the range of counter values * @param enable controls whether the counter increments this cycle + * @param reset resets the counter to its initial value during this cycle * @return tuple of the counter value and whether the counter will wrap (the value is at * maximum and the condition is true). */ @chiselName - def apply(r: Range, enable: Bool = true.B): (UInt, Bool) = { + def apply(r: Range, enable: Bool = true.B, reset: Bool = false.B): (UInt, Bool) = { val c = new Counter(r) val wrap = WireInit(false.B) - when (enable) { wrap := c.inc() } + + when(reset) { + c.reset() + }.elsewhen(enable) { + wrap := c.inc() + } + (c.value, wrap) } } diff --git a/src/test/scala/chiselTests/Counter.scala b/src/test/scala/chiselTests/Counter.scala index 985cf3fd..41f550a8 100644 --- a/src/test/scala/chiselTests/Counter.scala +++ b/src/test/scala/chiselTests/Counter.scala @@ -29,6 +29,19 @@ class EnableTester(seed: Int) extends BasicTester { } } +class ResetTester(n: Int) extends BasicTester { + val triggerReset = WireInit(false.B) + val wasReset = RegNext(triggerReset) + val (value, _) = Counter(0 until 8, reset = triggerReset) + + triggerReset := value === (n-1).U + + when(wasReset) { + assert(value === 0.U) + stop() + } +} + class WrapTester(max: Int) extends BasicTester { val (cnt, wrap) = Counter(true.B, max) when(wrap) { @@ -61,6 +74,10 @@ class CounterSpec extends ChiselPropSpec { forAll(safeUInts) { (seed: Int) => whenever(seed >= 0) { assertTesterPasses{ new EnableTester(seed) } } } } + property("Counter can be reset") { + forAll(smallPosInts) { (seed: Int) => assertTesterPasses{ new ResetTester(seed) } } + } + property("Counter should wrap") { forAll(smallPosInts) { (max: Int) => assertTesterPasses{ new WrapTester(max) } } } |
