File size: 12,284 Bytes
f5dbfe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
from amaranth import *
from amaranth.sim import Simulator
from amaranth.lib.wiring import Component, In, Out
from amaranth.lib.cdc import FFSynchronizer

from registers2 import *

from sandbox.fanuc_encoder_sim import rs422_sim

import math



class Fanuc_Encoders(Component):
    # Fanuc encoders interface
    # currently only supports rs422 encoders


    def __init__(self, number_of_encoders: int):

        assert(number_of_encoders > 0 and number_of_encoders <= 32)

        self.number_of_encoders = number_of_encoders

        super().__init__({
            "tx" : Out(self.number_of_encoders),
            "tx_enable" : Out(self.number_of_encoders),
            "rx" : In(self.number_of_encoders),

            "bram_address": In(16),
            "bram_write_data": In(32),
            "bram_read_data": Out(32),
            "bram_write_enable": In(1),

            "debug": Out(8)
        })

        # setup registers for DMA access
        driver_settings = {}
        self.rm = RegisterMapGenerator("fanuc_encoders", ["fanuc_encoders"], driver_settings, "Fanuc serial encoder interface")
        self.encoder_group = Group("encoder", self.number_of_encoders, 0x0, "Group of registers for each encoder")
        self.encoder_group.add(Register("multiturn_count", rw="r", type="unsigned", width=32, desc="Absolute multiturn count"))      # not scaled, typically only 16 bits are used
        self.encoder_group.add(Register("singleturn_count", rw="r", type="unsigned", width=32, desc="Absolute (after index) singleturn count"))    # scaled to 32 bits
        self.encoder_group.add(Register("commutation_count", rw="r", type="unsigned", width=16, desc="Absolute commutation count"))   # scaled to 16 bits
        
        self.encoder_group.add(Register("status", rw="r", desc="Encoder status", sub_registers=[
            Register("battery_fail", type="bool", desc="Battery fail"),
            Register("unindexed", type="bool", desc="Unindexed"),
            Register("no_response", type="bool", desc="No response"),
            Register("crc_fail", type="bool", desc="CRC fail"),
            Register("done", type="bool", desc="Done"),
        ]))

        self.rm.add(Register("trigger", rw="w", type="bool", desc="Trigger encoder capture"))

        self.rm.add(self.encoder_group)
        self.rm.generate()

        self.encoders = []

    def elaborate(self, platform):
        m = Module()
        self.synced_rx = Signal(self.number_of_encoders)

        m.submodules.request_pulse = request_pulse = Request_Pulse()

        m.submodules += FFSynchronizer(i=self.rx, o=self.synced_rx, o_domain="sync_100")
        
        m.d.comb += self.tx_enable.eq(0xffffffff)   # enable all transmitters
        m.d.comb += self.tx.eq(request_pulse.req.replicate(self.number_of_encoders))   # request pulse to all transmitters

        for i in range(self.number_of_encoders):
            receiver = Fanuc_rs422_Receiver()
            m.submodules[f"receiver_{i}"] = receiver
            self.encoders.append(receiver)

            m.d.comb += receiver.rx.eq(self.synced_rx[i])
            m.d.comb += receiver.trigger.eq(request_pulse.trigger)


        # system regs
        with m.If(self.bram_write_enable & (self.bram_address == self.rm.trigger.address_offset)):
            m.d.sync_100 += request_pulse.trigger.eq(1)
        with m.Else():
            m.d.sync_100 += request_pulse.trigger.eq(0)


        # encoder regs

        encoder_address_lsb = int(math.log2(self.rm.encoder.alignment)) # TODO: add otion to get these directly from the register map
        encoder_address_msb = int(math.log2(self.rm.encoder.count)) + encoder_address_lsb + 1

        for index, e in enumerate(self.encoders):
            
            with m.If(self.bram_address[encoder_address_lsb:encoder_address_msb] == index<<encoder_address_lsb):  # selected the encoder
                # TODO: add a way to create these switches automatically from the register map
                with m.Switch(self.bram_address[0:encoder_address_lsb]):
                    with m.Case(self.rm.encoder.multiturn_count.address_offset):
                        m.d.sync_100 += self.bram_read_data.eq(e.multiturn_count)
                    with m.Case(self.rm.encoder.singleturn_count.address_offset):
                        m.d.sync_100 += self.bram_read_data.eq(e.singleturn_count<<16)
                    with m.Case(self.rm.encoder.commutation_count.address_offset):
                        m.d.sync_100 += self.bram_read_data.eq(e.commutation_count<<6)
                    with m.Case(self.rm.encoder.status.address_offset):
                        m.d.sync_100 += self.bram_read_data[self.rm.encoder.status.battery_fail.starting_bit].eq(e.battery_fail)
                        m.d.sync_100 += self.bram_read_data[self.rm.encoder.status.no_response.starting_bit].eq(e.no_response)
                        m.d.sync_100 += self.bram_read_data[self.rm.encoder.status.crc_fail.starting_bit].eq(e.crc_fail)
                        m.d.sync_100 += self.bram_read_data[self.rm.encoder.status.done.starting_bit].eq(e.done)
                        m.d.sync_100 += self.bram_read_data[self.rm.encoder.status.unindexed.starting_bit].eq(e.unindexed)
                    with m.Default():
                        m.d.sync_100 += self.bram_read_data.eq(0) 


        return m

