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.
72 # The output consists of a (Python) list of I2C "packets", each of which
73 # has an (implicit) index number (its index in the list).
74 # Each packet consists of a Python dict with certain key/value pairs.
76 # TODO: Make this a list later instead of a dict?
79 # - 'S' (START condition)
80 # - 'Sr' (Repeated START)
81 # - 'AR' (Address, read)
82 # - 'AW' (Address, write)
84 # - 'DW' (Data, write)
85 # - 'P' (STOP condition)
86 # 'range': (tuple of 2 integers, the min/max samplenumber of this range)
88 # - min/max can also be identical.
89 # 'data': (actual data as integer ???) TODO: This can be very variable...
90 # 'ann': (string; additional annotations / comments)
93 # [{'type': 'S', 'range': (150, 160), 'data': None, 'ann': 'Foobar'},
94 # {'type': 'AW', 'range': (200, 300), 'data': 0x50, 'ann': 'Slave 4'},
95 # {'type': 'DW', 'range': (310, 370), 'data': 0x00, 'ann': 'Init cmd'},
96 # {'type': 'AR', 'range': (500, 560), 'data': 0x50, 'ann': 'Get stat'},
97 # {'type': 'DR', 'range': (580, 640), 'data': 0xfe, 'ann': 'OK'},
98 # {'type': 'P', 'range': (650, 660), 'data': None, 'ann': None}]
100 # Possible other events:
101 # - Error event in case protocol looks broken:
102 # [{'type': 'ERROR', 'range': (min, max),
103 # 'data': TODO, 'ann': 'This is not a Microchip 24XX64 EEPROM'},
104 # [{'type': 'ERROR', 'range': (min, max),
105 # 'data': TODO, 'ann': 'TODO'},
106 # - TODO: Make list of possible errors accessible as metadata?
108 # TODO: I2C address of slaves.
109 # TODO: Handle multiple different I2C devices on same bus
110 # -> we need to decode multiple protocols at the same time.
111 # TODO: range: Always contiguous? Splitted ranges? Multiple per event?
118 # [[id, channel, description], ...] # TODO
121 # {'id': 'SCL', 'ch': 5, 'desc': 'Serial clock line'}
122 # {'id': 'SDA', 'ch': 7, 'desc': 'Serial data line'}
126 # 'signals': [{'SCL': }]}
131 # symbols for i2c decoders up the stack
148 def __init__(self, data):
150 def probe(self, probe):
151 s = ord(self.data[probe / 8]) & (1 << (probe % 8))
152 return True if s else False
154 def sampleiter(data, unitsize):
155 for i in range(0, len(data), unitsize):
156 yield(Sample(data[i:i+unitsize]))
158 class Decoder(sigrok.Decoder):
161 longname = 'Inter-Integrated Circuit (I2C) bus'
162 desc = 'I2C is a two-wire, multi-master, serial bus.'
164 author = 'Uwe Hermann'
165 email = 'uwe@hermann-uwe.de'
170 'scl': {'ch': 0, 'name': 'SCL', 'desc': 'Serial clock line'},
171 'sda': {'ch': 1, 'name': 'SDA', 'desc': 'Serial data line'},
174 'address-space': ['Address space (in bits)', 7],
177 def __init__(self, **kwargs):
178 self.probes = Decoder.probes.copy()
179 self.output_protocol = None
180 self.output_annotation = None
182 # TODO: Don't hardcode the number of channels.
189 self.startsample = -1
190 self.is_repeat_start = 0
192 self.state = FIND_START
194 # Get the channel/probe number of the SCL/SDA signals.
195 self.scl_bit = self.probes['scl']['ch']
196 self.sda_bit = self.probes['sda']['ch']
201 def start(self, metadata):
202 self.unitsize = metadata["unitsize"]
203 self.output_protocol = self.output_new(2)
204 self.output_annotation = self.output_new(1)
209 def is_start_condition(self, scl, sda):
210 """START condition (S): SDA = falling, SCL = high"""
211 if (self.oldsda == 1 and sda == 0) and scl == 1:
215 def is_data_bit(self, scl, sda):
216 """Data sampling of receiver: SCL = rising"""
217 if self.oldscl == 0 and scl == 1:
221 def is_stop_condition(self, scl, sda):
222 """STOP condition (P): SDA = rising, SCL = high"""
223 if (self.oldsda == 0 and sda == 1) and scl == 1:
227 def found_start(self, scl, sda):
228 if self.is_repeat_start == 1:
229 out_proto = [ START_REPEAT ]
230 out_ann = [ "START REPEAT" ]
232 out_proto = [ START ]
233 out_ann = [ "START" ]
234 self.put(self.output_protocol, out_proto)
235 self.put(self.output_annotation, out_ann)
237 self.state = FIND_ADDRESS
238 self.bitcount = self.databyte = 0
239 self.is_repeat_start = 1
242 def found_address_or_data(self, scl, sda):
243 """Gather 8 bits of data plus the ACK/NACK bit."""
245 if self.startsample == -1:
246 self.startsample = self.samplenum
249 # Address and data are transmitted MSB-first.
253 # Return if we haven't collected all 8 + 1 bits, yet.
254 if self.bitcount != 9:
257 # We received 8 address/data bits and the ACK/NACK bit.
258 self.databyte >>= 1 # Shift out unwanted ACK/NACK bit here.
260 if self.state == FIND_ADDRESS:
261 d = self.databyte & 0xfe
262 # The READ/WRITE bit is only in address bytes, not data bytes.
263 self.wr = 1 if (self.databyte & 1) else 0
264 elif self.state == FIND_DATA:
273 if self.state == FIND_ADDRESS and self.wr == 1:
275 ann = 'ADDRESS WRITE'
276 elif self.state == FIND_ADDRESS and self.wr == 0:
279 elif self.state == FIND_DATA and self.wr == 1:
282 elif self.state == FIND_DATA and self.wr == 0:
285 out_proto.append( [cmd, d] )
286 out_ann.append( ["%s" % ann, "0x%02x" % d] )
289 out_proto.append( [NACK] )
290 out_ann.append( ["NACK"] )
292 out_proto.append( [ACK] )
293 out_ann.append( ["ACK"] )
295 self.put(self.output_protocol, out_proto)
296 self.put(self.output_annotation, out_ann)
298 self.bitcount = self.databyte = 0
299 self.startsample = -1
301 if self.state == FIND_ADDRESS:
302 self.state = FIND_DATA
303 elif self.state == FIND_DATA:
304 # There could be multiple data bytes in a row.
305 # So, either find a STOP condition or another data byte next.
308 def found_stop(self, scl, sda):
309 self.put(self.output_protocol, [ STOP ])
310 self.put(self.output_annotation, [ "STOP" ])
312 self.state = FIND_START
313 self.is_repeat_start = 0
316 def put(self, output_id, data):
317 timeoffset = self.timeoffset + ((self.samplenum - self.bitcount) * self.period)
318 if self.bitcount > 0:
319 duration = self.bitcount * self.period
321 duration = self.period
322 print "**", timeoffset, duration
323 super(Decoder, self).put(timeoffset, duration, output_id, data)
325 def decode(self, timeoffset, duration, data):
326 """I2C protocol decoder"""
328 self.timeoffset = timeoffset
329 self.duration = duration
330 print "++", timeoffset, duration, len(data)
331 # duration of one bit in ps, only valid for this call to decode()
332 self.period = duration / len(data)
334 # We should accept a list of samples and iterate...
335 for sample in sampleiter(data, self.unitsize):
337 # TODO: Eliminate the need for ord().
340 # TODO: Start counting at 0 or 1?
343 # First sample: Save SCL/SDA value.
344 if self.oldscl == None:
345 # Get SCL/SDA bit values (0/1 for low/high) of the first sample.
346 self.oldscl = (s & (1 << self.scl_bit)) >> self.scl_bit
347 self.oldsda = (s & (1 << self.sda_bit)) >> self.sda_bit
350 # Get SCL/SDA bit values (0/1 for low/high).
351 scl = (s & (1 << self.scl_bit)) >> self.scl_bit
352 sda = (s & (1 << self.sda_bit)) >> self.sda_bit
354 # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
357 if self.state == FIND_START:
358 if self.is_start_condition(scl, sda):
359 self.found_start(scl, sda)
360 elif self.state == FIND_ADDRESS:
361 if self.is_data_bit(scl, sda):
362 self.found_address_or_data(scl, sda)
363 elif self.state == FIND_DATA:
364 if self.is_data_bit(scl, sda):
365 self.found_address_or_data(scl, sda)
366 elif self.is_start_condition(scl, sda):
367 self.found_start(scl, sda)
368 elif self.is_stop_condition(scl, sda):
369 self.found_stop(scl, sda)
374 # Save current SDA/SCL values for the next round.