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
227 };
228
229
230 /** Create an I2C Master interface, connected to the specified pins.
231 * The new object defaults to 100kHz speed.
232 *
233 * @param sda I2C data line pin
234 * @param scl I2C clock line pin
235 */
236 I2C(PinName sda, PinName scl);
237
238 /** Create an I2C Master interface, connected to the specified pins.
239 * The new object defaults to 100kHz speed.
240 *
241 * @param static_pinmap reference to structure which holds static pinmap.
242 */
243 I2C(const i2c_pinmap_t &static_pinmap);
244 I2C(const i2c_pinmap_t &&) = delete; // prevent passing of temporary objects
245
246 /** Set the frequency of the I2C interface.
247 * If you do not call this function, the I2C will run at 100kHz speed.
248 *
249 * Note: Some underlying HALs only support a very limited set of common I2C frequencies, such as 100kHz and
250 * 400kHz. Other implementations support all frequencies. If the frequency you set is not supported, you will get
251 * an assertion failure after calling this function.
252 *
253 * @param hz The bus frequency in hertz
254 */
255 void frequency(int hz);
256
257 /** Read from an %I2C slave
258 *
259 * Performs a complete read transaction. The least significant bit of
260 * the address must be 1 to indicate a read.
261 *
262 * @param address 8/11-bit I2C slave address [ (7 or 10 bit addr << 1) | 1 ]
263 * @param data Pointer to the byte-array to read data in to
264 * @param length Number of bytes to read
265 * @param repeated Set up for a repeated start. If true, the Mbed processor does not relinquish the bus after
266 * this read operation. You may then call write(), read(), or start() again to start another operation.
267 *
268 * @returns Result enum describing whether the I2C transaction succeeded or failed
269 */
270 Result read(int address, char *data, int length, bool repeated = false);
271
272 /** Write to an %I2C slave
273 *
274 * Performs a complete write transaction. The least significant bit of
275 * the address must be 0 to indicate a write.
276 *
277 * @param address 8/11-bit I2C slave address [ (7 or 10 bit addr << 1) | 0 ]
278 * @param data Pointer to the byte-array data to send
279 * @param length Number of bytes to send
280 * @param repeated Set up for a repeated start. If true, the Mbed processor does not relinquish the bus after
281 * this write operation. You may then call write(), read(), or start() again to start another operation.
282 *
283 * @returns Result enum describing whether the I2C transaction succeeded or failed
284 */
285 Result write(int address, const char *data, int length, bool repeated = false);
286
287 /** Creates a start condition on the %I2C bus. After calling this function, you should call
288 * \link write_byte() \endlink to send the %I2C address.
289 */
290 void start(void);
291
292 /** Read a single byte from the %I2C bus.
293 *
294 * After calling this function, you may call it again to read another byte from the slave. Alternately,
295 * you may call \link stop() \endlink to stop the current transaction, or \link start() \endlink to
296 * start a new transaction.
297 *
298 * Note: Reads are not acknowledged by the slave device in I2C, which is why this function does not
299 * return an ACK/NACK result.
300 *
301 * @param ack indicates if the byte is to be acknowledged (true = acknowledge). Use false to indicate to
302 * the slave that you don't want to read any more data.
303 *
304 * @returns
305 * the byte read, or -1 on error.
306 */
307 int read_byte(bool ack);
308
309 /** Read a single byte from the %I2C bus. This function is a legacy alias for \link read_byte() \endlink
310 *
311 * After calling this function, you may call it again to read another byte from the slave. Alternately,
312 * you may call \link stop() \endlink to stop the current transaction, or \link start() \endlink to
313 * start a new transaction.
314 *
315 * Note: Reads are not acknowledged by the slave device in I2C, which is why this function does not
316 * return an ACK/NACK result.
317 *
318 * @param ack indicates if the byte is to be acknowledged (1 = acknowledge)
319 *
320 * @returns
321 * the byte read
322 */
323 int read(int ack)
324 {
325 return read_byte(ack);
326 }
327
328 /** Write a single byte out on the %I2C bus. The very first write_byte() call after calling start()
329 * is used to set up the slave address.
330 *
331 * After calling this function, you may call \link write_byte() \endlink again to write bytes in a write operation,
332 * or \link read_byte() \endlink to read bytes in a read operation. Once done, call \link stop() \endlink
333 * to stop the current transaction or \link start() \endlink to start a new transaction.
334 *
335 * @param data data to write out on bus. Note: This is an int, not a uint8_t, to support addressing modes
336 * with more than 7 bits.
337 *
338 * @returns Result enum describing whether the I2C byte was acknowledged or not
339 */
341
342 /** Write a single byte out on the %I2C bus. Deprecated version of \link write_byte() \endlink, with a legacy
343 * return code format.
344 *
345 * @param data data to write out on bus
346 *
347 * @returns
348 * '0' - NAK was received
349 * '1' - ACK was received,
350 * '2' - timeout
351 */
352 MBED_DEPRECATED_SINCE("mbed-ce", "Use I2C::write_byte() instead for better readability and return codes")
353 int write(int data);
354
355 /**
356 * Creates a stop condition on the %I2C bus. This puts the bus back into an idle state where new transactions can be
357 * initiated by this device or others.
358 */
359 void stop(void);
360
361 /** Acquire exclusive access to this %I2C bus
362 */
363 virtual void lock(void);
364
365 /** Release exclusive access to this %I2C bus
366 */
367 virtual void unlock(void);
368
369 virtual ~I2C()
370 {
371 // Do nothing
372 }
373
374#if DEVICE_I2C_ASYNCH
375
376 /** Start nonblocking %I2C transfer.
377 *
378 * The %I2C peripheral will begin a transmit and/or receive operation in the background. If only a transmit
379 * or receive buffer is specified, only a transmit or receive will be done. If both buffers are specified,
380 * first the transmission is done to the given slave address, then the MCU performs a repeated start
381 * and the specified number of bytes are received.
382 *
383 * If you wish to find out when the transfer is done, pass a callback function to the callback argument
384 * and set the event argument to the events you wish to receive.
385 * This callback will be called when the transfer completes or errors out. Be careful: if you
386 * only request the I2C_EVENT_TRANSFER_COMPLETE event, and the transfer errors, the callback will never be called.
387 *
388 * Internally, the chip vendor may implement this function using either DMA or interrupts.
389 *
390 * This function locks the deep sleep until any event has occurred.
391 *
392 * You may not call any other functions on this class instance until the transfer is complete, has errored,
393 * or is aborted. Trying to start multiple transfers at once will return an error.
394 *
395 * @param address 8/11 bit %I2C slave address
396 * @param tx_buffer The TX buffer with data to be transferred. May be nullptr if tx_length is 0.
397 * @param tx_length The length of TX buffer in bytes. If 0, no transmission is done.
398 * @param rx_buffer The RX buffer, which is used for received data. May be nullptr if tx_length is 0.
399 * @param rx_length The length of RX buffer in bytes If 0, no reception is done.
400 * @param event The logical OR of events to subscribe to. May be I2C_EVENT_ALL, or some combination
401 * of the flags I2C_EVENT_ERROR, I2C_EVENT_ERROR_NO_SLAVE, I2C_EVENT_TRANSFER_COMPLETE, or I2C_EVENT_TRANSFER_EARLY_NACK
402 * @param callback The event callback function
403 * @param repeated Set up for a repeated start. If true, the Mbed processor does not relinquish the bus after
404 * this operation. You may then call write(), read(), start(), or transfer() again to start another operation.
405 *
406 * @returns Zero if the transfer has started, or -1 if I2C peripheral is busy
407 */
408 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);
409
410 /** Abort the ongoing I2C transfer
411 */
413
414 /** Start %I2C transfer and wait until it is complete. Like the transactional API this blocks the current thread,
415 * however all work is done in the background and other threads may execute.
416 *
417 * The %I2C peripheral will begin a transmit and/or receive operation in the background. If only a transmit
418 * or receive buffer is specified, only a transmit or receive will be done. If both buffers are specified,
419 * first the transmission is done to the given slave address, then the MCU performs a repeated start
420 * and the specified number of bytes are received.
421 *
422 * Internally, the chip vendor may implement this function using either DMA or interrupts.
423 *
424 * This function locks the deep sleep until it returns.
425 *
426 * @param address 8/11 bit %I2C slave address
427 * @param tx_buffer The TX buffer with data to be transferred. May be nullptr if tx_length is 0.
428 * @param tx_length The length of TX buffer in bytes. If 0, no transmission is done.
429 * @param rx_buffer The RX buffer, which is used for received data. May be nullptr if tx_length is 0.
430 * @param rx_length The length of RX buffer in bytes If 0, no reception is done.
431 * @param timeout timeout value. Use #rtos::Kernel::wait_for_u32_forever to wait forever (the default).
432 * @param repeated Set up for a repeated start. If true, the Mbed processor does not relinquish the bus after
433 * this operation. You may then call write(), read(), start(), or transfer() again to start another operation.
434 *
435 * @returns Result code describing whether the transfer succeeded or not.
436 */
437 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);
438
439#if !defined(DOXYGEN_ONLY)
440protected:
441 /** Lock deep sleep only if it is not yet locked */
442 void lock_deep_sleep();
443
444 /** Unlock deep sleep only if it has been locked */
445 void unlock_deep_sleep();
446
447 void irq_handler_asynch(void);
448 event_callback_t _callback;
449 CThunk<I2C> _irq;
450 DMAUsage _usage;
451 bool _deep_sleep_locked;
452#endif
453#endif
454
455#if !defined(DOXYGEN_ONLY)
456protected:
457
458 i2c_t _i2c;
459 int _hz;
461 PinName _sda;
462 PinName _scl;
463
464private:
465 /** Recover I2C bus, when stuck with SDA low
466 * @note : Initialization of I2C bus is required after this API.
467 *
468 * @param sda I2C data line pin
469 * @param scl I2C clock line pin
470 *
471 * @returns
472 * '0' - Successfully recovered
473 * 'I2C_ERROR_BUS_BUSY' - In case of failure
474 *
475 */
476 int recover(PinName sda, PinName scl);
477#endif
478};
479
480/** @}*/
481
482} // namespace mbed
483
484#endif
485
486#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:323
virtual void unlock(void)
Release exclusive access to this I2C bus.
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 stop(void)
Creates a stop condition on the I2C bus.
void frequency(int hz)
Set the frequency of the I2C interface.
virtual void lock(void)
Acquire exclusive access to this I2C bus.
I2C(PinName sda, PinName scl)
Create an I2C Master interface, connected to the specified pins.
void start(void)
Creates a start condition on the I2C bus.
Result
Result code for I2C operations.
Definition: I2C.h:218
@ NACK
NACK was received.
Definition: I2C.h:222
@ ACK
ACK was received.
Definition: I2C.h:220
@ TIMEOUT
Timeout waiting for I2C hardware.
Definition: I2C.h:224
@ OTHER_ERROR
Other error in I2C operation.
Definition: I2C.h:226
Prevents generation of copy constructor and copy assignment operator in derived classes.
Definition: NonCopyable.h:162
#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.
Definition: SingletonPtr.h:88
Asynch I2C HAL structure.
Definition: i2c_api.h:75