2 ## This file is part of the libsigrokdecode project.
4 ## Copyright (C) 2010-2016 Uwe Hermann <uwe@hermann-uwe.de>
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
20 # TODO: Look into arbitration, collision detection, clock synchronisation, etc.
21 # TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
22 # TODO: Implement support for detecting various bus errors.
24 from common.srdhelper import bitpack_msb
25 import sigrokdecode as srd
34 - 'START' (START condition)
35 - 'START REPEAT' (Repeated START condition)
36 - 'ADDRESS READ' (Slave address, read)
37 - 'ADDRESS WRITE' (Slave address, write)
38 - 'DATA READ' (Data, read)
39 - 'DATA WRITE' (Data, write)
40 - 'STOP' (STOP condition)
43 - 'BITS' (<pdata>: list of data/address bits and their ss/es numbers)
45 <pdata> is the data or address byte associated with the 'ADDRESS*' and 'DATA*'
46 command. Slave addresses do not include bit 0 (the READ/WRITE indication bit).
47 For example, a slave address field could be 0x51 (instead of 0xa2).
48 For 'START', 'START REPEAT', 'STOP', 'ACK', and 'NACK' <pdata> is None.
51 # CMD: [annotation-type-index, long annotation, short annotation]
53 'START': [0, 'Start', 'S'],
54 'START REPEAT': [1, 'Start repeat', 'Sr'],
55 'STOP': [2, 'Stop', 'P'],
56 'ACK': [3, 'ACK', 'A'],
57 'NACK': [4, 'NACK', 'N'],
58 'BIT': [5, 'Bit', 'B'],
59 'ADDRESS READ': [6, 'Address read', 'AR'],
60 'ADDRESS WRITE': [7, 'Address write', 'AW'],
61 'DATA READ': [8, 'Data read', 'DR'],
62 'DATA WRITE': [9, 'Data write', 'DW'],
65 class Decoder(srd.Decoder):
69 longname = 'Inter-Integrated Circuit'
70 desc = 'Two-wire, multi-master, serial bus.'
74 tags = ['Embedded/industrial']
76 {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
77 {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
80 {'id': 'address_format', 'desc': 'Displayed slave address format',
81 'default': 'shifted', 'values': ('shifted', 'unshifted')},
84 ('start', 'Start condition'),
85 ('repeat-start', 'Repeat start condition'),
86 ('stop', 'Stop condition'),
89 ('bit', 'Data/address bit'),
90 ('address-read', 'Address read'),
91 ('address-write', 'Address write'),
92 ('data-read', 'Data read'),
93 ('data-write', 'Data write'),
94 ('warning', 'Warning'),
97 ('bits', 'Bits', (5,)),
98 ('addr-data', 'Address/data', (0, 1, 2, 3, 4, 6, 7, 8, 9)),
99 ('warnings', 'Warnings', (10,)),
102 ('address-read', 'Address read'),
103 ('address-write', 'Address write'),
104 ('data-read', 'Data read'),
105 ('data-write', 'Data write'),
112 self.samplerate = None
113 self.ss = self.es = self.ss_byte = -1
115 self.rem_addr_bytes = None
116 self.is_repeat_start = False
117 self.state = 'FIND START'
118 self.pdu_start = None
122 def metadata(self, key, value):
123 if key == srd.SRD_CONF_SAMPLERATE:
124 self.samplerate = value
127 self.out_python = self.register(srd.OUTPUT_PYTHON)
128 self.out_ann = self.register(srd.OUTPUT_ANN)
129 self.out_binary = self.register(srd.OUTPUT_BINARY)
130 self.out_bitrate = self.register(srd.OUTPUT_META,
131 meta=(int, 'Bitrate', 'Bitrate from Start bit to Stop bit'))
133 def putx(self, data):
134 self.put(self.ss, self.es, self.out_ann, data)
136 def putp(self, data):
137 self.put(self.ss, self.es, self.out_python, data)
139 def putb(self, data):
140 self.put(self.ss, self.es, self.out_binary, data)
142 def handle_start(self, pins):
143 self.ss, self.es = self.samplenum, self.samplenum
144 self.pdu_start = self.samplenum
146 cmd = 'START REPEAT' if self.is_repeat_start else 'START'
147 self.putp([cmd, None])
148 self.putx([proto[cmd][0], proto[cmd][1:]])
149 self.state = 'FIND ADDRESS'
150 self.is_repeat_start = True
152 self.rem_addr_bytes = None
153 self.data_bits.clear()
155 # Gather 8 bits of data plus the ACK/NACK bit.
156 def handle_address_or_data(self, pins):
160 # Accumulate a byte's bits, including its start position.
161 # Accumulate individual bits and their start/end sample numbers
162 # as we see them. Get the start sample number at the time when
163 # the bit value gets sampled. Assume the start of the next bit
164 # as the end sample number of the previous bit. Guess the last
165 # bit's end sample number from the second last bit's width.
166 # (gsi: Shouldn't falling SCL be the end of the bit value?)
167 # Keep the bits in receive order (MSB first) during accumulation.
168 if not self.data_bits:
169 self.ss_byte = self.samplenum
171 self.data_bits[-1][2] = self.samplenum
172 self.data_bits.append([sda, self.samplenum, self.samplenum])
173 if len(self.data_bits) < 8:
175 self.bitwidth = self.data_bits[-2][2] - self.data_bits[-3][2]
176 self.data_bits[-1][2] += self.bitwidth
178 # Get the byte value. Address and data are transmitted MSB-first.
179 d = bitpack_msb(self.data_bits, 0)
180 if self.state == 'FIND ADDRESS':
181 # The READ/WRITE bit is only in the first address byte, not
182 # in data bytes. Address bit pattern 0b1111_0xxx means that
183 # this is a 10bit slave address, another byte follows. Get
184 # the R/W direction and the address bytes count from the
185 # first byte in the I2C transfer.
187 if self.rem_addr_bytes is None:
188 if (addr_byte & 0xf8) == 0xf0:
189 self.rem_addr_bytes = 2
190 self.slave_addr_7 = None
191 self.slave_addr_10 = addr_byte & 0x06
192 self.slave_addr_10 <<= 7
194 self.rem_addr_bytes = 1
195 self.slave_addr_7 = addr_byte >> 1
196 self.slave_addr_10 = None
197 is_seven = self.slave_addr_7 is not None
198 if self.is_write is None:
199 read_bit = bool(addr_byte & 1)
200 shift_seven = self.options['address_format'] == 'shifted'
201 if is_seven and shift_seven:
203 self.is_write = False if read_bit else True
205 self.slave_addr_10 |= addr_byte
208 if self.state == 'FIND ADDRESS' and self.is_write:
209 cmd = 'ADDRESS WRITE'
211 elif self.state == 'FIND ADDRESS' and not self.is_write:
214 elif self.state == 'FIND DATA' and self.is_write:
217 elif self.state == 'FIND DATA' and not self.is_write:
221 self.ss, self.es = self.ss_byte, self.samplenum + self.bitwidth
223 # Reverse the list of bits to LSB first order before emitting
224 # annotations and passing bits to upper layers. This may be
225 # unexpected because the protocol is MSB first, but it keeps
226 # backwards compatibility.
227 self.data_bits.reverse()
228 self.putp(['BITS', self.data_bits])
231 self.putb([bin_class, bytes([d])])
233 for bit in self.data_bits:
234 self.put(bit[1], bit[2], self.out_ann, [5, ['%d' % bit[0]]])
236 if cmd.startswith('ADDRESS') and is_seven:
237 self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth
238 w = ['Write', 'Wr', 'W'] if self.is_write else ['Read', 'Rd', 'R']
239 self.putx([proto[cmd][0], w])
240 self.ss, self.es = self.ss_byte, self.samplenum
242 self.putx([proto[cmd][0], ['%s: %02X' % (proto[cmd][1], d),
243 '%s: %02X' % (proto[cmd][2], d), '%02X' % d]])
245 # Done with this packet.
246 self.data_bits.clear()
247 self.state = 'FIND ACK'
249 def get_ack(self, pins):
251 self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth
252 cmd = 'NACK' if (sda == 1) else 'ACK'
253 self.putp([cmd, None])
254 self.putx([proto[cmd][0], proto[cmd][1:]])
255 # Slave addresses can span one or two bytes, before data bytes
256 # follow. There can be an arbitrary number of data bytes. Stick
257 # with getting more address bytes if applicable, or enter or
258 # remain in the data phase of the transfer otherwise.
259 if self.rem_addr_bytes:
260 self.rem_addr_bytes -= 1
261 if self.rem_addr_bytes:
262 self.state = 'FIND ADDRESS'
264 self.state = 'FIND DATA'
266 def handle_stop(self, pins):
269 elapsed = 1 / float(self.samplerate) * (self.samplenum - self.pdu_start + 1)
270 bitrate = int(1 / elapsed * self.pdu_bits)
271 self.put(self.ss_byte, self.samplenum, self.out_bitrate, bitrate)
274 self.ss, self.es = self.samplenum, self.samplenum
275 self.putp([cmd, None])
276 self.putx([proto[cmd][0], proto[cmd][1:]])
277 self.state = 'FIND START'
278 self.is_repeat_start = False
280 self.data_bits.clear()
285 if self.state == 'FIND START':
286 # Wait for a START condition (S): SCL = high, SDA = falling.
287 self.handle_start(self.wait({0: 'h', 1: 'f'}))
288 elif self.state == 'FIND ADDRESS':
289 # Wait for a data bit: SCL = rising.
290 self.handle_address_or_data(self.wait({0: 'r'}))
291 elif self.state == 'FIND DATA':
292 # Wait for any of the following conditions (or combinations):
293 # a) Data sampling of receiver: SCL = rising, and/or
294 # b) START condition (S): SCL = high, SDA = falling, and/or
295 # c) STOP condition (P): SCL = high, SDA = rising
296 pins = self.wait([{0: 'r'}, {0: 'h', 1: 'f'}, {0: 'h', 1: 'r'}])
298 # Check which of the condition(s) matched and handle them.
300 self.handle_address_or_data(pins)
301 elif self.matched[1]:
302 self.handle_start(pins)
303 elif self.matched[2]:
304 self.handle_stop(pins)
305 elif self.state == 'FIND ACK':
306 # Wait for a data/ack bit: SCL = rising.
307 self.get_ack(self.wait({0: 'r'}))