Created
April 19, 2020 23:18
-
-
Save ianloic/97b22c5d400bd11a99ed4b2419442085 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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