From 0f9df2d7322a88cbbe1c25dfcac45f9fd4ed75d8 Mon Sep 17 00:00:00 2001 From: Sebastien Bourdeauducq Date: Wed, 24 Apr 2013 19:13:36 +0200 Subject: [PATCH] genlib: add Gray counter --- examples/basic/graycounter.py | 19 +++++++++++++++++++ migen/genlib/cdc.py | 24 ++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 examples/basic/graycounter.py diff --git a/examples/basic/graycounter.py b/examples/basic/graycounter.py new file mode 100644 index 00000000..bfc30f56 --- /dev/null +++ b/examples/basic/graycounter.py @@ -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) diff --git a/migen/genlib/cdc.py b/migen/genlib/cdc.py index 04b1b850..13612cfe 100644 --- a/migen/genlib/cdc.py +++ b/migen/genlib/cdc.py @@ -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) + ] -- 2.30.2