class Request_Pulse(Component):

    def __init__(self):
        self.pulse_width = int(8e-6 * 100e6)  # 8us pulse

        super().__init__({
            "trigger": In(1),
            "req": Out(1)
        })
    
    def elaborate(self, platform):
        m = Module()

        cnt = Signal(range(self.pulse_width))

        m.d.sync_100 += cnt.eq(cnt + 1)

        with m.FSM(init="idle", domain="sync_100"):
            with m.State("idle"):
                with m.If(self.trigger):
                    m.d.sync_100 += cnt.eq(0)
                    m.d.sync_100 += self.req.eq(1)
                    m.next = "pulse"

            with m.State("pulse"):
                with m.If(cnt == self.pulse_width - 1):
                    m.d.sync_100 += self.req.eq(0)
                    with m.If(~self.trigger):   # wait until trigger resets to prevent multiple pulses
                        m.next = "idle"
                
                with m.Else():
                    m.d.sync_100 += cnt.eq(cnt + 1)

        return m

class Fanuc_rs422_CRC(Component):
    def __init__(self):
        super().__init__({
            'input': In(1),
            'strobe': In(1),
            'crc_ok': Out(1),
            'reset': In(1),
        })

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

        shreg = Signal(5)
        xor = Signal(5)

        m.d.comb += self.crc_ok.eq(shreg == 0)

        with m.If(shreg[-1]):
            m.d.comb += xor.eq(0b01011)

        with m.If(self.strobe):
            m.d.sync_100 += shreg.eq(Cat(self.input, shreg) ^ xor)

        with m.If(self.reset):
            m.d.sync_100 += shreg.eq(0)

        return m

