Skip to content

Instantly share code, notes, and snippets.

@ianloic
Created April 19, 2020 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianloic/97b22c5d400bd11a99ed4b2419442085 to your computer and use it in GitHub Desktop.
Save ianloic/97b22c5d400bd11a99ed4b2419442085 to your computer and use it in GitHub Desktop.
import typing, math
from nmigen import *
from nmigen.build import Platform
from nmigen.back.pysim import Simulator, Delay
class Pulse(Elaboratable):
def __init__(self,
frequency: float,
clock_frequency: typing.Optional[float],
fractional_bits: int = 16):
self.output = Signal(name='output')
self.frequency = frequency
self.clock_frequency = clock_frequency
self.fractional_bits = fractional_bits
def elaborate(self, platform: typing.Optional[Platform]) -> Module:
assert self.clock_frequency != None or (
platform != None and platform.default_clk_frequency != None)
clock_frequency = self.clock_frequency or platform.default_clk_frequency
assert clock_frequency > self.frequency
integer_bits = math.ceil(clock_frequency / self.frequency).bit_length()
bits = integer_bits + self.fractional_bits
increment = Const(round(self.frequency * 2**bits / clock_frequency))
accumulator = Signal(unsigned(bits), name='accumulator')
m = Module()
m.d.comb += self.output.eq(accumulator < increment)
m.d.sync += accumulator.eq(accumulator + increment)
return m
if __name__ == '__main__':
m = Pulse(frequency=1_000, clock_frequency=1_000_000)
def process():
yield Delay(0.1)
sim = Simulator(m)
sim.add_clock(1.0 / 1_000_000)
sim.add_process(process)
with sim.write_vcd("pulse.vcd", "pulse.gtkw", traces=[m.output]):
sim.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment