slightly simplify SRlatch
[ieee754fpu.git] / src / nmutil / latch.py
1 from nmigen.compat.sim import run_simulation
2 from nmigen.cli import verilog, rtlil
3 from nmigen import Signal, Module, Elaboratable
4
5
6 class SRLatch(Elaboratable):
7 def __init__(self, sync=True):
8 self.sync = sync
9 self.s = Signal(reset_less=True)
10 self.r = Signal(reset_less=True)
11 self.q = Signal(reset_less=True)
12 self.qn = Signal(reset_less=True)
13
14 def elaborate(self, platform):
15 m = Module()
16 q_int = Signal(reset_less=True)
17
18 if self.sync:
19 with m.If(self.s):
20 m.d.sync += q_int.eq(1)
21 with m.Elif(self.r):
22 m.d.sync += q_int.eq(0)
23 with m.Else():
24 m.d.sync += q_int.eq(q_int)
25 m.d.comb += self.q.eq(q_int)
26 else:
27 with m.If(self.s):
28 m.d.sync += q_int.eq(1)
29 m.d.comb += self.q.eq(1)
30 with m.Elif(self.r):
31 m.d.sync += q_int.eq(0)
32 m.d.comb += self.q.eq(0)
33 with m.Else():
34 m.d.sync += q_int.eq(q_int)
35 m.d.comb += self.q.eq(q_int)
36 m.d.comb += self.qn.eq(~self.q)
37
38 return m
39
40 def ports(self):
41 return self.s, self.r, self.q, self.qn
42
43
44 def sr_sim(dut):
45 yield dut.s.eq(0)
46 yield dut.r.eq(0)
47 yield
48 yield
49 yield
50 yield dut.s.eq(1)
51 yield
52 yield
53 yield
54 yield dut.s.eq(0)
55 yield
56 yield
57 yield
58 yield dut.r.eq(1)
59 yield
60 yield
61 yield
62 yield dut.r.eq(0)
63 yield
64 yield
65 yield
66
67 def test_sr():
68 dut = SRLatch()
69 vl = rtlil.convert(dut, ports=dut.ports())
70 with open("test_srlatch.il", "w") as f:
71 f.write(vl)
72
73 run_simulation(dut, sr_sim(dut), vcd_name='test_srlatch.vcd')
74
75 dut = SRLatch(sync=False)
76 vl = rtlil.convert(dut, ports=dut.ports())
77 with open("test_srlatch_async.il", "w") as f:
78 f.write(vl)
79
80 run_simulation(dut, sr_sim(dut), vcd_name='test_srlatch_async.vcd')
81
82 if __name__ == '__main__':
83 test_sr()