summaryrefslogtreecommitdiff
path: root/src/main/scala/Chisel/util/Counter.scala
diff options
context:
space:
mode:
authorducky2015-10-26 17:30:15 -0700
committerPalmer Dabbelt2015-11-02 13:04:21 -0800
commit6c34949c45cf7ddfdabafb749de2cb9e439b381e (patch)
treeb4bcdd586123b571a2f53b6726e501003dd46119 /src/main/scala/Chisel/util/Counter.scala
parent178f5c564e9ab0594656185e2e0a5bcc029d5743 (diff)
Break out Utils.scala into smaller portions
Diffstat (limited to 'src/main/scala/Chisel/util/Counter.scala')
-rw-r--r--src/main/scala/Chisel/util/Counter.scala35
1 files changed, 35 insertions, 0 deletions
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)
+ }
+}