1.. currentmodule:: machine
2.. _machine.I2C:
3
4class I2C -- a two-wire serial protocol
5=======================================
6
7I2C is a two-wire protocol for communicating between devices.  At the physical
8level it consists of 2 wires: SCL and SDA, the clock and data lines respectively.
9
10I2C objects are created attached to a specific bus.  They can be initialised
11when created, or initialised later on.
12
13Printing the I2C object gives you information about its configuration.
14
15Both hardware and software I2C implementations exist via the
16:ref:`machine.I2C <machine.I2C>` and `machine.SoftI2C` classes.  Hardware I2C uses
17underlying hardware support of the system to perform the reads/writes and is
18usually efficient and fast but may have restrictions on which pins can be used.
19Software I2C is implemented by bit-banging and can be used on any pin but is not
20as efficient.  These classes have the same methods available and differ primarily
21in the way they are constructed.
22
23Example usage::
24
25    from machine import I2C
26
27    i2c = I2C(freq=400000)          # create I2C peripheral at frequency of 400kHz
28                                    # depending on the port, extra parameters may be required
29                                    # to select the peripheral and/or pins to use
30
31    i2c.scan()                      # scan for peripherals, returning a list of 7-bit addresses
32
33    i2c.writeto(42, b'123')         # write 3 bytes to peripheral with 7-bit address 42
34    i2c.readfrom(42, 4)             # read 4 bytes from peripheral with 7-bit address 42
35
36    i2c.readfrom_mem(42, 8, 3)      # read 3 bytes from memory of peripheral 42,
37                                    #   starting at memory-address 8 in the peripheral
38    i2c.writeto_mem(42, 2, b'\x10') # write 1 byte to memory of peripheral 42
39                                    #   starting at address 2 in the peripheral
40
41Constructors
42------------
43
44.. class:: I2C(id, *, scl, sda, freq=400000)
45
46   Construct and return a new I2C object using the following parameters:
47
48      - *id* identifies a particular I2C peripheral.  Allowed values for
49        depend on the particular port/board
50      - *scl* should be a pin object specifying the pin to use for SCL.
51      - *sda* should be a pin object specifying the pin to use for SDA.
52      - *freq* should be an integer which sets the maximum frequency
53        for SCL.
54
55   Note that some ports/boards will have default values of *scl* and *sda*
56   that can be changed in this constructor.  Others will have fixed values
57   of *scl* and *sda* that cannot be changed.
58
59.. _machine.SoftI2C:
60.. class:: SoftI2C(scl, sda, *, freq=400000, timeout=255)
61
62   Construct a new software I2C object.  The parameters are:
63
64      - *scl* should be a pin object specifying the pin to use for SCL.
65      - *sda* should be a pin object specifying the pin to use for SDA.
66      - *freq* should be an integer which sets the maximum frequency
67        for SCL.
68      - *timeout* is the maximum time in microseconds to wait for clock
69        stretching (SCL held low by another device on the bus), after
70        which an ``OSError(ETIMEDOUT)`` exception is raised.
71
72General Methods
73---------------
74
75.. method:: I2C.init(scl, sda, *, freq=400000)
76
77  Initialise the I2C bus with the given arguments:
78
79     - *scl* is a pin object for the SCL line
80     - *sda* is a pin object for the SDA line
81     - *freq* is the SCL clock rate
82
83.. method:: I2C.deinit()
84
85   Turn off the I2C bus.
86
87   Availability: WiPy.
88
89.. method:: I2C.scan()
90
91   Scan all I2C addresses between 0x08 and 0x77 inclusive and return a list of
92   those that respond.  A device responds if it pulls the SDA line low after
93   its address (including a write bit) is sent on the bus.
94
95Primitive I2C operations
96------------------------
97
98The following methods implement the primitive I2C controller bus operations and can
99be combined to make any I2C transaction.  They are provided if you need more
100control over the bus, otherwise the standard methods (see below) can be used.
101
102These methods are only available on the `machine.SoftI2C` class.
103
104.. method:: I2C.start()
105
106   Generate a START condition on the bus (SDA transitions to low while SCL is high).
107
108.. method:: I2C.stop()
109
110   Generate a STOP condition on the bus (SDA transitions to high while SCL is high).
111
112.. method:: I2C.readinto(buf, nack=True, /)
113
114   Reads bytes from the bus and stores them into *buf*.  The number of bytes
115   read is the length of *buf*.  An ACK will be sent on the bus after
116   receiving all but the last byte.  After the last byte is received, if *nack*
117   is true then a NACK will be sent, otherwise an ACK will be sent (and in this
118   case the peripheral assumes more bytes are going to be read in a later call).
119
120.. method:: I2C.write(buf)
121
122   Write the bytes from *buf* to the bus.  Checks that an ACK is received
123   after each byte and stops transmitting the remaining bytes if a NACK is
124   received.  The function returns the number of ACKs that were received.
125
126Standard bus operations
127-----------------------
128
129The following methods implement the standard I2C controller read and write
130operations that target a given peripheral device.
131
132.. method:: I2C.readfrom(addr, nbytes, stop=True, /)
133
134   Read *nbytes* from the peripheral specified by *addr*.
135   If *stop* is true then a STOP condition is generated at the end of the transfer.
136   Returns a `bytes` object with the data read.
137
138.. method:: I2C.readfrom_into(addr, buf, stop=True, /)
139
140   Read into *buf* from the peripheral specified by *addr*.
141   The number of bytes read will be the length of *buf*.
142   If *stop* is true then a STOP condition is generated at the end of the transfer.
143
144   The method returns ``None``.
145
146.. method:: I2C.writeto(addr, buf, stop=True, /)
147
148   Write the bytes from *buf* to the peripheral specified by *addr*.  If a
149   NACK is received following the write of a byte from *buf* then the
150   remaining bytes are not sent.  If *stop* is true then a STOP condition is
151   generated at the end of the transfer, even if a NACK is received.
152   The function returns the number of ACKs that were received.
153
154.. method:: I2C.writevto(addr, vector, stop=True, /)
155
156   Write the bytes contained in *vector* to the peripheral specified by *addr*.
157   *vector* should be a tuple or list of objects with the buffer protocol.
158   The *addr* is sent once and then the bytes from each object in *vector*
159   are written out sequentially.  The objects in *vector* may be zero bytes
160   in length in which case they don't contribute to the output.
161
162   If a NACK is received following the write of a byte from one of the
163   objects in *vector* then the remaining bytes, and any remaining objects,
164   are not sent.  If *stop* is true then a STOP condition is generated at
165   the end of the transfer, even if a NACK is received.  The function
166   returns the number of ACKs that were received.
167
168Memory operations
169-----------------
170
171Some I2C devices act as a memory device (or set of registers) that can be read
172from and written to.  In this case there are two addresses associated with an
173I2C transaction: the peripheral address and the memory address.  The following
174methods are convenience functions to communicate with such devices.
175
176.. method:: I2C.readfrom_mem(addr, memaddr, nbytes, *, addrsize=8)
177
178   Read *nbytes* from the peripheral specified by *addr* starting from the memory
179   address specified by *memaddr*.
180   The argument *addrsize* specifies the address size in bits.
181   Returns a `bytes` object with the data read.
182
183.. method:: I2C.readfrom_mem_into(addr, memaddr, buf, *, addrsize=8)
184
185   Read into *buf* from the peripheral specified by *addr* starting from the
186   memory address specified by *memaddr*.  The number of bytes read is the
187   length of *buf*.
188   The argument *addrsize* specifies the address size in bits (on ESP8266
189   this argument is not recognised and the address size is always 8 bits).
190
191   The method returns ``None``.
192
193.. method:: I2C.writeto_mem(addr, memaddr, buf, *, addrsize=8)
194
195   Write *buf* to the peripheral specified by *addr* starting from the
196   memory address specified by *memaddr*.
197   The argument *addrsize* specifies the address size in bits (on ESP8266
198   this argument is not recognised and the address size is always 8 bits).
199
200   The method returns ``None``.
201