class Fanuc_rs422_Receiver(Component):

    def __init__(self):
        self.bit_time = int(100e6 / 1024000) # 1.024M Baud

        self.capture = Signal()
        self.cnt = Signal(range(2 * self.bit_time))
        self.idx = Signal(range(96))
        self.state = Signal(3)

        
        self.input_prev = Signal()

        super().__init__({
            'rx': In(1),

            "trigger": In(1),

            "multiturn_count": Out(16),
            "singleturn_count": Out(16),
            "commutation_count": Out(10),
            "battery_fail": Out(1),
            "unindexed": Out(1),

            "no_response": Out(1),
            "crc_fail": Out(1),
            "done": Out(1),
        })

        self.input = self.rx

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

        m.submodules.crc = crc = Fanuc_rs422_CRC()

        

        m.d.sync_100 += self.input_prev.eq(self.input)

        buf = Array(Signal(name=f"buf_{_}") for _ in range(76))

        with m.If(self.trigger):
            m.d.sync_100 += self.no_response.eq(1)

        with m.FSM(init="WAIT_START", domain="sync_100"):
            with m.State('WAIT_START'):
                m.d.comb += self.state.eq(1)
                with m.If(self.input_prev & (~self.input)): # falling edge
                    m.d.sync_100 += self.done.eq(0)
                    m.d.sync_100 += self.no_response.eq(0)   # we got at least one edge
                    m.d.sync_100 += self.cnt.eq(self.bit_time + self.bit_time // 2 - 1)
                    m.d.sync_100 += self.idx.eq(0)
                    m.next = 'CAPTURE'

            with m.State('CAPTURE'):
                m.d.comb += self.state.eq(2)

                with m.If(self.trigger):    # reset on trigger
                    m.next = 'WAIT_START'

                with m.If(self.cnt == 0):
                    m.d.comb += self.capture.eq(1)
                    m.d.sync_100 += self.cnt.eq(self.bit_time - 1)
                    m.d.sync_100 += self.idx.eq(self.idx + 1)

                with m.Elif(self.input != self.input_prev):
                    m.d.sync_100 += self.cnt.eq(self.bit_time // 2 - 1)

                with m.Else():
                    m.d.sync_100 += self.cnt.eq(self.cnt - 1)

                with m.If(self.idx == 76):
                    m.next = 'DONE'

            with m.State('DONE'):
                m.d.comb += self.state.eq(3)
                m.d.sync_100 += self.done.eq(1)
                with m.If(self.no_response):    # no response
                    pass

                with m.Elif(~crc.crc_ok):   # crc fail
                    m.d.sync_100 += self.crc_fail.eq(1)

                with m.Else():  # valid response
                    m.d.sync_100 += self.crc_fail.eq(0)
                    
                    '''
                    bits 0..4 	constant : = 0b00101
                    bit  5     	1=battery fail
                    bits 6,7	unknown = 0b10,a860-360 0b00,a860-370 
                    bit  8		1=un-indexed
                    bits 9..17	unknown, perhaps for higher res encoders
                    bits 18..33	16 bit absolute encoder data (0..65535 for one turn)
                    bits 34..35     unknown = 0b01
                    bits 36..51	16 bit absolute turns count
                    bits 52,53	unknown = 0b01
                    bits 54..63	10 bit absolute commutation encoder (four 0->1023 cycles per turn) (is it always 4 or is it matched to the motor poles?)
                    '''
                    m.d.sync_100 += [
                        self.multiturn_count.eq(Cat(buf[36:52])),
                        self.singleturn_count.eq(Cat(buf[18:34])),
                        self.commutation_count.eq(Cat(buf[54:64])),
                        self.battery_fail.eq(Cat(buf[5])),
                        self.unindexed.eq(Cat(buf[8])),
                    ]

                with m.If(~self.trigger):   # wait until trigger resets to prevent freerunning
                    m.next = "WAIT_START"
        
        with m.If(self.capture):
            m.d.sync_100 += buf[self.idx].eq(self.input)

        m.d.comb += [
            crc.input.eq(self.input),
            crc.strobe.eq(self.capture),
            crc.reset.eq(self.done),
        ]

        # with m.If(done):
        #     m.d.sync_100 += [
        #         self.raw.eq(Cat(buf)),
        #     ]

        return m
    



dut = Fanuc_Encoders(6)
test_encoder = rs422_sim("controller-firmware/python/src/sandbox/fanuc_encoder_rs422.csv", 100e6)

async def bench(ctx):

    for i in range(2):

        # trigger the request pulse
        await ctx.tick("sync_100").repeat(10)
        ctx.set(dut.trigger, 1)
        await ctx.tick("sync_100")
        ctx.set(dut.trigger, 0)

        #test_encoder.inject_error()

        for j in range(int(100e-6 / (1/100e6))):
            test_encoder.set_request_level(ctx.get(dut.tx[0]))
            ctx.set(dut.rx[0], test_encoder.get_tx_level())
            test_encoder.tick()
            await ctx.tick("sync_100")
    


if __name__ == "__main__":

    sim = Simulator(dut)
    #sim.add_clock(1/25e6, domain="sync_25")
    sim.add_clock(1/100e6, domain="sync_100")
    sim.add_testbench(bench)
    with sim.write_vcd("fanuc_encoders_test.vcd"):
        sim.run()