From 6c34949c45cf7ddfdabafb749de2cb9e439b381e Mon Sep 17 00:00:00 2001 From: ducky Date: Mon, 26 Oct 2015 17:30:15 -0700 Subject: Break out Utils.scala into smaller portions --- src/main/scala/Chisel/util/Counter.scala | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/scala/Chisel/util/Counter.scala (limited to 'src/main/scala/Chisel/util/Counter.scala') diff --git a/src/main/scala/Chisel/util/Counter.scala b/src/main/scala/Chisel/util/Counter.scala new file mode 100644 index 00000000..e4a8e95b --- /dev/null +++ b/src/main/scala/Chisel/util/Counter.scala @@ -0,0 +1,35 @@ +// See LICENSE for license details. + +package Chisel + +/** A counter module + * @param n The maximum value of the counter, does not have to be power of 2 + */ +class Counter(val n: Int) { + val value = if (n == 1) UInt(0) else Reg(init=UInt(0, log2Up(n))) + def inc(): Bool = { + if (n == 1) { + Bool(true) + } else { + val wrap = value === UInt(n-1) + value := Mux(Bool(!isPow2(n)) && wrap, UInt(0), value + UInt(1)) + wrap + } + } +} + +/** Counter Object + * Example Usage: + * {{{ val countOn = Bool(true) // increment counter every clock cycle + * val myCounter = Counter(countOn, n) + * when ( myCounter.value === UInt(3) ) { ... } }}}*/ +object Counter +{ + def apply(n: Int): Counter = new Counter(n) + def apply(cond: Bool, n: Int): (UInt, Bool) = { + val c = new Counter(n) + var wrap: Bool = null + when (cond) { wrap = c.inc() } + (c.value, cond && wrap) + } +} -- cgit v1.2.3