2 ## This file is part of the sigrok project.
4 ## Copyright (C) 2010-2011 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, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 # I2C protocol decoder
26 # The Inter-Integrated Circuit (I2C) bus is a bidirectional, multi-master
27 # bus using two signals (SCL = serial clock line, SDA = serial data line).
29 # There can be many devices on the same bus. Each device can potentially be
30 # master or slave (and that can change during runtime). Both slave and master
31 # can potentially play the transmitter or receiver role (this can also
34 # Possible maximum data rates:
35 # - Standard mode: 100 kbit/s
36 # - Fast mode: 400 kbit/s
37 # - Fast-mode Plus: 1 Mbit/s
38 # - High-speed mode: 3.4 Mbit/s
40 # START condition (S): SDA = falling, SCL = high
41 # Repeated START condition (Sr): same as S
42 # Data bit sampling: SCL = rising
43 # STOP condition (P): SDA = rising, SCL = high
45 # All data bytes on SDA are exactly 8 bits long (transmitted MSB-first).
46 # Each byte has to be followed by a 9th ACK/NACK bit. If that bit is low,
47 # that indicates an ACK, if it's high that indicates a NACK.
49 # After the first START condition, a master sends the device address of the
50 # slave it wants to talk to. Slave addresses are 7 bits long (MSB-first).
51 # After those 7 bits, a data direction bit is sent. If the bit is low that
52 # indicates a WRITE operation, if it's high that indicates a READ operation.
54 # Later an optional 10bit slave addressing scheme was added.
57 # http://www.nxp.com/acrobat/literature/9398/39340011.pdf (v2.1 spec)
58 # http://www.nxp.com/acrobat/usermanuals/UM10204_3.pdf (v3 spec)
59 # http://en.wikipedia.org/wiki/I2C
62 # TODO: Look into arbitration, collision detection, clock synchronisation, etc.
63 # TODO: Handle clock stretching.
64 # TODO: Handle combined messages / repeated START.
65 # TODO: Implement support for 7bit and 10bit slave addresses.
66 # TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
67 # TODO: Implement support for detecting various bus errors.
68 # TODO: I2C address of slaves.
69 # TODO: Handle multiple different I2C devices on same bus
70 # -> we need to decode multiple protocols at the same time.
73 # I2C protocol output format:
75 # The protocol output consists of a (Python) list of I2C "packets", each of
76 # which is of the form
78 # [ _i2c_command_, _data_, _ack_bit_ ]
80 # _i2c_command_ is one of:
81 # - 'START' (START condition)
82 # - 'START_REPEAT' (Repeated START)
83 # - 'ADDRESS_READ' (Address, read)
84 # - 'ADDRESS_WRITE' (Address, write)
85 # - 'DATA_READ' (Data, read)
86 # - 'DATA_WRITE' (Data, write)
87 # - 'STOP' (STOP condition)
89 # _data_ is the data or address byte associated with the ADDRESS_* and DATA_*
90 # command. For START, START_REPEAT and STOP, this is None.
92 # _ack_bit_ is either 'ACK' or 'NACK', but may also be None.
96 import sigrokdecode as srd
98 # annotation feed formats
100 ANN_SHIFTED_SHORT = 1
103 # values are verbose and short annotation, respectively
105 'START': ['START', 'S'],
106 'START_REPEAT': ['START REPEAT', 'Sr'],
107 'STOP': ['STOP', 'P'],
109 'NACK': ['NACK', 'N'],
110 'ADDRESS_READ': ['ADDRESS READ', 'AR'],
111 'ADDRESS_WRITE': ['ADDRESS WRITE','AW'],
112 'DATA_READ': ['DATA READ', 'DR'],
113 'DATA_WRITE': ['DATA WRITE', 'DW'],
122 class Decoder(srd.Decoder):
125 longname = 'Inter-Integrated Circuit (I2C) bus'
126 desc = 'I2C is a two-wire, multi-master, serial bus.'
128 author = 'Uwe Hermann'
129 email = 'uwe@hermann-uwe.de'
134 {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
135 {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
138 'address-space': ['Address space (in bits)', 7],
142 ["7-bit shifted hex",
143 "Read/Write bit shifted out from the 8-bit i2c slave address"],
145 ["7-bit shifted hex (short)",
146 "Read/Write bit shifted out from the 8-bit i2c slave address"],
148 ["Raw hex", "Unaltered raw data"]
151 def __init__(self, **kwargs):
156 self.startsample = -1
157 self.is_repeat_start = 0
158 self.state = FIND_START
162 def start(self, metadata):
163 self.out_proto = self.add(srd.SRD_OUTPUT_PROTO, 'i2c')
164 self.out_ann = self.add(srd.SRD_OUTPUT_ANN, 'i2c')
169 def is_start_condition(self, scl, sda):
170 """START condition (S): SDA = falling, SCL = high"""
171 if (self.oldsda == 1 and sda == 0) and scl == 1:
175 def is_data_bit(self, scl, sda):
176 """Data sampling of receiver: SCL = rising"""
177 if self.oldscl == 0 and scl == 1:
181 def is_stop_condition(self, scl, sda):
182 """STOP condition (P): SDA = rising, SCL = high"""
183 if (self.oldsda == 0 and sda == 1) and scl == 1:
187 def found_start(self, scl, sda):
188 if self.is_repeat_start == 1:
192 self.put(self.out_proto, [ cmd, None, None ])
193 self.put(self.out_ann, [ ANN_SHIFTED, [protocol[cmd][0]] ])
194 self.put(self.out_ann, [ ANN_SHIFTED_SHORT, [protocol[cmd][1]] ])
196 self.state = FIND_ADDRESS
197 self.bitcount = self.databyte = 0
198 self.is_repeat_start = 1
201 def found_address_or_data(self, scl, sda):
202 """Gather 8 bits of data plus the ACK/NACK bit."""
204 if self.startsample == -1:
205 # TODO: should be samplenum, as received from the feed
206 self.startsample = self.samplecnt
209 # Address and data are transmitted MSB-first.
213 # Return if we haven't collected all 8 + 1 bits, yet.
214 if self.bitcount != 9:
217 # send raw output annotation before we start shifting out
218 # read/write and ack/nack bits
219 self.put(self.out_ann, [ANN_RAW, ["0x%.2x" % self.databyte]])
221 # We received 8 address/data bits and the ACK/NACK bit.
222 self.databyte >>= 1 # Shift out unwanted ACK/NACK bit here.
224 if self.state == FIND_ADDRESS:
225 # The READ/WRITE bit is only in address bytes, not data bytes.
226 if self.databyte & 1:
230 d = self.databyte >> 1
231 elif self.state == FIND_DATA:
237 # last bit that came in was the ACK/NACK bit (1 = NACK)
244 if self.state == FIND_ADDRESS and self.wr == 1:
245 cmd = 'ADDRESS_WRITE'
246 elif self.state == FIND_ADDRESS and self.wr == 0:
248 elif self.state == FIND_DATA and self.wr == 1:
250 elif self.state == FIND_DATA and self.wr == 0:
252 self.put(self.out_proto, [ cmd, d, ack_bit ] )
253 self.put(self.out_ann, [ANN_SHIFTED, [
254 "%s" % protocol[cmd][0],
256 "%s" % protocol[ack_bit][0]]
258 self.put(self.out_ann, [ANN_SHIFTED_SHORT, [
259 "%s" % protocol[cmd][1],
261 "%s" % protocol[ack_bit][1]]
264 self.bitcount = self.databyte = 0
265 self.startsample = -1
267 if self.state == FIND_ADDRESS:
268 self.state = FIND_DATA
269 elif self.state == FIND_DATA:
270 # There could be multiple data bytes in a row.
271 # So, either find a STOP condition or another data byte next.
274 def found_stop(self, scl, sda):
275 self.put(self.out_proto, [ 'STOP', None, None ])
276 self.put(self.out_ann, [ ANN_SHIFTED, [protocol['STOP'][0]] ])
277 self.put(self.out_ann, [ ANN_SHIFTED_SHORT, [protocol['STOP'][1]] ])
279 self.state = FIND_START
280 self.is_repeat_start = 0
283 def put(self, output_id, data):
284 # inject sample range into the call up to sigrok
285 # TODO: 0-0 sample range for now
286 super(Decoder, self).put(0, 0, output_id, data)
288 def decode(self, timeoffset, duration, data):
289 for samplenum, (scl, sda) in data:
292 # First sample: Save SCL/SDA value.
293 if self.oldscl == None:
298 # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
301 if self.state == FIND_START:
302 if self.is_start_condition(scl, sda):
303 self.found_start(scl, sda)
304 elif self.state == FIND_ADDRESS:
305 if self.is_data_bit(scl, sda):
306 self.found_address_or_data(scl, sda)
307 elif self.state == FIND_DATA:
308 if self.is_data_bit(scl, sda):
309 self.found_address_or_data(scl, sda)
310 elif self.is_start_condition(scl, sda):
311 self.found_start(scl, sda)
312 elif self.is_stop_condition(scl, sda):
313 self.found_stop(scl, sda)
318 # Save current SDA/SCL values for the next round.