Mbed OS Reference
Loading...
Searching...
No Matches
I2C.h
1/* mbed Microcontroller Library
2 * Copyright (c) 2006-2019 ARM Limited
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17#ifndef MBED_I2C_H
18#define MBED_I2C_H
19
20#include "platform/platform.h"
21#include "hal/gpio_api.h"
22
23#if DEVICE_I2C || defined(DOXYGEN_ONLY)
24
25#include "hal/i2c_api.h"
26#include "platform/SingletonPtr.h"
27#include "rtos/Mutex.h"
28#include "platform/NonCopyable.h"
29
30#if DEVICE_I2C_ASYNCH
31#include "platform/CThunk.h"
32#include "hal/dma_api.h"
33#include "platform/Callback.h"
34#endif
35
36namespace mbed {
37/** \defgroup drivers-public-api-i2c I2C
38 * \ingroup drivers-public-api
39 */
40
41/**
42 * \defgroup drivers_I2C I2C class
43 * \ingroup drivers-public-api-i2c
44 * @{
45 */
46
47// Note: In the below comments, Doxygen wants to auto-link the word "I2C" to the class name. A percent sign is used to
48// suppress this behavior.
49
50/** An %I2C Master, used for communicating with %I2C slave devices
51 *
52 * There are three different forms of the %I2C API usable via this class:
53 * <ul>
54 * <li>Transaction-based %I2C</li>
55 * <li>Single-byte %I2C</li>
56 * <li>Asynchronous %I2C</li>
57 * </ul>
58 *
59 * All three of these APIs let you execute %I2C operations, but they work differently.
60 *
61 * <h1>Transaction-Based API</h1>
62 *
63 * The simplest API, which should be appropriate for most use cases, is the transaction-based API, which is
64 * accessed through the \link I2C::read(int address, char *data, int length, bool repeated) read() \endlink and the
65 * \link write(int address, const char *data, int length, bool repeated) write() \endlink functions. These functions
66 * execute an entire %I2C transaction (the start condition, address, data bytes, and stop condition) in a single
67 * function call.
68 *
69 * The bytes to be read/written are passed in through an array, which requires that you can predict the
70 * size of the data ahead of time. If this information is not known, you may want to use the single-byte API instead
71 * (see below).
72 *
73 * Example of using the transaction-based API to read the temperature from an LM75BD:
74 * @code
75 * #include "mbed.h"
76 * I2C i2c(I2C_SDA , I2C_SCL);
77 * const int addr7bit = 0x48; // 7-bit I2C address
78 * const int addr8bit = 0x48 << 1; // 8-bit I2C address, 0x90
79 *
80 * int main() {
81 * char cmd[2];
82 * while (1) {
83 * cmd[0] = 0x01;
84 * cmd[1] = 0x00;
85 *
86 * // read and write takes the 8-bit version of the address.
87 * // set up configuration register (at 0x01)
88 * I2C::Result result = i2c.write(addr8bit, cmd, 2);
89 *
90 * if(result != I2C::ACK)
91 * {
92 * // Chip not accessible, handle error....
93 * }
94 *
95 * ThisThread::sleep_for(500);
96 *
97 * // read temperature register
98 * cmd[0] = 0x00;
99 * i2c.write(addr8bit, cmd, 1, true); // Set repeated to true so that we don't give up the bus after this transaction
100 * i2c.read(addr8bit | 1, cmd, 2);
101 *
102 * float tmp = (float((cmd[0]<<8)|cmd[1]) / 256.0);
103 * printf("Temp = %.2f\n", tmp);
104 * }
105 * }
106 * @endcode
107 *
108 *
109 *
110 * <h1>Single-Byte API</h1>
111 *
112 * The single-byte API consists of the \link I2C::start() start() \endlink, \link I2C::write_byte() write_byte()
113 * \endlink, \link I2C::read_byte() read_byte() \endlink, and \link I2C::stop() stop() \endlink functions.
114 * With the single-byte API, you have manual control over each condition and data byte put onto the I2C bus.
115 * This is useful for dealing with devices which can return variable amounts of data in one I2C operation,
116 * or when you don't want to create buffers to store the data. However, this API is more verbose than the
117 * transaction-based API and will have a bit more overhead since there's more code executing per byte.
118 *
119 * The following is an example that accomplishes the same thing as the above code, but using the single-byte API.
120 * @code
121 * #include "mbed.h"
122 * I2C i2c(I2C_SDA , I2C_SCL);
123 * const int addr7bit = 0x48; // 7-bit I2C address
124 * const int addr8bit = 0x48 << 1; // 8-bit I2C address, 0x90
125 *
126 * int main() {
127 * while (1) {
128 * // read and write takes the 8-bit version of the address.
129 * // set up configuration register (at 0x01)
130 * i2c.lock();
131 * i2c.start();
132 * I2C::Result result = i2c.write_byte(addr8bit); // Write address, LSBit low to indicate write
133 * i2c.write_byte(0x01);
134 * i2c.write_byte(0x00);
135 * i2c.stop();
136 * i2c.unlock();
137 *
138 * if(result != I2C::ACK)
139 * {
140 * // Chip not accessible, handle error....
141 * }
142 *
143 * ThisThread::sleep_for(500);
144 *
145 * // Set register to read
146 * i2c.lock();
147 * i2c.start();
148 * i2c.write_byte(addr8bit); // Write address
149 * i2c.write_byte(0x00);
150 * // To create a repeated start condition, we do not call stop() here
151 *
152 * i2c.start();
153 * i2c.write_byte(addr8bit | 1); // Write address, LSBit high to indicate read
154 *
155 * // Read the two byte temperature word
156 * uint16_t temperatureBinary = 0;
157 * temperatureBinary |= static_cast<uint16_t>(i2c.read_byte(true)) << 8;
158 * temperatureBinary |= static_cast<uint16_t>(i2c.read_byte(false)); // send NACK to indicate last byte
159 * i2c.stop();
160 * i2c.unlock();
161 *
162 * float tmp = (float(temperatureBinary) / 256.0);
163 * printf("Temp = %.2f\n", tmp);
164 * }
165 * }
166 * @endcode
167 *
168 * \attention If a single I2C object is being shared among multiple threads, you should surround usage of the
169 * single-byte API with \link I2C::lock() lock() \endlink and \link I2C::unlock() unlock() \endlink. This
170 * ensures that a transaction by one thread is not interrupted by another. It may also improve performance
171 * because the backing mutex will not need to be locked for each byte.
172 *
173 * <h1>Asynchronous API</h1>
174 *
175 * The asynchronous API allows you to run %I2C operations in the background. This API is only
176 * available if your device has the I2C_ASYNCH feature. To use this API, use \link I2C::transfer() transfer() \endlink
177 * to start an operation and \link I2C::abort_transfer() abort_transfer() \endlink to stop it. Alternately, use the
178 * \link I2C::transfer_and_wait() transfer_and_wait() \endlink function to block the current thread until
179 * the transfer finishes.
180 *
181 * Some devices implement these features using DMA, others use interrupts, so be mindful that there may still be
182 * significant CPU usage if you have multiple and/or high-rate transfers going on.
183 *
184 * <h1>A Note about Addressing</h1>
185 * Most %I2C devices make use of 7-bit addresses (see <a href="https://www.i2c-bus.org/addressing/">here</a> for details).
186 * Mbed OS, however, works with addresses in 8-bit format, where the least significant bit specifies if the transaction
187 * is a read (1) or a write (0). Due to this, you will generally need to use bitshifts and bitwise ORs when passing
188 * addresses to I2C functions. See the documentation on each function for details.
189 *
190 * %I2C also has a <a href="https://www.i2c-bus.org/addressing/10-bit-addressing/">10-bit addressing mode</a>, where
191 * the address is sent in two physical bytes on the bus. Some, but not all, Mbed targets support this mode -- refer
192 * to your MCU datasheet and your target's HAL code for details. For 10-bit addresses, use the same format to
193 * pass them to I2C functions -- shift them left by one and set the LSBit to indicate the read/write direction.
194 * On MCUs that do not natively support 10-bit addressing, you can emulate support by using the single-byte API
195 * to send two address bytes; see the linked page above for details.
196 *
197 * <h1>Other Info</h1>
198 *
199 * The I2C class is thread-safe, and uses a mutex to prevent multiple threads from using it at the same time.
200 *
201 * \warning Mbed OS requires that you only create one instance of the I2C class per physical %I2C bus on your chip.
202 * This means that if you have multiple sensors connected together on a bus, you must create one I2C object at the
203 * top level and pass it in to the drivers for each sensor. Violating this directive will cause undefined
204 * behavior in your code.
205 *
206 * \attention Due to how %I2C works, if multiple devices are sharing a bus which support different %I2C speeds, you cannot
207 * go faster than the maximum bus speed of any of the devices. Otherwise, slower devices may misinterpret messages
208 * that are too fast for them and cause interference on the bus. For example, if you have two 400kHz devices and one
209 * 100kHz device on a bus, you must run the entire bus at 100kHz!
210 */
211class I2C : private NonCopyable<I2C> {
212
213public:
214
215 /**
216 * Result code for I2C operations
217 */
218 enum Result : int {
219 /// ACK was received
220 ACK = 0,
221 /// NACK was received
223 /// Timeout waiting for I2C hardware
225 /// Other error in I2C operation (e.g. wrong sequence of single byte calls)
227 /// Operation not supported (check i2c_get_capabilities())
229 /// You tried to do something while in the wrong state (e.g. calling stop() before start())
231 };
232
233 /** Create an I2C Master interface, connected to the specified pins.
234 * The new object defaults to 100kHz speed.
235 *
236 * @param sda I2C data line pin
237 * @param scl I2C clock line pin
238 */
239 I2C(PinName sda, PinName scl);
240
241 /** Create an I2C Master interface, connected to the specified pins.
242 * The new object defaults to 100kHz speed.
243 *
244 * @param static_pinmap reference to structure which holds static pinmap.
245 */
246 I2C(const i2c_pinmap_t &static_pinmap);
247 I2C(const i2c_pinmap_t &&) = delete; // prevent passing of temporary objects
248
249 /** Set the frequency of the I2C interface.
250 * If you do not call this function, the I2C will run at 100kHz speed.
251 *
252 * Note: Some underlying HALs only support a very limited set of common I2C frequencies, such as 100kHz and
253 * 400kHz. Other implementations support all frequencies. If the frequency you set is not supported, you will get
254 * an assertion failure after calling this function.
255 *
256 * @param hz The bus frequency in hertz
257 */
258 void frequency(int hz);
259
260 /** Read from an %I2C slave
261 *
262 * Performs a complete read transaction. The least significant bit of
263 * the address must be 1 to indicate a read.
264 *
265 * @param address 8/11-bit I2C slave address [ (7 or 10 bit addr << 1) | 1 ]
266 * @param data Pointer to the byte-array to read data in to
267 * @param length Number of bytes to read
268 * @param repeated Set up for a repeated start. If true, the Mbed processor does not relinquish the bus after
269 * this read operation. You may then call write(), read(), or start() again to start another operation.
270 *
271 * @returns Result enum describing whether the I2C transaction succeeded or failed
272 */
273 Result read(int address, char *data, int length, bool repeated = false);
274
275 /** Write to an %I2C slave
276 *
277 * Performs a complete write transaction. The least significant bit of
278 * the address must be 0 to indicate a write.
279 *
280 * @param address 8/11-bit I2C slave address [ (7 or 10 bit addr << 1) | 0 ]
281 * @param data Pointer to the byte-array data to send
282 * @param length Number of bytes to send
283 * @param repeated Set up for a repeated start. If true, the Mbed processor does not relinquish the bus after
284 * this write operation. You may then call write(), read(), or start() again to start another operation.
285 *
286 * @returns Result enum describing whether the I2C transaction succeeded or failed
287 */
288 Result write(int address, const char *data, int length, bool repeated = false);
289
290 /**
291 * @brief Creates a start condition on the %I2C bus.
292 *
293 * After calling this function, you should call \link write_byte() \endlink to send the %I2C address.
294 *
295 * @note Some I2C peripherals (e.g. RP2xxx, newer STM32s) are not capable of sending a start condition
296 * until the address is known. On these MCUs, the start condition will not actually be sent until the first
297 * \link write_byte() \endlink call after the start().
298 *
299 * @returns 0 if successful or negative error code on error
300 */
301 int start();
302
303 /** Read a single byte from the %I2C bus.
304 *
305 * After calling this function, you may call it again to read another byte from the slave. Alternately,
306 * you may call \link stop() \endlink to stop the current transaction, or \link start() \endlink to
307 * start a new transaction.
308 *
309 * Note: Reads are not acknowledged by the slave device in I2C, which is why this function does not
310 * return an ACK/NACK result.
311 *
312 * @param ack indicates if the byte is to be acknowledged (true = acknowledge). Use false to indicate to
313 * the slave that you don't want to read any more data.
314 *
315 * @returns
316 * the byte read, or -1 on error.
317 */
318 int read_byte(bool ack);
319
320 /** Read a single byte from the %I2C bus. This function is a legacy alias for \link read_byte() \endlink
321 *
322 * After calling this function, you may call it again to read another byte from the slave. Alternately,
323 * you may call \link stop() \endlink to stop the current transaction, or \link start() \endlink to
324 * start a new transaction.
325 *
326 * Note: Reads are not acknowledged by the slave device in I2C, which is why this function does not
327 * return an ACK/NACK result.
328 *
329 * @param ack indicates if the byte is to be acknowledged (1 = acknowledge)
330 *
331 * @returns
332 * the byte read
333 */
334 int read(int ack)
335 {
336 return read_byte(ack);
337 }
338
339 /** Write a single byte out on the %I2C bus. The very first write_byte() call after calling start()
340 * is used to set up the slave address.
341 *
342 * After calling this function, you may call \link write_byte() \endlink again to write bytes in a write operation,
343 * or \link read_byte() \endlink to read bytes in a read operation. Once done, call \link stop() \endlink
344 * to stop the current transaction or \link start() \endlink to start a new transaction.
345 *
346 * @param data data to write out on bus. Note: This is an int, not a uint8_t, to support addressing modes
347 * with more than 7 bits.
348 *
349 * @returns Result enum describing whether the I2C byte was acknowledged or not
350 */
352
353 /** Write a single byte out on the %I2C bus. Deprecated version of \link write_byte() \endlink, with a legacy
354 * return code format.
355 *
356 * @param data data to write out on bus
357 *
358 * @returns
359 * '0' - NAK was received
360 * '1' - ACK was received,
361 * '2' - timeout
362 */
363 MBED_DEPRECATED_SINCE("mbed-os-7.0", "Use I2C::write_byte() instead for better readability and return codes")
364 int write(int data);
365
366 /**
367 * @brief Creates a stop condition on the %I2C bus.
368 *
369 * This puts the bus back into an idle state where new transactions can be
370 * initiated by this device or others.
371 *
372 * @returns 0 if successful or negative error code on error
373 */
374 int stop();
375
376 /** Acquire exclusive access to this %I2C bus
377 */
378 virtual void lock();
379
380 /** Release exclusive access to this %I2C bus
381 */
382 virtual void unlock();
383
384 virtual ~I2C();
385
386#if DEVICE_I2C_ASYNCH
387
388 /** Start nonblocking %I2C transfer.
389 *
390 * The %I2C peripheral will begin a transmit and/or receive operation in the background. If only a transmit
391 * or receive buffer is specified, only a transmit or receive will be done. If both buffers are specified,
392 * first the transmission is done to the given slave address, then the MCU performs a repeated start
393 * and the specified number of bytes are received.
394 *
395 * If you wish to find out when the transfer is done, pass a callback function to the callback argument
396 * and set the event argument to the events you wish to receive.
397 * This callback will be called when the transfer completes or errors out. Be careful: if you
398 * only request the I2C_EVENT_TRANSFER_COMPLETE event, and the transfer errors, the callback will never be called.
399 *
400 * Internally, the chip HAL may implement this function using either DMA or interrupts.
401 *
402 * This function locks the deep sleep until any event has occurred.
403 *
404 * You may not call any other functions on this class instance until the transfer is complete, has errored,
405 * or is aborted. Trying to start multiple transfers at once will return an error.
406 *
407 * @param address 8/11 bit %I2C slave address
408 * @param tx_buffer The TX buffer with data to be transferred. May be nullptr if tx_length is 0.
409 * @param tx_length The length of TX buffer in bytes. If 0, no transmission is done.
410 * @param rx_buffer The RX buffer, which is used for received data. May be nullptr if tx_length is 0.
411 * @param rx_length The length of RX buffer in bytes If 0, no reception is done.
412 * @param event The logical OR of events to subscribe to. May be I2C_EVENT_ALL, or some combination
413 * of the flags I2C_EVENT_ERROR, I2C_EVENT_ERROR_NO_SLAVE, I2C_EVENT_TRANSFER_COMPLETE, or I2C_EVENT_TRANSFER_EARLY_NACK
414 * @param callback The event callback function
415 * @param repeated Set up for a repeated start. If true, the Mbed processor does not relinquish the bus after
416 * this operation. You may then call write(), read(), start(), or transfer() again to start another operation.
417 *
418 * @returns Zero if the transfer has started, or -1 on error
419 */
420 int transfer(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t &callback, int event = I2C_EVENT_TRANSFER_COMPLETE, bool repeated = false);
421
422 /** Abort the ongoing I2C transfer
423 */
425
426 /** Start %I2C transfer and wait until it is complete. Like the transactional API this blocks the current thread,
427 * however all work is done in the background and other threads may execute.
428 *
429 * The %I2C peripheral will begin a transmit and/or receive operation in the background. If only a transmit
430 * or receive buffer is specified, only a transmit or receive will be done. If both buffers are specified,
431 * first the transmission is done to the given slave address, then the MCU performs a repeated start
432 * and the specified number of bytes are received.
433 *
434 * Internally, the chip vendor may implement this function using either DMA or interrupts.
435 *
436 * This function locks the deep sleep until it returns.
437 *
438 * @param address 8/11 bit %I2C slave address
439 * @param tx_buffer The TX buffer with data to be transferred. May be nullptr if tx_length is 0.
440 * @param tx_length The length of TX buffer in bytes. If 0, no transmission is done.
441 * @param rx_buffer The RX buffer, which is used for received data. May be nullptr if tx_length is 0.
442 * @param rx_length The length of RX buffer in bytes If 0, no reception is done.
443 * @param timeout timeout value. Use #rtos::Kernel::wait_for_u32_forever to wait forever (the default).
444 * @param repeated Set up for a repeated start. If true, the Mbed processor does not relinquish the bus after
445 * this operation. You may then call write(), read(), start(), or transfer() again to start another operation.
446 *
447 * @returns Result code describing whether the transfer succeeded or not.
448 */
449 Result transfer_and_wait(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, rtos::Kernel::Clock::duration_u32 timeout = rtos::Kernel::wait_for_u32_forever, bool repeated = false);
450
451#if !defined(DOXYGEN_ONLY)
452protected:
453 /** Lock deep sleep only if it is not yet locked */
454 void lock_deep_sleep();
455
456 /** Unlock deep sleep only if it has been locked */
457 void unlock_deep_sleep();
458
459 void irq_handler_asynch(void);
460 event_callback_t _callback;
461 CThunk<I2C> _irq;
462 DMAUsage _usage;
463 bool _deep_sleep_locked;
464 bool _async_transfer_is_repeated; // Flag that the current async transfer is configured for a repeated start
465#endif
466#endif
467
468#if !defined(DOXYGEN_ONLY)
469protected:
470
471 i2c_t _i2c;
472 int _hz;
474 PinName _sda;
475 PinName _scl;
476
477private:
478 /** Recover I2C bus, when stuck with SDA low
479 * @note : Initialization of I2C bus is required after this API.
480 *
481 * @param sda I2C data line pin
482 * @param scl I2C clock line pin
483 *
484 * @returns
485 * '0' - Successfully recovered
486 * 'I2C_ERROR_BUS_BUSY' - In case of failure
487 *
488 */
489 int recover(PinName sda, PinName scl);
490#endif
491};
492
493/** @}*/
494
495} // namespace mbed
496
497#endif
498
499#endif
Class for created a pointer with data bound to it.
Definition CThunk.h:45
An I2C Master, used for communicating with I2C slave devices.
Definition I2C.h:211
Result read(int address, char *data, int length, bool repeated=false)
Read from an I2C slave.
Result transfer_and_wait(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, rtos::Kernel::Clock::duration_u32 timeout=rtos::Kernel::wait_for_u32_forever, bool repeated=false)
Start I2C transfer and wait until it is complete.
int transfer(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t &callback, int event=I2C_EVENT_TRANSFER_COMPLETE, bool repeated=false)
Start nonblocking I2C transfer.
Result write_byte(int data)
Write a single byte out on the I2C bus.
int read(int ack)
Read a single byte from the I2C bus.
Definition I2C.h:334
int read_byte(bool ack)
Read a single byte from the I2C bus.
I2C(const i2c_pinmap_t &static_pinmap)
Create an I2C Master interface, connected to the specified pins.
Result write(int address, const char *data, int length, bool repeated=false)
Write to an I2C slave.
void abort_transfer()
Abort the ongoing I2C transfer.
void frequency(int hz)
Set the frequency of the I2C interface.
int start()
Creates a start condition on the I2C bus.
I2C(PinName sda, PinName scl)
Create an I2C Master interface, connected to the specified pins.
virtual void lock()
Acquire exclusive access to this I2C bus.
int stop()
Creates a stop condition on the I2C bus.
virtual void unlock()
Release exclusive access to this I2C bus.
Result
Result code for I2C operations.
Definition I2C.h:218
@ NACK
NACK was received.
Definition I2C.h:222
@ INVALID_STATE
You tried to do something while in the wrong state (e.g. calling stop() before start())
Definition I2C.h:230
@ ACK
ACK was received.
Definition I2C.h:220
@ NOT_SUPPORTED
Operation not supported (check i2c_get_capabilities())
Definition I2C.h:228
@ TIMEOUT
Timeout waiting for I2C hardware.
Definition I2C.h:224
@ OTHER_ERROR
Other error in I2C operation (e.g. wrong sequence of single byte calls)
Definition I2C.h:226
Prevents generation of copy constructor and copy assignment operator in derived classes.
#define I2C_EVENT_TRANSFER_COMPLETE
Indicates that the transfer completed successfully.
Definition i2c_api.h:54
DMAUsage
Enumeration of possible DMA usage hints.
Definition dma_api.h:32
Callback< R(ArgTs...)> callback(R(*func)(ArgTs...)=nullptr) noexcept
Create a callback class with type inferred from the arguments.
Definition Callback.h:678
#define MBED_DEPRECATED_SINCE(D, M)
MBED_DEPRECATED("message string") Mark a function declaration as deprecated, if it used then a warnin...
constexpr Clock::duration_u32 wait_for_u32_forever
Magic "wait forever" constant for Kernel::Clock::duration_u32-based APIs.
Definition Kernel.h:120
Utility class for creating and using a singleton.