1 /***************************************************************************//**
2 * @file
3 * @brief Inter-integrated Circuit (I2C) Peripheral API
4 *******************************************************************************
5 * # License
6 * <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
7 *******************************************************************************
8 *
9 * SPDX-License-Identifier: Zlib
10 *
11 * The licensor of this software is Silicon Laboratories Inc.
12 *
13 * This software is provided 'as-is', without any express or implied
14 * warranty. In no event will the authors be held liable for any damages
15 * arising from the use of this software.
16 *
17 * Permission is granted to anyone to use this software for any purpose,
18 * including commercial applications, and to alter it and redistribute it
19 * freely, subject to the following restrictions:
20 *
21 * 1. The origin of this software must not be misrepresented; you must not
22 * claim that you wrote the original software. If you use this software
23 * in a product, an acknowledgment in the product documentation would be
24 * appreciated but is not required.
25 * 2. Altered source versions must be plainly marked as such, and must not be
26 * misrepresented as being the original software.
27 * 3. This notice may not be removed or altered from any source distribution.
28 *
29 ******************************************************************************/
30
31 #include "em_i2c.h"
32 #if defined(I2C_COUNT) && (I2C_COUNT > 0)
33
34 #include "em_cmu.h"
35 #include "em_bus.h"
36 #include "sl_assert.h"
37
38 #include <limits.h>
39
40 /***************************************************************************//**
41 * @addtogroup i2c I2C - Inter-Integrated Circuit
42 * @brief Inter-integrated Circuit (I2C) Peripheral API
43 * @details
44 * This module contains functions to control the I2C peripheral of Silicon
45 * Labs 32-bit MCUs and SoCs. The I2C interface allows communication on I2C
46 * buses with the lowest energy consumption possible.
47 * @{
48 ******************************************************************************/
49
50 /*******************************************************************************
51 ******************************* DEFINES ***********************************
52 ******************************************************************************/
53
54 /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */
55
56 /** Validation of the I2C register block pointer reference for assert statements. */
57 #if (I2C_COUNT == 1)
58 #define I2C_REF_VALID(ref) ((ref) == I2C0)
59 #elif (I2C_COUNT == 2)
60 #define I2C_REF_VALID(ref) (((ref) == I2C0) || ((ref) == I2C1))
61 #elif (I2C_COUNT == 3)
62 #define I2C_REF_VALID(ref) (((ref) == I2C0) || ((ref) == I2C1) || ((ref) == I2C2))
63 #elif (I2C_COUNT == 4)
64 #define I2C_REF_VALID(ref) (((ref) == I2C0) || ((ref) == I2C1) || ((ref) == I2C2) || ((ref) == I2C3))
65 #endif
66
67 /** Error flags indicating that the I2C transfer has failed. */
68 /* Notice that I2C_IF_TXOF (transmit overflow) is not really possible with */
69 /* the software-supporting master mode. Likewise, for I2C_IF_RXUF (receive underflow) */
70 /* RXUF is only likely to occur with the software if using a debugger peeking into */
71 /* the RXDATA register. Therefore, those types of faults are ignored. */
72 #define I2C_IF_ERRORS (I2C_IF_BUSERR | I2C_IF_ARBLOST)
73 #define I2C_IEN_ERRORS (I2C_IEN_BUSERR | I2C_IEN_ARBLOST)
74
75 /* Maximum I2C transmission rate constant. */
76 #if defined(_SILICON_LABS_32B_SERIES_0)
77 #if defined(_EFM32_HAPPY_FAMILY) || defined(_EFM32_ZERO_FAMILY)
78 #define I2C_CR_MAX 8
79 #else
80 #define I2C_CR_MAX 4
81 #endif
82 #elif defined(_SILICON_LABS_32B_SERIES_1)
83 #define I2C_CR_MAX 8
84 #elif defined(_SILICON_LABS_32B_SERIES_2)
85 #define I2C_CR_MAX 8
86 #else
87 #warning "Max I2C transmission rate constant is not defined"
88 #endif
89
90 /** @endcond */
91
92 /*******************************************************************************
93 ******************************** ENUMS ************************************
94 ******************************************************************************/
95
96 /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */
97
98 /** Master mode transfer states. */
99 typedef enum {
100 i2cStateStartAddrSend, /**< Send start + (first part of) address. */
101 i2cStateAddrWFAckNack, /**< Wait for ACK/NACK on (the first part of) address. */
102 i2cStateAddrWF2ndAckNack, /**< Wait for ACK/NACK on the second part of a 10 bit address. */
103 i2cStateRStartAddrSend, /**< Send a repeated start + (first part of) address. */
104 i2cStateRAddrWFAckNack, /**< Wait for ACK/NACK on an address sent after a repeated start. */
105 i2cStateDataSend, /**< Send data. */
106 i2cStateDataWFAckNack, /**< Wait for ACK/NACK on data sent. */
107 i2cStateWFData, /**< Wait for data. */
108 i2cStateWFStopSent, /**< Wait for STOP to have been transmitted. */
109 i2cStateDone /**< Transfer completed successfully. */
110 } I2C_TransferState_TypeDef;
111
112 /** @endcond */
113
114 /*******************************************************************************
115 ******************************* STRUCTS ***********************************
116 ******************************************************************************/
117
118 /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */
119
120 /** Structure used to store state information on an ongoing master mode transfer. */
121 typedef struct {
122 /** Current state. */
123 I2C_TransferState_TypeDef state;
124
125 /** Result return code. */
126 I2C_TransferReturn_TypeDef result;
127
128 /** Offset in the current sequence buffer. */
129 uint16_t offset;
130
131 /* Index to the current sequence buffer in use. */
132 uint8_t bufIndx;
133
134 /** Reference to the I2C transfer sequence definition provided by the user. */
135 I2C_TransferSeq_TypeDef *seq;
136 } I2C_Transfer_TypeDef;
137
138 /** @endcond */
139
140 /*******************************************************************************
141 ***************************** LOCAL DATA *******^**************************
142 ******************************************************************************/
143
144 /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */
145
146 /**
147 * Lookup table for Nlow + Nhigh setting defined by CLHR. Set the undefined
148 * index (0x3) to reflect a default setting just in case.
149 */
150 static const uint8_t i2cNSum[] = { 4 + 4, 6 + 3, 11 + 6, 4 + 4 };
151
152 /** A transfer state information for an ongoing master mode transfer. */
153 static I2C_Transfer_TypeDef i2cTransfer[I2C_COUNT];
154
155 /** @endcond */
156
157 /*******************************************************************************
158 ************************** LOCAL FUNCTIONS *******************************
159 ******************************************************************************/
160
161 /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */
162
163 /***************************************************************************//**
164 * @brief
165 * Empty received data buffer.
166 ******************************************************************************/
flushRx(I2C_TypeDef * i2c)167 static void flushRx(I2C_TypeDef *i2c)
168 {
169 while (i2c->STATUS & I2C_STATUS_RXDATAV) {
170 i2c->RXDATA;
171 }
172
173 #if defined(_SILICON_LABS_32B_SERIES_2)
174 /* SW needs to clear RXDATAV IF on Series 2 devices.
175 Flag is kept high by HW if buffer is not empty. */
176 I2C_IntClear(i2c, I2C_IF_RXDATAV);
177 #endif
178 }
179
180 /** @endcond */
181
182 /*******************************************************************************
183 ************************** GLOBAL FUNCTIONS *******************************
184 ******************************************************************************/
185
186 /***************************************************************************//**
187 * @brief
188 * Get the current configured I2C bus frequency.
189 *
190 * @details
191 * This frequency is only relevant when acting as master.
192 *
193 * @note
194 * The actual frequency is a real number, this function returns a rounded
195 * down (truncated) integer value.
196 *
197 * @param[in] i2c
198 * A pointer to the I2C peripheral register block.
199 *
200 * @return
201 * The current I2C frequency in Hz.
202 ******************************************************************************/
I2C_BusFreqGet(I2C_TypeDef * i2c)203 uint32_t I2C_BusFreqGet(I2C_TypeDef *i2c)
204 {
205 uint32_t freqHfper = 0;
206 uint32_t n;
207
208 /* Maximum frequency is given by freqScl = freqHfper/((Nlow + Nhigh)(DIV + 1) + I2C_CR_MAX)
209 * For more details, see the reference manual
210 * I2C Clock Generation chapter. */
211 if (i2c == I2C0) {
212 freqHfper = CMU_ClockFreqGet(cmuClock_I2C0);
213 #if defined(I2C1)
214 } else if (i2c == I2C1) {
215 freqHfper = CMU_ClockFreqGet(cmuClock_I2C1);
216 #endif
217 #if defined(I2C2)
218 } else if (i2c == I2C2) {
219 freqHfper = CMU_ClockFreqGet(cmuClock_I2C2);
220 #endif
221 } else {
222 EFM_ASSERT(false);
223 }
224
225 /* n = Nlow + Nhigh */
226 n = (uint32_t)i2cNSum[(i2c->CTRL & _I2C_CTRL_CLHR_MASK)
227 >> _I2C_CTRL_CLHR_SHIFT];
228 return freqHfper / ((n * (i2c->CLKDIV + 1)) + I2C_CR_MAX);
229 }
230
231 /***************************************************************************//**
232 * @brief
233 * Set the I2C bus frequency.
234 *
235 * @details
236 * The bus frequency is only relevant when acting as master. The bus
237 * frequency should not be set higher than the maximum frequency accepted by the
238 * slowest device on the bus.
239 *
240 * Notice that, due to asymmetric requirements on low and high I2C clock
241 * cycles in the I2C specification, the maximum frequency allowed
242 * to comply with the specification may be somewhat lower than expected.
243 *
244 * See the reference manual, details on I2C clock generation,
245 * for maximum allowed theoretical frequencies for different modes.
246 *
247 * @param[in] i2c
248 * A pointer to the I2C peripheral register block.
249 *
250 * @param[in] freqRef
251 * An I2C reference clock frequency in Hz that will be used. If set to 0,
252 * HFPERCLK / HFPERCCLK clock is used. Setting it to a higher than actual
253 * configured value has the consequence of reducing the real I2C frequency.
254 *
255 * @param[in] freqScl
256 * A bus frequency to set (bus speed may be lower due to integer
257 * prescaling). Safe (according to the I2C specification) maximum frequencies for
258 * standard fast and fast+ modes are available using I2C_FREQ_ defines.
259 * (Using I2C_FREQ_ defines requires corresponding setting of @p type.)
260 * The slowest slave device on a bus must always be considered.
261 *
262 * @param[in] i2cMode
263 * A clock low-to-high ratio type to use. If not using i2cClockHLRStandard,
264 * make sure all devices on the bus support the specified mode. Using a
265 * non-standard ratio is useful to achieve a higher bus clock in fast and
266 * fast+ modes.
267 ******************************************************************************/
I2C_BusFreqSet(I2C_TypeDef * i2c,uint32_t freqRef,uint32_t freqScl,I2C_ClockHLR_TypeDef i2cMode)268 void I2C_BusFreqSet(I2C_TypeDef *i2c,
269 uint32_t freqRef,
270 uint32_t freqScl,
271 I2C_ClockHLR_TypeDef i2cMode)
272 {
273 uint32_t n, minFreq, denominator;
274 int32_t div;
275
276 /* Avoid dividing by 0. */
277 EFM_ASSERT(freqScl);
278 if (!freqScl) {
279 return;
280 }
281
282 /* Ensure mode is valid */
283 i2cMode &= _I2C_CTRL_CLHR_MASK >> _I2C_CTRL_CLHR_SHIFT;
284
285 /* Set the CLHR (clock low-to-high ratio). */
286 i2c->CTRL &= ~_I2C_CTRL_CLHR_MASK;
287 BUS_RegMaskedWrite(&i2c->CTRL,
288 _I2C_CTRL_CLHR_MASK,
289 i2cMode << _I2C_CTRL_CLHR_SHIFT);
290
291 if (freqRef == 0) {
292 if (i2c == I2C0) {
293 freqRef = CMU_ClockFreqGet(cmuClock_I2C0);
294 #if defined(I2C1)
295 } else if (i2c == I2C1) {
296 freqRef = CMU_ClockFreqGet(cmuClock_I2C1);
297 #endif
298 #if defined(I2C2)
299 } else if (i2c == I2C2) {
300 freqRef = CMU_ClockFreqGet(cmuClock_I2C2);
301 #endif
302 } else {
303 EFM_ASSERT(false);
304 }
305 }
306
307 /* Check the minumum HF peripheral clock. */
308 minFreq = UINT_MAX;
309 if (i2c->CTRL & I2C_CTRL_SLAVE) {
310 switch (i2cMode) {
311 case i2cClockHLRStandard:
312 #if defined(_SILICON_LABS_32B_SERIES_0)
313 minFreq = 4200000; break;
314 #elif defined(_SILICON_LABS_32B_SERIES_1)
315 minFreq = 2000000; break;
316 #elif defined(_SILICON_LABS_32B_SERIES_2)
317 minFreq = 2000000; break;
318 #endif
319 case i2cClockHLRAsymetric:
320 #if defined(_SILICON_LABS_32B_SERIES_0)
321 minFreq = 11000000; break;
322 #elif defined(_SILICON_LABS_32B_SERIES_1)
323 minFreq = 5000000; break;
324 #elif defined(_SILICON_LABS_32B_SERIES_2)
325 minFreq = 5000000; break;
326 #endif
327 case i2cClockHLRFast:
328 #if defined(_SILICON_LABS_32B_SERIES_0)
329 minFreq = 24400000; break;
330 #elif defined(_SILICON_LABS_32B_SERIES_1)
331 minFreq = 14000000; break;
332 #elif defined(_SILICON_LABS_32B_SERIES_2)
333 minFreq = 14000000; break;
334 #endif
335 default:
336 /* MISRA requires the default case. */
337 break;
338 }
339 } else {
340 /* For master mode, platform 1 and 2 share the same
341 minimum frequencies. */
342 switch (i2cMode) {
343 case i2cClockHLRStandard:
344 minFreq = 2000000; break;
345 case i2cClockHLRAsymetric:
346 minFreq = 9000000; break;
347 case i2cClockHLRFast:
348 minFreq = 20000000; break;
349 default:
350 /* MISRA requires default case */
351 break;
352 }
353 }
354
355 /* Frequency most be larger-than. */
356 EFM_ASSERT(freqRef > minFreq);
357
358 /* SCL frequency is given by:
359 * freqScl = freqRef/((Nlow + Nhigh) * (DIV + 1) + I2C_CR_MAX)
360 *
361 * Therefore,
362 * DIV = ((freqRef - (I2C_CR_MAX * freqScl))/((Nlow + Nhigh) * freqScl)) - 1
363 *
364 * For more details, see the reference manual
365 * I2C Clock Generation chapter. */
366
367 /* n = Nlow + Nhigh */
368 n = (uint32_t)i2cNSum[i2cMode];
369 denominator = n * freqScl;
370
371 /* Explicitly ensure denominator is never zero. */
372 if (denominator == 0) {
373 EFM_ASSERT(0);
374 return;
375 }
376 /* Perform integer division so that div is rounded up. */
377 div = (int32_t)(((freqRef - (I2C_CR_MAX * freqScl) + denominator - 1)
378 / denominator) - 1);
379 EFM_ASSERT(div >= 0);
380 EFM_ASSERT((uint32_t)div <= _I2C_CLKDIV_DIV_MASK);
381
382 /* The clock divisor must be at least 1 in slave mode according to the reference */
383 /* manual (in which case there is normally no need to set the bus frequency). */
384 if ((i2c->CTRL & I2C_CTRL_SLAVE) && (div == 0)) {
385 div = 1;
386 }
387 i2c->CLKDIV = (uint32_t)div;
388 }
389
390 /***************************************************************************//**
391 * @brief
392 * Enable/disable I2C.
393 *
394 * @note
395 * After enabling the I2C (from being disabled), the I2C is in BUSY state.
396 *
397 * @param[in] i2c
398 * A pointer to the I2C peripheral register block.
399 *
400 * @param[in] enable
401 * True to enable counting, false to disable.
402 ******************************************************************************/
I2C_Enable(I2C_TypeDef * i2c,bool enable)403 void I2C_Enable(I2C_TypeDef *i2c, bool enable)
404 {
405 EFM_ASSERT(I2C_REF_VALID(i2c));
406
407 #if defined (_I2C_EN_MASK)
408 BUS_RegBitWrite(&(i2c->EN), _I2C_EN_EN_SHIFT, enable);
409 #else
410 BUS_RegBitWrite(&(i2c->CTRL), _I2C_CTRL_EN_SHIFT, enable);
411 #endif
412 }
413
414 /***************************************************************************//**
415 * @brief
416 * Initialize I2C.
417 *
418 * @param[in] i2c
419 * A pointer to the I2C peripheral register block.
420 *
421 * @param[in] init
422 * A pointer to the I2C initialization structure.
423 ******************************************************************************/
I2C_Init(I2C_TypeDef * i2c,const I2C_Init_TypeDef * init)424 void I2C_Init(I2C_TypeDef *i2c, const I2C_Init_TypeDef *init)
425 {
426 EFM_ASSERT(I2C_REF_VALID(i2c));
427
428 i2c->IEN = 0;
429 I2C_IntClear(i2c, _I2C_IF_MASK);
430
431 /* Set SLAVE select mode. */
432 BUS_RegBitWrite(&(i2c->CTRL), _I2C_CTRL_SLAVE_SHIFT, init->master ? 0 : 1);
433
434 I2C_BusFreqSet(i2c, init->refFreq, init->freq, init->clhr);
435
436 I2C_Enable(i2c, init->enable);
437 }
438
439 /***************************************************************************//**
440 * @brief
441 * Reset I2C to the same state that it was in after a hardware reset.
442 *
443 * @note
444 * The ROUTE register is NOT reset by this function to allow for
445 * centralized setup of this feature.
446 *
447 * @param[in] i2c
448 * A pointer to the I2C peripheral register block.
449 ******************************************************************************/
I2C_Reset(I2C_TypeDef * i2c)450 void I2C_Reset(I2C_TypeDef *i2c)
451 {
452 // Cancel ongoing operations and clear TX buffer
453 i2c->CMD = I2C_CMD_CLEARPC | I2C_CMD_CLEARTX | I2C_CMD_ABORT;
454 i2c->CTRL = _I2C_CTRL_RESETVALUE;
455 i2c->CLKDIV = _I2C_CLKDIV_RESETVALUE;
456 i2c->SADDR = _I2C_SADDR_RESETVALUE;
457 i2c->SADDRMASK = _I2C_SADDRMASK_RESETVALUE;
458 i2c->IEN = _I2C_IEN_RESETVALUE;
459 #if defined (_I2C_EN_EN_MASK)
460 i2c->EN = _I2C_EN_RESETVALUE;
461 #endif
462
463 // Empty received data buffer
464 flushRx(i2c);
465 I2C_IntClear(i2c, _I2C_IF_MASK);
466 /* Do not reset the route register; setting should be done independently. */
467 }
468
469 // *****************************************************************************
470 /// @brief
471 /// Continue an initiated I2C transfer (single master mode only).
472 ///
473 /// @details
474 /// This function is used repeatedly after a I2C_TransferInit() to
475 /// complete a transfer. It may be used in polled mode as the below example
476 /// shows:
477 /// @code{.c}
478 /// I2C_TransferReturn_TypeDef ret;
479 ///
480 /// // Do a polled transfer
481 /// ret = I2C_TransferInit(I2C0, seq);
482 /// while (ret == i2cTransferInProgress)
483 /// {
484 /// ret = I2C_Transfer(I2C0);
485 /// }
486 /// @endcode
487 /// It may also be used in interrupt driven mode, where this function is invoked
488 /// from the interrupt handler. Notice that, if used in interrupt mode, NVIC
489 /// interrupts must be configured and enabled for the I2C bus used. I2C
490 /// peripheral specific interrupts are managed by this software.
491 ///
492 /// @note
493 /// Only single master mode is supported.
494 ///
495 /// @param[in] i2c
496 /// A pointer to the I2C peripheral register block.
497 ///
498 /// @return
499 /// Returns status for an ongoing transfer.
500 /// @li #i2cTransferInProgress - indicates that transfer not finished.
501 /// @li #i2cTransferDone - transfer completed successfully.
502 /// @li otherwise some sort of error has occurred.
503 ///
504 // *****************************************************************************
I2C_Transfer(I2C_TypeDef * i2c)505 I2C_TransferReturn_TypeDef I2C_Transfer(I2C_TypeDef *i2c)
506 {
507 uint32_t tmp;
508 uint32_t pending;
509 I2C_Transfer_TypeDef *transfer;
510 I2C_TransferSeq_TypeDef *seq;
511 bool finished = false;
512
513 EFM_ASSERT(I2C_REF_VALID(i2c));
514
515 /* Support up to 2 I2C buses. */
516 if (i2c == I2C0) {
517 transfer = i2cTransfer;
518 }
519 #if (I2C_COUNT > 1)
520 else if (i2c == I2C1) {
521 transfer = i2cTransfer + 1;
522 }
523 #endif
524 #if (I2C_COUNT > 2)
525 else if (i2c == I2C2) {
526 transfer = i2cTransfer + 2;
527 }
528 #endif
529 #if (I2C_COUNT > 3)
530 else if (i2c == I2C3) {
531 transfer = i2cTransfer + 3;
532 }
533 #endif
534 else {
535 return i2cTransferUsageFault;
536 }
537
538 seq = transfer->seq;
539 while (!finished) {
540 pending = i2c->IF;
541
542 /* If some sort of fault, abort transfer. */
543 if (pending & I2C_IF_ERRORS) {
544 if (pending & I2C_IF_ARBLOST) {
545 /* If an arbitration fault, indicates either a slave device */
546 /* not responding as expected, or other master which is not */
547 /* supported by this software. */
548 transfer->result = i2cTransferArbLost;
549 } else if (pending & I2C_IF_BUSERR) {
550 /* A bus error indicates a misplaced start or stop, which should */
551 /* not occur in master mode controlled by this software. */
552 transfer->result = i2cTransferBusErr;
553 }
554
555 /* Ifan error occurs, it is difficult to know */
556 /* an exact cause and how to resolve. It will be up to a wrapper */
557 /* to determine how to handle a fault/recovery if possible. */
558 transfer->state = i2cStateDone;
559 break;
560 }
561
562 switch (transfer->state) {
563 /***************************************************/
564 /* Send the first start+address (first byte if 10 bit). */
565 /***************************************************/
566 case i2cStateStartAddrSend:
567 if (seq->flags & I2C_FLAG_10BIT_ADDR) {
568 tmp = (((uint32_t)(seq->addr) >> 8) & 0x06) | 0xf0;
569
570 /* In 10 bit address mode, the address following the first */
571 /* start always indicates write. */
572 } else {
573 tmp = (uint32_t)(seq->addr) & 0xfe;
574
575 if (seq->flags & I2C_FLAG_READ) {
576 /* Indicate read request */
577 tmp |= 1;
578 }
579 }
580
581 transfer->state = i2cStateAddrWFAckNack;
582 i2c->TXDATA = tmp;/* Data not transmitted until the START is sent. */
583 i2c->CMD = I2C_CMD_START;
584 finished = true;
585 break;
586
587 /*******************************************************/
588 /* Wait for ACK/NACK on the address (first byte if 10 bit). */
589 /*******************************************************/
590 case i2cStateAddrWFAckNack:
591 if (pending & I2C_IF_NACK) {
592 I2C_IntClear(i2c, I2C_IF_NACK);
593 transfer->result = i2cTransferNack;
594 transfer->state = i2cStateWFStopSent;
595 i2c->CMD = I2C_CMD_STOP;
596 } else if (pending & I2C_IF_ACK) {
597 I2C_IntClear(i2c, I2C_IF_ACK);
598
599 /* If a 10 bit address, send the 2nd byte of the address. */
600 if (seq->flags & I2C_FLAG_10BIT_ADDR) {
601 transfer->state = i2cStateAddrWF2ndAckNack;
602 i2c->TXDATA = (uint32_t)(seq->addr) & 0xff;
603 } else {
604 /* Determine whether receiving or sending data. */
605 if (seq->flags & I2C_FLAG_READ) {
606 transfer->state = i2cStateWFData;
607 if (seq->buf[transfer->bufIndx].len == 1) {
608 i2c->CMD = I2C_CMD_NACK;
609 }
610 } else {
611 transfer->state = i2cStateDataSend;
612 continue;
613 }
614 }
615 }
616 finished = true;
617 break;
618
619 /******************************************************/
620 /* Wait for ACK/NACK on the second byte of a 10 bit address. */
621 /******************************************************/
622 case i2cStateAddrWF2ndAckNack:
623 if (pending & I2C_IF_NACK) {
624 I2C_IntClear(i2c, I2C_IF_NACK);
625 transfer->result = i2cTransferNack;
626 transfer->state = i2cStateWFStopSent;
627 i2c->CMD = I2C_CMD_STOP;
628 } else if (pending & I2C_IF_ACK) {
629 I2C_IntClear(i2c, I2C_IF_ACK);
630
631 /* If using a plain read sequence with a 10 bit address, switch to send */
632 /* a repeated start. */
633 if (seq->flags & I2C_FLAG_READ) {
634 transfer->state = i2cStateRStartAddrSend;
635 }
636 /* Otherwise, expected to write 0 or more bytes. */
637 else {
638 transfer->state = i2cStateDataSend;
639 }
640 continue;
641 }
642 finished = true;
643 break;
644
645 /*******************************/
646 /* Send a repeated start+address */
647 /*******************************/
648 case i2cStateRStartAddrSend:
649 if (seq->flags & I2C_FLAG_10BIT_ADDR) {
650 tmp = (uint32_t)((seq->addr >> 8) & 0x06) | 0xf0;
651 } else {
652 tmp = (uint32_t)(seq->addr & 0xfe);
653 }
654
655 /* If this is a write+read combined sequence, read is about to start. */
656 if (seq->flags & I2C_FLAG_WRITE_READ) {
657 /* Indicate a read request. */
658 tmp |= 1;
659 /* If reading only one byte, prepare the NACK now before START command. */
660 if (seq->buf[transfer->bufIndx].len == 1) {
661 i2c->CMD = I2C_CMD_NACK;
662 }
663 }
664
665 transfer->state = i2cStateRAddrWFAckNack;
666 /* The START command has to be written first since repeated start. Otherwise, */
667 /* data would be sent first. */
668 i2c->CMD = I2C_CMD_START;
669 i2c->TXDATA = tmp;
670
671 finished = true;
672 break;
673
674 /**********************************************************************/
675 /* Wait for ACK/NACK on the repeated start+address (first byte if 10 bit) */
676 /**********************************************************************/
677 case i2cStateRAddrWFAckNack:
678 if (pending & I2C_IF_NACK) {
679 I2C_IntClear(i2c, I2C_IF_NACK);
680 transfer->result = i2cTransferNack;
681 transfer->state = i2cStateWFStopSent;
682 i2c->CMD = I2C_CMD_STOP;
683 } else if (pending & I2C_IF_ACK) {
684 I2C_IntClear(i2c, I2C_IF_ACK);
685
686 /* Determine whether receiving or sending data. */
687 if (seq->flags & I2C_FLAG_WRITE_READ) {
688 transfer->state = i2cStateWFData;
689 } else {
690 transfer->state = i2cStateDataSend;
691 continue;
692 }
693 }
694 finished = true;
695 break;
696
697 /*****************************/
698 /* Send a data byte to the slave */
699 /*****************************/
700 case i2cStateDataSend:
701 /* Reached end of data buffer. */
702 if (transfer->offset >= seq->buf[transfer->bufIndx].len) {
703 /* Move to the next message part. */
704 transfer->offset = 0;
705 transfer->bufIndx++;
706
707 /* Send a repeated start when switching to read mode on the 2nd buffer. */
708 if (seq->flags & I2C_FLAG_WRITE_READ) {
709 transfer->state = i2cStateRStartAddrSend;
710 continue;
711 }
712
713 /* Only writing from one buffer or finished both buffers. */
714 if ((seq->flags & I2C_FLAG_WRITE) || (transfer->bufIndx > 1)) {
715 transfer->state = i2cStateWFStopSent;
716 i2c->CMD = I2C_CMD_STOP;
717 finished = true;
718 break;
719 }
720
721 /* Reprocess in case the next buffer is empty. */
722 continue;
723 }
724
725 /* Send byte. */
726 i2c->TXDATA = (uint32_t)(seq->buf[transfer->bufIndx].data[transfer->offset++]);
727 transfer->state = i2cStateDataWFAckNack;
728 finished = true;
729 break;
730
731 /*********************************************************/
732 /* Wait for ACK/NACK from the slave after sending data to it. */
733 /*********************************************************/
734 case i2cStateDataWFAckNack:
735 if (pending & I2C_IF_NACK) {
736 I2C_IntClear(i2c, I2C_IF_NACK);
737 transfer->result = i2cTransferNack;
738 transfer->state = i2cStateWFStopSent;
739 i2c->CMD = I2C_CMD_STOP;
740 } else if (pending & I2C_IF_ACK) {
741 I2C_IntClear(i2c, I2C_IF_ACK);
742 transfer->state = i2cStateDataSend;
743 continue;
744 }
745 finished = true;
746 break;
747
748 /****************************/
749 /* Wait for data from slave */
750 /****************************/
751 case i2cStateWFData:
752 if (pending & I2C_IF_RXDATAV) {
753 uint8_t data;
754 unsigned int rxLen = seq->buf[transfer->bufIndx].len;
755
756 /* Must read out data not to block further progress. */
757 data = (uint8_t)(i2c->RXDATA);
758
759 #if (defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) \
760 || defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2) \
761 || defined(_SILICON_LABS_32B_SERIES_2_CONFIG_3))
762 // Errata I2C_E303. I2C Fails to Indicate New Incoming Data.
763 uint32_t status = i2c->STATUS;
764 // look for invalid RXDATAV = 0 and RXFULL = 1 condition
765 if (((status & I2C_IF_RXDATAV) == 0) & ((status & I2C_IF_RXFULL) != 0)) {
766 // Performing a dummy read of the RXFIFO (I2C_RXDATA).
767 // This restores the expected RXDATAV = 1 and RXFULL = 0 condition.
768 (void)i2c->RXDATA;
769 // The dummy read will also set the RXUFIF flag bit, which should be ignored and cleared.
770 I2C_IntClear(i2c, I2C_IF_RXUF);
771 }
772 #endif
773
774 /* SW needs to clear RXDATAV IF on Series 2 devices.
775 Flag is kept high by HW if buffer is not empty. */
776 #if defined(_SILICON_LABS_32B_SERIES_2)
777 I2C_IntClear(i2c, I2C_IF_RXDATAV);
778 #endif
779
780 /* Make sure that there is no storing beyond the end of the buffer (just in case). */
781 if (transfer->offset < rxLen) {
782 seq->buf[transfer->bufIndx].data[transfer->offset++] = data;
783 }
784
785 /* If all requested data is read, the sequence should end. */
786 if (transfer->offset >= rxLen) {
787 transfer->state = i2cStateWFStopSent;
788 i2c->CMD = I2C_CMD_STOP;
789 } else {
790 /* Send ACK and wait for the next byte. */
791 i2c->CMD = I2C_CMD_ACK;
792
793 if ( (1 < rxLen) && (transfer->offset == (rxLen - 1)) ) {
794 /* If receiving more than one byte and this is the next
795 to last byte, transmit the NACK now before receiving
796 the last byte. */
797 i2c->CMD = I2C_CMD_NACK;
798 }
799 }
800 }
801 finished = true;
802 break;
803
804 /***********************************/
805 /* Wait for STOP to have been sent */
806 /***********************************/
807 case i2cStateWFStopSent:
808 if (pending & I2C_IF_MSTOP) {
809 I2C_IntClear(i2c, I2C_IF_MSTOP);
810 transfer->state = i2cStateDone;
811 }
812 finished = true;
813 break;
814
815 /******************************/
816 /* An unexpected state, software fault */
817 /******************************/
818 default:
819 transfer->result = i2cTransferSwFault;
820 transfer->state = i2cStateDone;
821 finished = true;
822 break;
823 }
824 }
825
826 if (transfer->state == i2cStateDone) {
827 /* Disable interrupt sources when done. */
828 i2c->IEN = 0;
829
830 /* Update the result unless a fault has already occurred. */
831 if (transfer->result == i2cTransferInProgress) {
832 transfer->result = i2cTransferDone;
833 }
834 }
835 /* Until transfer is done, keep returning i2cTransferInProgress. */
836 else {
837 return i2cTransferInProgress;
838 }
839
840 return transfer->result;
841 }
842
843 /***************************************************************************//**
844 * @brief
845 * Prepare and start an I2C transfer (single master mode only).
846 *
847 * @details
848 * This function must be invoked to start an I2C transfer
849 * sequence. To complete the transfer, I2C_Transfer() must
850 * be used either in polled mode or by adding a small driver wrapper using
851 * interrupts.
852 *
853 * @note
854 * Only single master mode is supported.
855 *
856 * @param[in] i2c
857 * A pointer to the I2C peripheral register block.
858 *
859 * @param[in] seq
860 * A pointer to the sequence structure defining the I2C transfer to take place. The
861 * referenced structure must exist until the transfer has fully completed.
862 *
863 * @return
864 * Returns the status for an ongoing transfer:
865 * @li #i2cTransferInProgress - indicates that the transfer is not finished.
866 * @li Otherwise, an error has occurred.
867 ******************************************************************************/
I2C_TransferInit(I2C_TypeDef * i2c,I2C_TransferSeq_TypeDef * seq)868 I2C_TransferReturn_TypeDef I2C_TransferInit(I2C_TypeDef *i2c,
869 I2C_TransferSeq_TypeDef *seq)
870 {
871 I2C_Transfer_TypeDef *transfer;
872
873 EFM_ASSERT(I2C_REF_VALID(i2c));
874 EFM_ASSERT(seq);
875
876 /* Support up to 2 I2C buses. */
877 if (i2c == I2C0) {
878 transfer = i2cTransfer;
879 }
880 #if (I2C_COUNT > 1)
881 else if (i2c == I2C1) {
882 transfer = i2cTransfer + 1;
883 }
884 #endif
885 #if (I2C_COUNT > 2)
886 else if (i2c == I2C2) {
887 transfer = i2cTransfer + 2;
888 }
889 #endif
890 #if (I2C_COUNT > 3)
891 else if (i2c == I2C3) {
892 transfer = i2cTransfer + 3;
893 }
894 #endif
895 else {
896 return i2cTransferUsageFault;
897 }
898
899 /* Check if in a busy state. Since this software assumes a single master, */
900 /* issue an abort. The BUSY state is normal after a reset. */
901 if (i2c->STATE & I2C_STATE_BUSY) {
902 i2c->CMD = I2C_CMD_ABORT;
903 }
904
905 /* Do not try to read 0 bytes. It is not */
906 /* possible according to the I2C spec, since the slave will always start */
907 /* sending the first byte ACK on an address. The read operation can */
908 /* only be stopped by NACKing a received byte, i.e., minimum 1 byte. */
909 if (((seq->flags & I2C_FLAG_READ) && !(seq->buf[0].len))
910 || ((seq->flags & I2C_FLAG_WRITE_READ) && !(seq->buf[1].len))
911 ) {
912 return i2cTransferUsageFault;
913 }
914
915 /* Prepare for a transfer. */
916 transfer->state = i2cStateStartAddrSend;
917 transfer->result = i2cTransferInProgress;
918 transfer->offset = 0;
919 transfer->bufIndx = 0;
920 transfer->seq = seq;
921
922 /* Ensure buffers are empty. */
923 i2c->CMD = I2C_CMD_CLEARPC | I2C_CMD_CLEARTX;
924 flushRx(i2c);
925
926 /* Clear all pending interrupts prior to starting a transfer. */
927 I2C_IntClear(i2c, _I2C_IF_MASK);
928
929 /* Enable relevant interrupts. */
930 /* Notice that the I2C interrupt must also be enabled in the NVIC, but */
931 /* that is left for an additional driver wrapper. */
932 i2c->IEN |= I2C_IEN_NACK | I2C_IEN_ACK | I2C_IEN_MSTOP
933 | I2C_IEN_RXDATAV | I2C_IEN_ERRORS;
934
935 /* Start a transfer. */
936 return I2C_Transfer(i2c);
937 }
938
939 /** @} (end addtogroup i2c) */
940 #endif /* defined(I2C_COUNT) && (I2C_COUNT > 0) */
941