debounce.py

Pasted by zyp on Wed Jul 16 21:52:59 2025 UTC as Python
from amaranth import *
from amaranth.lib import wiring

class Debounce(wiring.Component):
    i: wiring.In(1)
    o: wiring.Out(1)

    def __init__(self, cycles):
        super().__init__()
        self._cycles = cycles

    def elaborate(self, platform):
        m = Module()

        cnt = Signal(range(self._cycles + 1))

        with m.If(cnt > 0):
            m.d.sync += cnt.eq(cnt - 1)

        with m.Elif(self.o != self.i):
            m.d.sync += self.o.eq(self.i)
            m.d.sync += cnt.eq(self._cycles)

        return m