2 ## This file is part of the sigrok project.
4 ## Copyright (C) 2010 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 # STOP condition (P): SDA = rising, SCL = high
44 # All data bytes on SDA are exactly 8 bits long (transmitted MSB-first).
45 # Each byte has to be followed by a 9th ACK/NACK bit. If that bit is low,
46 # that indicates an ACK, if it's high that indicates a NACK.
48 # After the first START condition, a master sends the device address of the
49 # slave it wants to talk to. Slave addresses are 7 bits long (MSB-first).
50 # After those 7 bits, a data direction bit is sent. If the bit is low that
51 # indicates a WRITE operation, if it's high that indicates a READ operation.
53 # Later an optional 10bit slave addressing scheme was added.
56 # http://www.nxp.com/acrobat/literature/9398/39340011.pdf (v2.1 spec)
57 # http://www.nxp.com/acrobat/usermanuals/UM10204_3.pdf (v3 spec)
58 # http://en.wikipedia.org/wiki/I2C
61 # TODO: Look into arbitration, collision detection, clock synchronisation, etc.
62 # TODO: Handle clock stretching.
63 # TODO: Handle combined messages / repeated START.
64 # TODO: Implement support for 7bit and 10bit slave addresses.
65 # TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
66 # TODO: Implement support for detecting various bus errors.
71 # The output consists of a (Python) list of I2C "packets", each of which
72 # has an (implicit) index number (its index in the list).
73 # Each packet consists of a Python dict with certain key/value pairs.
75 # TODO: Make this a list later instead of a dict?
78 # - 'S' (START condition)
79 # - 'Sr' (Repeated START)
80 # - 'AR' (Address, read)
81 # - 'AW' (Address, write)
83 # - 'DW' (Data, write)
84 # - 'P' (STOP condition)
85 # 'range': (tuple of 2 integers, the min/max samplenumber of this range)
87 # - min/max can also be identical.
88 # 'data': (actual data as integer ???) TODO: This can be very variable...
89 # 'ann': (string; additional annotations / comments)
92 # [{'type': 'S', 'range': (150, 160), 'data': None, 'ann': 'Foobar'},
93 # {'type': 'AW', 'range': (200, 300), 'data': 0x50, 'ann': 'Slave 4'},
94 # {'type': 'DW', 'range': (310, 370), 'data': 0x00, 'ann': 'Init cmd'},
95 # {'type': 'AR', 'range': (500, 560), 'data': 0x50, 'ann': 'Get stat'},
96 # {'type': 'DR', 'range': (580, 640), 'data': 0xfe, 'ann': 'OK'},
97 # {'type': 'P', 'range': (650, 660), 'data': None, 'ann': None}]
99 # Possible other events:
100 # - Error event in case protocol looks broken:
101 # [{'type': 'ERROR', 'range': (min, max),
102 # 'data': TODO, 'ann': 'This is not a Microchip 24XX64 EEPROM'},
103 # [{'type': 'ERROR', 'range': (min, max),
104 # 'data': TODO, 'ann': 'TODO'},
105 # - TODO: Make list of possible errors accessible as metadata?
107 # TODO: I2C address of slaves.
108 # TODO: Handle multiple different I2C devices on same bus
109 # -> we need to decode multiple protocols at the same time.
110 # TODO: range: Always contiguous? Splitted ranges? Multiple per event?
117 # [[id, channel, description], ...] # TODO
120 # {'id': 'SCL', 'ch': 5, 'desc': 'Serial clock line'}
121 # {'id': 'SDA', 'ch': 7, 'desc': 'Serial data line'}
125 # 'signals': [{'SCL': }]}
129 def __init__(self, data):
131 def probe(self, probe):
132 s = ord(self.data[probe / 8]) & (1 << (probe % 8))
133 return True if s else False
135 def sampleiter(data, unitsize):
136 for i in range(0, len(data), unitsize):
137 yield(Sample(data[i:i+unitsize]))
141 longname = 'Inter-Integrated Circuit (I2C) bus'
142 desc = 'I2C is a two-wire, multi-master, serial bus.'
144 author = 'Uwe Hermann'
145 email = 'uwe@hermann-uwe.de'
150 'scl': {'ch': 0, 'name': 'SCL', 'desc': 'Serial clock line'},
151 'sda': {'ch': 1, 'name': 'SDA', 'desc': 'Serial data line'},
154 'address-space': ['Address space (in bits)', 7],
157 def __init__(self, **kwargs):
158 self.probes = Decoder.probes.copy()
160 # TODO: Don't hardcode the number of channels.
168 self.startsample = -1
169 self.IDLE, self.START, self.ADDRESS, self.DATA = range(4)
170 self.state = self.IDLE
172 # Get the channel/probe number of the SCL/SDA signals.
173 self.scl_bit = self.probes['scl']['ch']
174 self.sda_bit = self.probes['sda']['ch']
179 def start(self, metadata):
180 self.unitsize = metadata["unitsize"]
186 def decode(self, data):
187 """I2C protocol decoder"""
192 # We should accept a list of samples and iterate...
193 for sample in sampleiter(data["data"], self.unitsize):
195 # TODO: Eliminate the need for ord().
198 # TODO: Start counting at 0 or 1?
201 # First sample: Save SCL/SDA value.
202 if self.oldscl == None:
203 # Get SCL/SDA bit values (0/1 for low/high) of the first sample.
204 self.oldscl = (s & (1 << self.scl_bit)) >> self.scl_bit
205 self.oldsda = (s & (1 << self.sda_bit)) >> self.sda_bit
208 # Get SCL/SDA bit values (0/1 for low/high).
209 scl = (s & (1 << self.scl_bit)) >> self.scl_bit
210 sda = (s & (1 << self.sda_bit)) >> self.sda_bit
212 # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
214 # START condition (S): SDA = falling, SCL = high
215 if (self.oldsda == 1 and sda == 0) and scl == 1:
216 o = {'type': 'S', 'range': (self.samplenum, self.samplenum),
217 'data': None, 'ann': None},
219 self.state = self.ADDRESS
220 self.bitcount = self.databyte = 0
222 # Data latching by transmitter: SCL = low
226 # Data sampling of receiver: SCL = rising
227 elif (self.oldscl == 0 and scl == 1):
228 if self.startsample == -1:
229 self.startsample = self.samplenum
232 # out.append("%d\t\tRECEIVED BIT %d: %d\n" % \
233 # (self.samplenum, 8 - bitcount, sda))
235 # Address and data are transmitted MSB-first.
239 if self.bitcount != 9:
242 # We received 8 address/data bits and the ACK/NACK bit.
243 self.databyte >>= 1 # Shift out unwanted ACK/NACK bit here.
244 ack = (sda == 1) and 'N' or 'A'
245 d = (self.state == self.ADDRESS) and (self.databyte & 0xfe) or self.databyte
246 if self.state == self.ADDRESS:
247 self.wr = (self.databyte & 1) and 1 or 0
248 self.state = self.DATA
249 o = {'type': self.state,
250 'range': (self.startsample, self.samplenum - 1),
251 'data': d, 'ann': None}
252 if self.state == self.ADDRESS and self.wr == 1:
254 elif self.state == self.ADDRESS and self.wr == 0:
256 elif self.state == self.DATA and self.wr == 1:
258 elif self.state == self.DATA and self.wr == 0:
261 o = {'type': ack, 'range': (self.samplenum, self.samplenum),
262 'data': None, 'ann': None}
264 self.bitcount = self.databyte = self.startsample = 0
265 self.startsample = -1
267 # STOP condition (P): SDA = rising, SCL = high
268 elif (self.oldsda == 0 and sda == 1) and scl == 1:
269 o = {'type': 'P', 'range': (self.samplenum, self.samplenum),
270 'data': None, 'ann': None},
272 self.state = self.IDLE
275 # Save current SDA/SCL values for the next round.
279 # TODO: Which output format?
280 # TODO: How to only output something after the last chunk of data?
284 # Use psyco (if available) as it results in huge performance improvements.