make qlq output q | q_int
[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 """ jk latch
6
7 module jk(q,q1,j,k,c);
8 output q,q1;
9 input j,k,c;
10 reg q,q1;
11 initial begin q=1'b0; q1=1'b1; end
12 always @ (posedge c)
13 begin
14 case({j,k})
15 {1'b0,1'b0}:begin q=q; q1=q1; end
16 {1'b0,1'b1}: begin q=1'b0; q1=1'b1; end
17 {1'b1,1'b0}:begin q=1'b1; q1=1'b0; end
18 {1'b1,1'b1}: begin q=~q; q1=~q1; end
19 endcase
20 end
21 endmodule
22 """
23
24 def latchregister(m, incoming, outgoing, settrue):
25 reg = Signal.like(incoming) # make register same as input. reset is OK.
26 with m.If(settrue):
27 m.d.sync += reg.eq(incoming) # latch input into register
28 m.d.comb += outgoing.eq(incoming) # return input (combinatorial)
29 with m.Else():
30 m.d.comb += outgoing.eq(reg) # return input (combinatorial)
31
32
33 class SRLatch(Elaboratable):
34 def __init__(self, sync=True):
35 self.sync = sync
36 self.s = Signal(reset=0)
37 self.r = Signal(reset=1) # defaults to off
38 self.q = Signal(reset_less=True)
39 self.qn = Signal(reset_less=True)
40 self.qlq = Signal(reset_less=True)
41
42 def elaborate(self, platform):
43 m = Module()
44 q_int = Signal()
45
46 if self.sync:
47 with m.If(self.s):
48 m.d.sync += q_int.eq(1)
49 with m.Elif(self.r):
50 m.d.sync += q_int.eq(0)
51 with m.Else():
52 m.d.sync += q_int.eq(q_int)
53 m.d.comb += self.q.eq(q_int)
54 else:
55 with m.If(self.s):
56 m.d.sync += q_int.eq(1)
57 m.d.comb += self.q.eq(1)
58 with m.Elif(self.r):
59 m.d.sync += q_int.eq(0)
60 m.d.comb += self.q.eq(0)
61 with m.Else():
62 m.d.sync += q_int.eq(q_int)
63 m.d.comb += self.q.eq(q_int)
64 m.d.comb += self.qn.eq(~self.q)
65 m.d.comb += self.qlq.eq(self.q | q_int) # useful output
66
67 return m
68
69 def ports(self):
70 return self.s, self.r, self.q, self.qn
71
72
73 def sr_sim(dut):
74 yield dut.s.eq(0)
75 yield dut.r.eq(0)
76 yield
77 yield
78 yield
79 yield dut.s.eq(1)
80 yield
81 yield
82 yield
83 yield dut.s.eq(0)
84 yield
85 yield
86 yield
87 yield dut.r.eq(1)
88 yield
89 yield
90 yield
91 yield dut.r.eq(0)
92 yield
93 yield
94 yield
95
96 def test_sr():
97 dut = SRLatch()
98 vl = rtlil.convert(dut, ports=dut.ports())
99 with open("test_srlatch.il", "w") as f:
100 f.write(vl)
101
102 run_simulation(dut, sr_sim(dut), vcd_name='test_srlatch.vcd')
103
104 dut = SRLatch(sync=False)
105 vl = rtlil.convert(dut, ports=dut.ports())
106 with open("test_srlatch_async.il", "w") as f:
107 f.write(vl)
108
109 run_simulation(dut, sr_sim(dut), vcd_name='test_srlatch_async.vcd')
110
111 if __name__ == '__main__':
112 test_sr()