genlib: add Gray counter
authorSebastien Bourdeauducq <sebastien@milkymist.org>
Wed, 24 Apr 2013 17:13:36 +0000 (19:13 +0200)
committerSebastien Bourdeauducq <sebastien@milkymist.org>
Wed, 24 Apr 2013 17:13:36 +0000 (19:13 +0200)
examples/basic/graycounter.py [new file with mode: 0644]
migen/genlib/cdc.py

diff --git a/examples/basic/graycounter.py b/examples/basic/graycounter.py
new file mode 100644 (file)
index 0000000..bfc30f5
--- /dev/null
@@ -0,0 +1,19 @@
+from random import Random
+
+from migen.fhdl.module import Module
+from migen.genlib.cdc import GrayCounter
+from migen.sim.generic import Simulator
+
+class TB(Module):
+       def __init__(self, width=3):
+               self.width = width
+               self.submodules.gc = GrayCounter(self.width)
+               self.prng = Random(7345)
+
+       def do_simulation(self, s):
+               print("{0:0{1}b} CE={2}".format(s.rd(self.gc.q),
+                       self.width, s.rd(self.gc.ce)))
+               s.wr(self.gc.ce, self.prng.getrandbits(1))
+
+sim = Simulator(TB())
+sim.run(35)
index 04b1b8500977869eb5ed5c512ecc5d7f8b6d64e6..13612cfec5eedeed3d4c4fe3db52b9f1a4510bff 100644 (file)
@@ -1,4 +1,5 @@
 from migen.fhdl.structure import *
+from migen.fhdl.module import Module
 from migen.fhdl.specials import Special
 from migen.fhdl.tools import list_signals
 
@@ -71,3 +72,26 @@ class PulseSynchronizer:
                return Fragment(comb, 
                        {self.idomain: sync_i, self.odomain: sync_o},
                        specials={MultiReg(toggle_i, toggle_o, self.odomain)})
+
+class GrayCounter(Module):
+       def __init__(self, width):
+               self.ce = Signal()
+               self.q = Signal(width)
+               self.q_next = Signal(width)
+
+               ###
+
+               q_binary = Signal(width)
+               q_next_binary = Signal(width)
+               self.comb += [
+                       If(self.ce,
+                               q_next_binary.eq(q_binary + 1)
+                       ).Else(
+                               q_next_binary.eq(q_binary)
+                       ),
+                       self.q_next.eq(q_next_binary ^ q_next_binary[1:])
+               ]
+               self.sync += [
+                       q_binary.eq(q_next_binary),
+                       self.q.eq(self.q_next)
+               ]