1 /**
2   ******************************************************************************
3   * @file    stm32wbaxx_hal_i2c.c
4   * @author  MCD Application Team
5   * @brief   I2C HAL module driver.
6   *          This file provides firmware functions to manage the following
7   *          functionalities of the Inter Integrated Circuit (I2C) peripheral:
8   *           + Initialization and de-initialization functions
9   *           + IO operation functions
10   *           + Peripheral State and Errors functions
11   *
12   ******************************************************************************
13   * @attention
14   *
15   * Copyright (c) 2022 STMicroelectronics.
16   * All rights reserved.
17   *
18   * This software is licensed under terms that can be found in the LICENSE file
19   * in the root directory of this software component.
20   * If no LICENSE file comes with this software, it is provided AS-IS.
21   *
22   ******************************************************************************
23   @verbatim
24   ==============================================================================
25                         ##### How to use this driver #####
26   ==============================================================================
27     [..]
28     The I2C HAL driver can be used as follows:
29 
30     (#) Declare a I2C_HandleTypeDef handle structure, for example:
31         I2C_HandleTypeDef  hi2c;
32 
33     (#)Initialize the I2C low level resources by implementing the HAL_I2C_MspInit() API:
34         (##) Enable the I2Cx interface clock
35         (##) I2C pins configuration
36             (+++) Enable the clock for the I2C GPIOs
37             (+++) Configure I2C pins as alternate function open-drain
38         (##) NVIC configuration if you need to use interrupt process
39             (+++) Configure the I2Cx interrupt priority
40             (+++) Enable the NVIC I2C IRQ Channel
41         (##) DMA Configuration if you need to use DMA process
42             (+++) Declare a DMA_HandleTypeDef handle structure for
43                   the transmit or receive channel
44             (+++) Enable the DMAx interface clock using
45             (+++) Configure the DMA handle parameters
46             (+++) Configure the DMA Tx or Rx channel
47             (+++) Associate the initialized DMA handle to the hi2c DMA Tx or Rx handle
48             (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on
49                   the DMA Tx or Rx channel
50 
51     (#) Configure the Communication Clock Timing, Own Address1, Master Addressing mode, Dual Addressing mode,
52         Own Address2, Own Address2 Mask, General call and Nostretch mode in the hi2c Init structure.
53 
54     (#) Initialize the I2C registers by calling the HAL_I2C_Init(), configures also the low level Hardware
55         (GPIO, CLOCK, NVIC...etc) by calling the customized HAL_I2C_MspInit(&hi2c) API.
56 
57     (#) To check if target device is ready for communication, use the function HAL_I2C_IsDeviceReady()
58 
59     (#) For I2C IO and IO MEM operations, three operation modes are available within this driver :
60 
61     *** Polling mode IO operation ***
62     =================================
63     [..]
64       (+) Transmit in master mode an amount of data in blocking mode using HAL_I2C_Master_Transmit()
65       (+) Receive in master mode an amount of data in blocking mode using HAL_I2C_Master_Receive()
66       (+) Transmit in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Transmit()
67       (+) Receive in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Receive()
68 
69     *** Polling mode IO MEM operation ***
70     =====================================
71     [..]
72       (+) Write an amount of data in blocking mode to a specific memory address using HAL_I2C_Mem_Write()
73       (+) Read an amount of data in blocking mode from a specific memory address using HAL_I2C_Mem_Read()
74 
75 
76     *** Interrupt mode IO operation ***
77     ===================================
78     [..]
79       (+) Transmit in master mode an amount of data in non-blocking mode using HAL_I2C_Master_Transmit_IT()
80       (+) At transmission end of transfer, HAL_I2C_MasterTxCpltCallback() is executed and users can
81            add their own code by customization of function pointer HAL_I2C_MasterTxCpltCallback()
82       (+) Receive in master mode an amount of data in non-blocking mode using HAL_I2C_Master_Receive_IT()
83       (+) At reception end of transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can
84            add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback()
85       (+) Transmit in slave mode an amount of data in non-blocking mode using HAL_I2C_Slave_Transmit_IT()
86       (+) At transmission end of transfer, HAL_I2C_SlaveTxCpltCallback() is executed and users can
87            add their own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback()
88       (+) Receive in slave mode an amount of data in non-blocking mode using HAL_I2C_Slave_Receive_IT()
89       (+) At reception end of transfer, HAL_I2C_SlaveRxCpltCallback() is executed and users can
90            add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback()
91       (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
92            add their own code by customization of function pointer HAL_I2C_ErrorCallback()
93       (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT()
94       (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can
95            add their own code by customization of function pointer HAL_I2C_AbortCpltCallback()
96       (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro.
97            This action will inform Master to generate a Stop condition to discard the communication.
98 
99 
100     *** Interrupt mode or DMA mode IO sequential operation ***
101     ==========================================================
102     [..]
103       (@) These interfaces allow to manage a sequential transfer with a repeated start condition
104           when a direction change during transfer
105     [..]
106       (+) A specific option field manage the different steps of a sequential transfer
107       (+) Option field values are defined through I2C_XFEROPTIONS and are listed below:
108       (++) I2C_FIRST_AND_LAST_FRAME: No sequential usage, functional is same as associated interfaces in
109            no sequential mode
110       (++) I2C_FIRST_FRAME: Sequential usage, this option allow to manage a sequence with start condition, address
111                             and data to transfer without a final stop condition
112       (++) I2C_FIRST_AND_NEXT_FRAME: Sequential usage (Master only), this option allow to manage a sequence with
113                             start condition, address and data to transfer without a final stop condition,
114                             an then permit a call the same master sequential interface several times
115                             (like HAL_I2C_Master_Seq_Transmit_IT() then HAL_I2C_Master_Seq_Transmit_IT()
116                             or HAL_I2C_Master_Seq_Transmit_DMA() then HAL_I2C_Master_Seq_Transmit_DMA())
117       (++) I2C_NEXT_FRAME: Sequential usage, this option allow to manage a sequence with a restart condition, address
118                             and with new data to transfer if the direction change or manage only the new data to
119                             transfer
120                             if no direction change and without a final stop condition in both cases
121       (++) I2C_LAST_FRAME: Sequential usage, this option allow to manage a sequance with a restart condition, address
122                             and with new data to transfer if the direction change or manage only the new data to
123                             transfer
124                             if no direction change and with a final stop condition in both cases
125       (++) I2C_LAST_FRAME_NO_STOP: Sequential usage (Master only), this option allow to manage a restart condition
126                             after several call of the same master sequential interface several times
127                             (link with option I2C_FIRST_AND_NEXT_FRAME).
128                             Usage can, transfer several bytes one by one using
129                               HAL_I2C_Master_Seq_Transmit_IT
130                               or HAL_I2C_Master_Seq_Receive_IT
131                               or HAL_I2C_Master_Seq_Transmit_DMA
132                               or HAL_I2C_Master_Seq_Receive_DMA
133                               with option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME.
134                              Then usage of this option I2C_LAST_FRAME_NO_STOP at the last Transmit or
135                               Receive sequence permit to call the opposite interface Receive or Transmit
136                               without stopping the communication and so generate a restart condition.
137       (++) I2C_OTHER_FRAME: Sequential usage (Master only), this option allow to manage a restart condition after
138                             each call of the same master sequential
139                             interface.
140                             Usage can, transfer several bytes one by one with a restart with slave address between
141                             each bytes using
142                               HAL_I2C_Master_Seq_Transmit_IT
143                               or HAL_I2C_Master_Seq_Receive_IT
144                               or HAL_I2C_Master_Seq_Transmit_DMA
145                               or HAL_I2C_Master_Seq_Receive_DMA
146                               with option I2C_FIRST_FRAME then I2C_OTHER_FRAME.
147                             Then usage of this option I2C_OTHER_AND_LAST_FRAME at the last frame to help automatic
148                             generation of STOP condition.
149 
150       (+) Different sequential I2C interfaces are listed below:
151       (++) Sequential transmit in master I2C mode an amount of data in non-blocking mode using
152             HAL_I2C_Master_Seq_Transmit_IT() or using HAL_I2C_Master_Seq_Transmit_DMA()
153       (+++) At transmission end of current frame transfer, HAL_I2C_MasterTxCpltCallback() is executed and
154             users can add their own code by customization of function pointer HAL_I2C_MasterTxCpltCallback()
155       (++) Sequential receive in master I2C mode an amount of data in non-blocking mode using
156             HAL_I2C_Master_Seq_Receive_IT() or using HAL_I2C_Master_Seq_Receive_DMA()
157       (+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can
158            add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback()
159       (++) Abort a master or memory IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT()
160       (+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can
161            add their own code by customization of function pointer HAL_I2C_AbortCpltCallback()
162       (++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT()
163             HAL_I2C_DisableListen_IT()
164       (+++) When address slave I2C match, HAL_I2C_AddrCallback() is executed and users can
165            add their own code to check the Address Match Code and the transmission direction request by master
166            (Write/Read).
167       (+++) At Listen mode end HAL_I2C_ListenCpltCallback() is executed and users can
168           add their own code by customization of function pointer HAL_I2C_ListenCpltCallback()
169       (++) Sequential transmit in slave I2C mode an amount of data in non-blocking mode using
170             HAL_I2C_Slave_Seq_Transmit_IT() or using HAL_I2C_Slave_Seq_Transmit_DMA()
171       (+++) At transmission end of current frame transfer, HAL_I2C_SlaveTxCpltCallback() is executed and
172             users can add their own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback()
173       (++) Sequential receive in slave I2C mode an amount of data in non-blocking mode using
174             HAL_I2C_Slave_Seq_Receive_IT() or using HAL_I2C_Slave_Seq_Receive_DMA()
175       (+++) At reception end of current frame transfer, HAL_I2C_SlaveRxCpltCallback() is executed and users can
176            add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback()
177       (++) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
178            add their own code by customization of function pointer HAL_I2C_ErrorCallback()
179       (++) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro.
180            This action will inform Master to generate a Stop condition to discard the communication.
181 
182     *** Interrupt mode IO MEM operation ***
183     =======================================
184     [..]
185       (+) Write an amount of data in non-blocking mode with Interrupt to a specific memory address using
186           HAL_I2C_Mem_Write_IT()
187       (+) At Memory end of write transfer, HAL_I2C_MemTxCpltCallback() is executed and users can
188            add their own code by customization of function pointer HAL_I2C_MemTxCpltCallback()
189       (+) Read an amount of data in non-blocking mode with Interrupt from a specific memory address using
190           HAL_I2C_Mem_Read_IT()
191       (+) At Memory end of read transfer, HAL_I2C_MemRxCpltCallback() is executed and users can
192            add their own code by customization of function pointer HAL_I2C_MemRxCpltCallback()
193       (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
194            add their own code by customization of function pointer HAL_I2C_ErrorCallback()
195 
196     *** DMA mode IO operation ***
197     ==============================
198     [..]
199       (+) Transmit in master mode an amount of data in non-blocking mode (DMA) using
200           HAL_I2C_Master_Transmit_DMA()
201       (+) At transmission end of transfer, HAL_I2C_MasterTxCpltCallback() is executed and users can
202            add their own code by customization of function pointer HAL_I2C_MasterTxCpltCallback()
203       (+) Receive in master mode an amount of data in non-blocking mode (DMA) using
204           HAL_I2C_Master_Receive_DMA()
205       (+) At reception end of transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can
206            add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback()
207       (+) Transmit in slave mode an amount of data in non-blocking mode (DMA) using
208           HAL_I2C_Slave_Transmit_DMA()
209       (+) At transmission end of transfer, HAL_I2C_SlaveTxCpltCallback() is executed and users can
210            add their own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback()
211       (+) Receive in slave mode an amount of data in non-blocking mode (DMA) using
212           HAL_I2C_Slave_Receive_DMA()
213       (+) At reception end of transfer, HAL_I2C_SlaveRxCpltCallback() is executed and users can
214            add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback()
215       (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
216            add their own code by customization of function pointer HAL_I2C_ErrorCallback()
217       (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT()
218       (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can
219            add their own code by customization of function pointer HAL_I2C_AbortCpltCallback()
220       (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro.
221            This action will inform Master to generate a Stop condition to discard the communication.
222 
223     *** DMA mode IO MEM operation ***
224     =================================
225     [..]
226       (+) Write an amount of data in non-blocking mode with DMA to a specific memory address using
227           HAL_I2C_Mem_Write_DMA()
228       (+) At Memory end of write transfer, HAL_I2C_MemTxCpltCallback() is executed and users can
229            add their own code by customization of function pointer HAL_I2C_MemTxCpltCallback()
230       (+) Read an amount of data in non-blocking mode with DMA from a specific memory address using
231           HAL_I2C_Mem_Read_DMA()
232       (+) At Memory end of read transfer, HAL_I2C_MemRxCpltCallback() is executed and users can
233            add their own code by customization of function pointer HAL_I2C_MemRxCpltCallback()
234       (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
235            add their own code by customization of function pointer HAL_I2C_ErrorCallback()
236 
237 
238      *** I2C HAL driver macros list ***
239      ==================================
240      [..]
241        Below the list of most used macros in I2C HAL driver.
242 
243       (+) __HAL_I2C_ENABLE: Enable the I2C peripheral
244       (+) __HAL_I2C_DISABLE: Disable the I2C peripheral
245       (+) __HAL_I2C_GENERATE_NACK: Generate a Non-Acknowledge I2C peripheral in Slave mode
246       (+) __HAL_I2C_GET_FLAG: Check whether the specified I2C flag is set or not
247       (+) __HAL_I2C_CLEAR_FLAG: Clear the specified I2C pending flag
248       (+) __HAL_I2C_ENABLE_IT: Enable the specified I2C interrupt
249       (+) __HAL_I2C_DISABLE_IT: Disable the specified I2C interrupt
250 
251      *** Callback registration ***
252      =============================================
253     [..]
254      The compilation flag USE_HAL_I2C_REGISTER_CALLBACKS when set to 1
255      allows the user to configure dynamically the driver callbacks.
256      Use Functions HAL_I2C_RegisterCallback() or HAL_I2C_RegisterAddrCallback()
257      to register an interrupt callback.
258     [..]
259      Function HAL_I2C_RegisterCallback() allows to register following callbacks:
260        (+) MasterTxCpltCallback : callback for Master transmission end of transfer.
261        (+) MasterRxCpltCallback : callback for Master reception end of transfer.
262        (+) SlaveTxCpltCallback  : callback for Slave transmission end of transfer.
263        (+) SlaveRxCpltCallback  : callback for Slave reception end of transfer.
264        (+) ListenCpltCallback   : callback for end of listen mode.
265        (+) MemTxCpltCallback    : callback for Memory transmission end of transfer.
266        (+) MemRxCpltCallback    : callback for Memory reception end of transfer.
267        (+) ErrorCallback        : callback for error detection.
268        (+) AbortCpltCallback    : callback for abort completion process.
269        (+) MspInitCallback      : callback for Msp Init.
270        (+) MspDeInitCallback    : callback for Msp DeInit.
271      This function takes as parameters the HAL peripheral handle, the Callback ID
272      and a pointer to the user callback function.
273     [..]
274      For specific callback AddrCallback use dedicated register callbacks : HAL_I2C_RegisterAddrCallback().
275     [..]
276      Use function HAL_I2C_UnRegisterCallback to reset a callback to the default
277      weak function.
278      HAL_I2C_UnRegisterCallback takes as parameters the HAL peripheral handle,
279      and the Callback ID.
280      This function allows to reset following callbacks:
281        (+) MasterTxCpltCallback : callback for Master transmission end of transfer.
282        (+) MasterRxCpltCallback : callback for Master reception end of transfer.
283        (+) SlaveTxCpltCallback  : callback for Slave transmission end of transfer.
284        (+) SlaveRxCpltCallback  : callback for Slave reception end of transfer.
285        (+) ListenCpltCallback   : callback for end of listen mode.
286        (+) MemTxCpltCallback    : callback for Memory transmission end of transfer.
287        (+) MemRxCpltCallback    : callback for Memory reception end of transfer.
288        (+) ErrorCallback        : callback for error detection.
289        (+) AbortCpltCallback    : callback for abort completion process.
290        (+) MspInitCallback      : callback for Msp Init.
291        (+) MspDeInitCallback    : callback for Msp DeInit.
292     [..]
293      For callback AddrCallback use dedicated register callbacks : HAL_I2C_UnRegisterAddrCallback().
294     [..]
295      By default, after the HAL_I2C_Init() and when the state is HAL_I2C_STATE_RESET
296      all callbacks are set to the corresponding weak functions:
297      examples HAL_I2C_MasterTxCpltCallback(), HAL_I2C_MasterRxCpltCallback().
298      Exception done for MspInit and MspDeInit functions that are
299      reset to the legacy weak functions in the HAL_I2C_Init()/ HAL_I2C_DeInit() only when
300      these callbacks are null (not registered beforehand).
301      If MspInit or MspDeInit are not null, the HAL_I2C_Init()/ HAL_I2C_DeInit()
302      keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
303     [..]
304      Callbacks can be registered/unregistered in HAL_I2C_STATE_READY state only.
305      Exception done MspInit/MspDeInit functions that can be registered/unregistered
306      in HAL_I2C_STATE_READY or HAL_I2C_STATE_RESET state,
307      thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
308      Then, the user first registers the MspInit/MspDeInit user callbacks
309      using HAL_I2C_RegisterCallback() before calling HAL_I2C_DeInit()
310      or HAL_I2C_Init() function.
311     [..]
312      When the compilation flag USE_HAL_I2C_REGISTER_CALLBACKS is set to 0 or
313      not defined, the callback registration feature is not available and all callbacks
314      are set to the corresponding weak functions.
315 
316      [..]
317        (@) You can refer to the I2C HAL driver header file for more useful macros
318 
319   @endverbatim
320   */
321 
322 /* Includes ------------------------------------------------------------------*/
323 #include "stm32wbaxx_hal.h"
324 
325 /** @addtogroup STM32WBAxx_HAL_Driver
326   * @{
327   */
328 
329 /** @defgroup I2C I2C
330   * @brief I2C HAL module driver
331   * @{
332   */
333 
334 #ifdef HAL_I2C_MODULE_ENABLED
335 
336 /* Private typedef -----------------------------------------------------------*/
337 /* Private define ------------------------------------------------------------*/
338 
339 /** @defgroup I2C_Private_Define I2C Private Define
340   * @{
341   */
342 #define TIMING_CLEAR_MASK   (0xF0FFFFFFU)  /*!< I2C TIMING clear register Mask */
343 #define I2C_TIMEOUT_ADDR    (10000U)       /*!< 10 s  */
344 #define I2C_TIMEOUT_BUSY    (25U)          /*!< 25 ms */
345 #define I2C_TIMEOUT_DIR     (25U)          /*!< 25 ms */
346 #define I2C_TIMEOUT_RXNE    (25U)          /*!< 25 ms */
347 #define I2C_TIMEOUT_STOPF   (25U)          /*!< 25 ms */
348 #define I2C_TIMEOUT_TC      (25U)          /*!< 25 ms */
349 #define I2C_TIMEOUT_TCR     (25U)          /*!< 25 ms */
350 #define I2C_TIMEOUT_TXIS    (25U)          /*!< 25 ms */
351 #define I2C_TIMEOUT_FLAG    (25U)          /*!< 25 ms */
352 
353 #define MAX_NBYTE_SIZE      255U
354 #define SLAVE_ADDR_SHIFT     7U
355 #define SLAVE_ADDR_MSK       0x06U
356 
357 /* Private define for @ref PreviousState usage */
358 #define I2C_STATE_MSK             ((uint32_t)((uint32_t)((uint32_t)HAL_I2C_STATE_BUSY_TX | \
359                                                          (uint32_t)HAL_I2C_STATE_BUSY_RX) & \
360                                               (uint32_t)(~((uint32_t)HAL_I2C_STATE_READY))))
361 /*!< Mask State define, keep only RX and TX bits */
362 #define I2C_STATE_NONE            ((uint32_t)(HAL_I2C_MODE_NONE))
363 /*!< Default Value */
364 #define I2C_STATE_MASTER_BUSY_TX  ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \
365                                               (uint32_t)HAL_I2C_MODE_MASTER))
366 /*!< Master Busy TX, combinaison of State LSB and Mode enum */
367 #define I2C_STATE_MASTER_BUSY_RX  ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \
368                                               (uint32_t)HAL_I2C_MODE_MASTER))
369 /*!< Master Busy RX, combinaison of State LSB and Mode enum */
370 #define I2C_STATE_SLAVE_BUSY_TX   ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \
371                                               (uint32_t)HAL_I2C_MODE_SLAVE))
372 /*!< Slave Busy TX, combinaison of State LSB and Mode enum */
373 #define I2C_STATE_SLAVE_BUSY_RX   ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \
374                                               (uint32_t)HAL_I2C_MODE_SLAVE))
375 /*!< Slave Busy RX, combinaison of State LSB and Mode enum  */
376 #define I2C_STATE_MEM_BUSY_TX     ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \
377                                               (uint32_t)HAL_I2C_MODE_MEM))
378 /*!< Memory Busy TX, combinaison of State LSB and Mode enum */
379 #define I2C_STATE_MEM_BUSY_RX     ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \
380                                               (uint32_t)HAL_I2C_MODE_MEM))
381 /*!< Memory Busy RX, combinaison of State LSB and Mode enum */
382 
383 
384 /* Private define to centralize the enable/disable of Interrupts */
385 #define I2C_XFER_TX_IT          (uint16_t)(0x0001U)   /*!< Bit field can be combinated with
386                                                          @ref I2C_XFER_LISTEN_IT */
387 #define I2C_XFER_RX_IT          (uint16_t)(0x0002U)   /*!< Bit field can be combinated with
388                                                          @ref I2C_XFER_LISTEN_IT */
389 #define I2C_XFER_LISTEN_IT      (uint16_t)(0x8000U)   /*!< Bit field can be combinated with @ref I2C_XFER_TX_IT
390                                                          and @ref I2C_XFER_RX_IT */
391 
392 #define I2C_XFER_ERROR_IT       (uint16_t)(0x0010U)   /*!< Bit definition to manage addition of global Error
393                                                          and NACK treatment */
394 #define I2C_XFER_CPLT_IT        (uint16_t)(0x0020U)   /*!< Bit definition to manage only STOP evenement */
395 #define I2C_XFER_RELOAD_IT      (uint16_t)(0x0040U)   /*!< Bit definition to manage only Reload of NBYTE */
396 
397 /* Private define Sequential Transfer Options default/reset value */
398 #define I2C_NO_OPTION_FRAME     (0xFFFF0000U)
399 /**
400   * @}
401   */
402 
403 /* Private macros ------------------------------------------------------------*/
404 /** @addtogroup I2C_Private_Macro
405   * @{
406   */
407 #if defined(HAL_DMA_MODULE_ENABLED)
408 /* Macro to get remaining data to transfer on DMA side */
409 #define I2C_GET_DMA_REMAIN_DATA(__HANDLE__)     (__HAL_DMA_GET_COUNTER(__HANDLE__) + HAL_DMAEx_GetFifoLevel(__HANDLE__))
410 #endif /* HAL_DMA_MODULE_ENABLED */
411 /**
412   * @}
413   */
414 
415 /* Private variables ---------------------------------------------------------*/
416 /* Private function prototypes -----------------------------------------------*/
417 
418 /** @defgroup I2C_Private_Functions I2C Private Functions
419   * @{
420   */
421 #if defined(HAL_DMA_MODULE_ENABLED)
422 /* Private functions to handle DMA transfer */
423 static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma);
424 static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma);
425 static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma);
426 static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma);
427 static void I2C_DMAError(DMA_HandleTypeDef *hdma);
428 static void I2C_DMAAbort(DMA_HandleTypeDef *hdma);
429 
430 #endif /* HAL_DMA_MODULE_ENABLED */
431 
432 /* Private functions to handle IT transfer */
433 static void I2C_ITAddrCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags);
434 static void I2C_ITMasterSeqCplt(I2C_HandleTypeDef *hi2c);
435 static void I2C_ITSlaveSeqCplt(I2C_HandleTypeDef *hi2c);
436 static void I2C_ITMasterCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags);
437 static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags);
438 static void I2C_ITListenCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags);
439 static void I2C_ITError(I2C_HandleTypeDef *hi2c, uint32_t ErrorCode);
440 
441 /* Private functions to handle IT transfer */
442 static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
443                                                 uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout,
444                                                 uint32_t Tickstart);
445 static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
446                                                uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout,
447                                                uint32_t Tickstart);
448 
449 /* Private functions for I2C transfer IRQ handler */
450 static HAL_StatusTypeDef I2C_Master_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
451                                            uint32_t ITSources);
452 static HAL_StatusTypeDef I2C_Mem_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
453                                         uint32_t ITSources);
454 static HAL_StatusTypeDef I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
455                                           uint32_t ITSources);
456 #if defined(HAL_DMA_MODULE_ENABLED)
457 static HAL_StatusTypeDef I2C_Master_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
458                                             uint32_t ITSources);
459 static HAL_StatusTypeDef I2C_Mem_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
460                                          uint32_t ITSources);
461 static HAL_StatusTypeDef I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
462                                            uint32_t ITSources);
463 #endif /* HAL_DMA_MODULE_ENABLED */
464 
465 /* Private functions to handle flags during polling transfer */
466 static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status,
467                                                     uint32_t Timeout, uint32_t Tickstart);
468 static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
469                                                         uint32_t Tickstart);
470 static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
471                                                         uint32_t Tickstart);
472 static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
473                                                         uint32_t Tickstart);
474 static HAL_StatusTypeDef I2C_IsErrorOccurred(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
475                                              uint32_t Tickstart);
476 
477 /* Private functions to centralize the enable/disable of Interrupts */
478 static void I2C_Enable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest);
479 static void I2C_Disable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest);
480 
481 /* Private function to treat different error callback */
482 static void I2C_TreatErrorCallback(I2C_HandleTypeDef *hi2c);
483 
484 /* Private function to flush TXDR register */
485 static void I2C_Flush_TXDR(I2C_HandleTypeDef *hi2c);
486 
487 /* Private function to handle  start, restart or stop a transfer */
488 static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode,
489                                uint32_t Request);
490 
491 /* Private function to Convert Specific options */
492 static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c);
493 /**
494   * @}
495   */
496 
497 /* Exported functions --------------------------------------------------------*/
498 
499 /** @defgroup I2C_Exported_Functions I2C Exported Functions
500   * @{
501   */
502 
503 /** @defgroup I2C_Exported_Functions_Group1 Initialization and de-initialization functions
504   *  @brief    Initialization and Configuration functions
505   *
506 @verbatim
507  ===============================================================================
508               ##### Initialization and de-initialization functions #####
509  ===============================================================================
510     [..]  This subsection provides a set of functions allowing to initialize and
511           deinitialize the I2Cx peripheral:
512 
513       (+) User must Implement HAL_I2C_MspInit() function in which he configures
514           all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ).
515 
516       (+) Call the function HAL_I2C_Init() to configure the selected device with
517           the selected configuration:
518         (++) Clock Timing
519         (++) Own Address 1
520         (++) Addressing mode (Master, Slave)
521         (++) Dual Addressing mode
522         (++) Own Address 2
523         (++) Own Address 2 Mask
524         (++) General call mode
525         (++) Nostretch mode
526 
527       (+) Call the function HAL_I2C_DeInit() to restore the default configuration
528           of the selected I2Cx peripheral.
529 
530 @endverbatim
531   * @{
532   */
533 
534 /**
535   * @brief  Initializes the I2C according to the specified parameters
536   *         in the I2C_InitTypeDef and initialize the associated handle.
537   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
538   *                the configuration information for the specified I2C.
539   * @retval HAL status
540   */
HAL_I2C_Init(I2C_HandleTypeDef * hi2c)541 HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c)
542 {
543   /* Check the I2C handle allocation */
544   if (hi2c == NULL)
545   {
546     return HAL_ERROR;
547   }
548 
549   /* Check the parameters */
550   assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
551   assert_param(IS_I2C_OWN_ADDRESS1(hi2c->Init.OwnAddress1));
552   assert_param(IS_I2C_ADDRESSING_MODE(hi2c->Init.AddressingMode));
553   assert_param(IS_I2C_DUAL_ADDRESS(hi2c->Init.DualAddressMode));
554   assert_param(IS_I2C_OWN_ADDRESS2(hi2c->Init.OwnAddress2));
555   assert_param(IS_I2C_OWN_ADDRESS2_MASK(hi2c->Init.OwnAddress2Masks));
556   assert_param(IS_I2C_GENERAL_CALL(hi2c->Init.GeneralCallMode));
557   assert_param(IS_I2C_NO_STRETCH(hi2c->Init.NoStretchMode));
558 
559   if (hi2c->State == HAL_I2C_STATE_RESET)
560   {
561     /* Allocate lock resource and initialize it */
562     hi2c->Lock = HAL_UNLOCKED;
563 
564 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
565     /* Init the I2C Callback settings */
566     hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */
567     hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */
568     hi2c->SlaveTxCpltCallback  = HAL_I2C_SlaveTxCpltCallback;  /* Legacy weak SlaveTxCpltCallback  */
569     hi2c->SlaveRxCpltCallback  = HAL_I2C_SlaveRxCpltCallback;  /* Legacy weak SlaveRxCpltCallback  */
570     hi2c->ListenCpltCallback   = HAL_I2C_ListenCpltCallback;   /* Legacy weak ListenCpltCallback   */
571     hi2c->MemTxCpltCallback    = HAL_I2C_MemTxCpltCallback;    /* Legacy weak MemTxCpltCallback    */
572     hi2c->MemRxCpltCallback    = HAL_I2C_MemRxCpltCallback;    /* Legacy weak MemRxCpltCallback    */
573     hi2c->ErrorCallback        = HAL_I2C_ErrorCallback;        /* Legacy weak ErrorCallback        */
574     hi2c->AbortCpltCallback    = HAL_I2C_AbortCpltCallback;    /* Legacy weak AbortCpltCallback    */
575     hi2c->AddrCallback         = HAL_I2C_AddrCallback;         /* Legacy weak AddrCallback         */
576 
577     if (hi2c->MspInitCallback == NULL)
578     {
579       hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit  */
580     }
581 
582     /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
583     hi2c->MspInitCallback(hi2c);
584 #else
585     /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
586     HAL_I2C_MspInit(hi2c);
587 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
588   }
589 
590   hi2c->State = HAL_I2C_STATE_BUSY;
591 
592   /* Disable the selected I2C peripheral */
593   __HAL_I2C_DISABLE(hi2c);
594 
595   /*---------------------------- I2Cx TIMINGR Configuration ------------------*/
596   /* Configure I2Cx: Frequency range */
597   hi2c->Instance->TIMINGR = hi2c->Init.Timing & TIMING_CLEAR_MASK;
598 
599   /*---------------------------- I2Cx OAR1 Configuration ---------------------*/
600   /* Disable Own Address1 before set the Own Address1 configuration */
601   hi2c->Instance->OAR1 &= ~I2C_OAR1_OA1EN;
602 
603   /* Configure I2Cx: Own Address1 and ack own address1 mode */
604   if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT)
605   {
606     hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | hi2c->Init.OwnAddress1);
607   }
608   else /* I2C_ADDRESSINGMODE_10BIT */
609   {
610     hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE | hi2c->Init.OwnAddress1);
611   }
612 
613   /*---------------------------- I2Cx CR2 Configuration ----------------------*/
614   /* Configure I2Cx: Addressing Master mode */
615   if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)
616   {
617     SET_BIT(hi2c->Instance->CR2, I2C_CR2_ADD10);
618   }
619   else
620   {
621     /* Clear the I2C ADD10 bit */
622     CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_ADD10);
623   }
624   /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process */
625   hi2c->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK);
626 
627   /*---------------------------- I2Cx OAR2 Configuration ---------------------*/
628   /* Disable Own Address2 before set the Own Address2 configuration */
629   hi2c->Instance->OAR2 &= ~I2C_DUALADDRESS_ENABLE;
630 
631   /* Configure I2Cx: Dual mode and Own Address2 */
632   hi2c->Instance->OAR2 = (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2 | \
633                           (hi2c->Init.OwnAddress2Masks << 8));
634 
635   /*---------------------------- I2Cx CR1 Configuration ----------------------*/
636   /* Configure I2Cx: Generalcall and NoStretch mode */
637   hi2c->Instance->CR1 = (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode);
638 
639   /* Enable the selected I2C peripheral */
640   __HAL_I2C_ENABLE(hi2c);
641 
642   hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
643   hi2c->State = HAL_I2C_STATE_READY;
644   hi2c->PreviousState = I2C_STATE_NONE;
645   hi2c->Mode = HAL_I2C_MODE_NONE;
646 
647   return HAL_OK;
648 }
649 
650 /**
651   * @brief  DeInitialize the I2C peripheral.
652   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
653   *                the configuration information for the specified I2C.
654   * @retval HAL status
655   */
HAL_I2C_DeInit(I2C_HandleTypeDef * hi2c)656 HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c)
657 {
658   /* Check the I2C handle allocation */
659   if (hi2c == NULL)
660   {
661     return HAL_ERROR;
662   }
663 
664   /* Check the parameters */
665   assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
666 
667   hi2c->State = HAL_I2C_STATE_BUSY;
668 
669   /* Disable the I2C Peripheral Clock */
670   __HAL_I2C_DISABLE(hi2c);
671 
672 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
673   if (hi2c->MspDeInitCallback == NULL)
674   {
675     hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit  */
676   }
677 
678   /* DeInit the low level hardware: GPIO, CLOCK, NVIC */
679   hi2c->MspDeInitCallback(hi2c);
680 #else
681   /* DeInit the low level hardware: GPIO, CLOCK, NVIC */
682   HAL_I2C_MspDeInit(hi2c);
683 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
684 
685   hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
686   hi2c->State = HAL_I2C_STATE_RESET;
687   hi2c->PreviousState = I2C_STATE_NONE;
688   hi2c->Mode = HAL_I2C_MODE_NONE;
689 
690   /* Release Lock */
691   __HAL_UNLOCK(hi2c);
692 
693   return HAL_OK;
694 }
695 
696 /**
697   * @brief Initialize the I2C MSP.
698   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
699   *                the configuration information for the specified I2C.
700   * @retval None
701   */
HAL_I2C_MspInit(I2C_HandleTypeDef * hi2c)702 __weak void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c)
703 {
704   /* Prevent unused argument(s) compilation warning */
705   UNUSED(hi2c);
706 
707   /* NOTE : This function should not be modified, when the callback is needed,
708             the HAL_I2C_MspInit could be implemented in the user file
709    */
710 }
711 
712 /**
713   * @brief DeInitialize the I2C MSP.
714   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
715   *                the configuration information for the specified I2C.
716   * @retval None
717   */
HAL_I2C_MspDeInit(I2C_HandleTypeDef * hi2c)718 __weak void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c)
719 {
720   /* Prevent unused argument(s) compilation warning */
721   UNUSED(hi2c);
722 
723   /* NOTE : This function should not be modified, when the callback is needed,
724             the HAL_I2C_MspDeInit could be implemented in the user file
725    */
726 }
727 
728 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
729 /**
730   * @brief  Register a User I2C Callback
731   *         To be used instead of the weak predefined callback
732   * @note   The HAL_I2C_RegisterCallback() may be called before HAL_I2C_Init() in HAL_I2C_STATE_RESET
733   *         to register callbacks for HAL_I2C_MSPINIT_CB_ID and HAL_I2C_MSPDEINIT_CB_ID.
734   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
735   *                the configuration information for the specified I2C.
736   * @param  CallbackID ID of the callback to be registered
737   *         This parameter can be one of the following values:
738   *          @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID
739   *          @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID
740   *          @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID
741   *          @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID
742   *          @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID
743   *          @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID
744   *          @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID
745   *          @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID
746   *          @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID
747   *          @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID
748   *          @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID
749   * @param  pCallback pointer to the Callback function
750   * @retval HAL status
751   */
HAL_I2C_RegisterCallback(I2C_HandleTypeDef * hi2c,HAL_I2C_CallbackIDTypeDef CallbackID,pI2C_CallbackTypeDef pCallback)752 HAL_StatusTypeDef HAL_I2C_RegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID,
753                                            pI2C_CallbackTypeDef pCallback)
754 {
755   HAL_StatusTypeDef status = HAL_OK;
756 
757   if (pCallback == NULL)
758   {
759     /* Update the error code */
760     hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
761 
762     return HAL_ERROR;
763   }
764 
765   if (HAL_I2C_STATE_READY == hi2c->State)
766   {
767     switch (CallbackID)
768     {
769       case HAL_I2C_MASTER_TX_COMPLETE_CB_ID :
770         hi2c->MasterTxCpltCallback = pCallback;
771         break;
772 
773       case HAL_I2C_MASTER_RX_COMPLETE_CB_ID :
774         hi2c->MasterRxCpltCallback = pCallback;
775         break;
776 
777       case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID :
778         hi2c->SlaveTxCpltCallback = pCallback;
779         break;
780 
781       case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID :
782         hi2c->SlaveRxCpltCallback = pCallback;
783         break;
784 
785       case HAL_I2C_LISTEN_COMPLETE_CB_ID :
786         hi2c->ListenCpltCallback = pCallback;
787         break;
788 
789       case HAL_I2C_MEM_TX_COMPLETE_CB_ID :
790         hi2c->MemTxCpltCallback = pCallback;
791         break;
792 
793       case HAL_I2C_MEM_RX_COMPLETE_CB_ID :
794         hi2c->MemRxCpltCallback = pCallback;
795         break;
796 
797       case HAL_I2C_ERROR_CB_ID :
798         hi2c->ErrorCallback = pCallback;
799         break;
800 
801       case HAL_I2C_ABORT_CB_ID :
802         hi2c->AbortCpltCallback = pCallback;
803         break;
804 
805       case HAL_I2C_MSPINIT_CB_ID :
806         hi2c->MspInitCallback = pCallback;
807         break;
808 
809       case HAL_I2C_MSPDEINIT_CB_ID :
810         hi2c->MspDeInitCallback = pCallback;
811         break;
812 
813       default :
814         /* Update the error code */
815         hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
816 
817         /* Return error status */
818         status =  HAL_ERROR;
819         break;
820     }
821   }
822   else if (HAL_I2C_STATE_RESET == hi2c->State)
823   {
824     switch (CallbackID)
825     {
826       case HAL_I2C_MSPINIT_CB_ID :
827         hi2c->MspInitCallback = pCallback;
828         break;
829 
830       case HAL_I2C_MSPDEINIT_CB_ID :
831         hi2c->MspDeInitCallback = pCallback;
832         break;
833 
834       default :
835         /* Update the error code */
836         hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
837 
838         /* Return error status */
839         status =  HAL_ERROR;
840         break;
841     }
842   }
843   else
844   {
845     /* Update the error code */
846     hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
847 
848     /* Return error status */
849     status =  HAL_ERROR;
850   }
851 
852   return status;
853 }
854 
855 /**
856   * @brief  Unregister an I2C Callback
857   *         I2C callback is redirected to the weak predefined callback
858   * @note   The HAL_I2C_UnRegisterCallback() may be called before HAL_I2C_Init() in HAL_I2C_STATE_RESET
859   *         to un-register callbacks for HAL_I2C_MSPINIT_CB_ID and HAL_I2C_MSPDEINIT_CB_ID.
860   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
861   *                the configuration information for the specified I2C.
862   * @param  CallbackID ID of the callback to be unregistered
863   *         This parameter can be one of the following values:
864   *         This parameter can be one of the following values:
865   *          @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID
866   *          @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID
867   *          @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID
868   *          @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID
869   *          @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID
870   *          @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID
871   *          @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID
872   *          @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID
873   *          @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID
874   *          @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID
875   *          @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID
876   * @retval HAL status
877   */
HAL_I2C_UnRegisterCallback(I2C_HandleTypeDef * hi2c,HAL_I2C_CallbackIDTypeDef CallbackID)878 HAL_StatusTypeDef HAL_I2C_UnRegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID)
879 {
880   HAL_StatusTypeDef status = HAL_OK;
881 
882   if (HAL_I2C_STATE_READY == hi2c->State)
883   {
884     switch (CallbackID)
885     {
886       case HAL_I2C_MASTER_TX_COMPLETE_CB_ID :
887         hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */
888         break;
889 
890       case HAL_I2C_MASTER_RX_COMPLETE_CB_ID :
891         hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */
892         break;
893 
894       case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID :
895         hi2c->SlaveTxCpltCallback = HAL_I2C_SlaveTxCpltCallback;   /* Legacy weak SlaveTxCpltCallback  */
896         break;
897 
898       case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID :
899         hi2c->SlaveRxCpltCallback = HAL_I2C_SlaveRxCpltCallback;   /* Legacy weak SlaveRxCpltCallback  */
900         break;
901 
902       case HAL_I2C_LISTEN_COMPLETE_CB_ID :
903         hi2c->ListenCpltCallback = HAL_I2C_ListenCpltCallback;     /* Legacy weak ListenCpltCallback   */
904         break;
905 
906       case HAL_I2C_MEM_TX_COMPLETE_CB_ID :
907         hi2c->MemTxCpltCallback = HAL_I2C_MemTxCpltCallback;       /* Legacy weak MemTxCpltCallback    */
908         break;
909 
910       case HAL_I2C_MEM_RX_COMPLETE_CB_ID :
911         hi2c->MemRxCpltCallback = HAL_I2C_MemRxCpltCallback;       /* Legacy weak MemRxCpltCallback    */
912         break;
913 
914       case HAL_I2C_ERROR_CB_ID :
915         hi2c->ErrorCallback = HAL_I2C_ErrorCallback;               /* Legacy weak ErrorCallback        */
916         break;
917 
918       case HAL_I2C_ABORT_CB_ID :
919         hi2c->AbortCpltCallback = HAL_I2C_AbortCpltCallback;       /* Legacy weak AbortCpltCallback    */
920         break;
921 
922       case HAL_I2C_MSPINIT_CB_ID :
923         hi2c->MspInitCallback = HAL_I2C_MspInit;                   /* Legacy weak MspInit              */
924         break;
925 
926       case HAL_I2C_MSPDEINIT_CB_ID :
927         hi2c->MspDeInitCallback = HAL_I2C_MspDeInit;               /* Legacy weak MspDeInit            */
928         break;
929 
930       default :
931         /* Update the error code */
932         hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
933 
934         /* Return error status */
935         status =  HAL_ERROR;
936         break;
937     }
938   }
939   else if (HAL_I2C_STATE_RESET == hi2c->State)
940   {
941     switch (CallbackID)
942     {
943       case HAL_I2C_MSPINIT_CB_ID :
944         hi2c->MspInitCallback = HAL_I2C_MspInit;                   /* Legacy weak MspInit              */
945         break;
946 
947       case HAL_I2C_MSPDEINIT_CB_ID :
948         hi2c->MspDeInitCallback = HAL_I2C_MspDeInit;               /* Legacy weak MspDeInit            */
949         break;
950 
951       default :
952         /* Update the error code */
953         hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
954 
955         /* Return error status */
956         status =  HAL_ERROR;
957         break;
958     }
959   }
960   else
961   {
962     /* Update the error code */
963     hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
964 
965     /* Return error status */
966     status =  HAL_ERROR;
967   }
968 
969   return status;
970 }
971 
972 /**
973   * @brief  Register the Slave Address Match I2C Callback
974   *         To be used instead of the weak HAL_I2C_AddrCallback() predefined callback
975   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
976   *                the configuration information for the specified I2C.
977   * @param  pCallback pointer to the Address Match Callback function
978   * @retval HAL status
979   */
HAL_I2C_RegisterAddrCallback(I2C_HandleTypeDef * hi2c,pI2C_AddrCallbackTypeDef pCallback)980 HAL_StatusTypeDef HAL_I2C_RegisterAddrCallback(I2C_HandleTypeDef *hi2c, pI2C_AddrCallbackTypeDef pCallback)
981 {
982   HAL_StatusTypeDef status = HAL_OK;
983 
984   if (pCallback == NULL)
985   {
986     /* Update the error code */
987     hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
988 
989     return HAL_ERROR;
990   }
991 
992   if (HAL_I2C_STATE_READY == hi2c->State)
993   {
994     hi2c->AddrCallback = pCallback;
995   }
996   else
997   {
998     /* Update the error code */
999     hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
1000 
1001     /* Return error status */
1002     status =  HAL_ERROR;
1003   }
1004 
1005   return status;
1006 }
1007 
1008 /**
1009   * @brief  UnRegister the Slave Address Match I2C Callback
1010   *         Info Ready I2C Callback is redirected to the weak HAL_I2C_AddrCallback() predefined callback
1011   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1012   *                the configuration information for the specified I2C.
1013   * @retval HAL status
1014   */
HAL_I2C_UnRegisterAddrCallback(I2C_HandleTypeDef * hi2c)1015 HAL_StatusTypeDef HAL_I2C_UnRegisterAddrCallback(I2C_HandleTypeDef *hi2c)
1016 {
1017   HAL_StatusTypeDef status = HAL_OK;
1018 
1019   if (HAL_I2C_STATE_READY == hi2c->State)
1020   {
1021     hi2c->AddrCallback = HAL_I2C_AddrCallback; /* Legacy weak AddrCallback  */
1022   }
1023   else
1024   {
1025     /* Update the error code */
1026     hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
1027 
1028     /* Return error status */
1029     status =  HAL_ERROR;
1030   }
1031 
1032   return status;
1033 }
1034 
1035 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
1036 
1037 /**
1038   * @}
1039   */
1040 
1041 /** @defgroup I2C_Exported_Functions_Group2 Input and Output operation functions
1042   *  @brief   Data transfers functions
1043   *
1044 @verbatim
1045  ===============================================================================
1046                       ##### IO operation functions #####
1047  ===============================================================================
1048     [..]
1049     This subsection provides a set of functions allowing to manage the I2C data
1050     transfers.
1051 
1052     (#) There are two modes of transfer:
1053        (++) Blocking mode : The communication is performed in the polling mode.
1054             The status of all data processing is returned by the same function
1055             after finishing transfer.
1056        (++) No-Blocking mode : The communication is performed using Interrupts
1057             or DMA. These functions return the status of the transfer startup.
1058             The end of the data processing will be indicated through the
1059             dedicated I2C IRQ when using Interrupt mode or the DMA IRQ when
1060             using DMA mode.
1061 
1062     (#) Blocking mode functions are :
1063         (++) HAL_I2C_Master_Transmit()
1064         (++) HAL_I2C_Master_Receive()
1065         (++) HAL_I2C_Slave_Transmit()
1066         (++) HAL_I2C_Slave_Receive()
1067         (++) HAL_I2C_Mem_Write()
1068         (++) HAL_I2C_Mem_Read()
1069         (++) HAL_I2C_IsDeviceReady()
1070 
1071     (#) No-Blocking mode functions with Interrupt are :
1072         (++) HAL_I2C_Master_Transmit_IT()
1073         (++) HAL_I2C_Master_Receive_IT()
1074         (++) HAL_I2C_Slave_Transmit_IT()
1075         (++) HAL_I2C_Slave_Receive_IT()
1076         (++) HAL_I2C_Mem_Write_IT()
1077         (++) HAL_I2C_Mem_Read_IT()
1078         (++) HAL_I2C_Master_Seq_Transmit_IT()
1079         (++) HAL_I2C_Master_Seq_Receive_IT()
1080         (++) HAL_I2C_Slave_Seq_Transmit_IT()
1081         (++) HAL_I2C_Slave_Seq_Receive_IT()
1082         (++) HAL_I2C_EnableListen_IT()
1083         (++) HAL_I2C_DisableListen_IT()
1084         (++) HAL_I2C_Master_Abort_IT()
1085 
1086     (#) No-Blocking mode functions with DMA are :
1087         (++) HAL_I2C_Master_Transmit_DMA()
1088         (++) HAL_I2C_Master_Receive_DMA()
1089         (++) HAL_I2C_Slave_Transmit_DMA()
1090         (++) HAL_I2C_Slave_Receive_DMA()
1091         (++) HAL_I2C_Mem_Write_DMA()
1092         (++) HAL_I2C_Mem_Read_DMA()
1093         (++) HAL_I2C_Master_Seq_Transmit_DMA()
1094         (++) HAL_I2C_Master_Seq_Receive_DMA()
1095         (++) HAL_I2C_Slave_Seq_Transmit_DMA()
1096         (++) HAL_I2C_Slave_Seq_Receive_DMA()
1097 
1098     (#) A set of Transfer Complete Callbacks are provided in non Blocking mode:
1099         (++) HAL_I2C_MasterTxCpltCallback()
1100         (++) HAL_I2C_MasterRxCpltCallback()
1101         (++) HAL_I2C_SlaveTxCpltCallback()
1102         (++) HAL_I2C_SlaveRxCpltCallback()
1103         (++) HAL_I2C_MemTxCpltCallback()
1104         (++) HAL_I2C_MemRxCpltCallback()
1105         (++) HAL_I2C_AddrCallback()
1106         (++) HAL_I2C_ListenCpltCallback()
1107         (++) HAL_I2C_ErrorCallback()
1108         (++) HAL_I2C_AbortCpltCallback()
1109 
1110 @endverbatim
1111   * @{
1112   */
1113 
1114 /**
1115   * @brief  Transmits in master mode an amount of data in blocking mode.
1116   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1117   *                the configuration information for the specified I2C.
1118   * @param  DevAddress Target device address: The device 7 bits address value
1119   *         in datasheet must be shifted to the left before calling the interface
1120   * @param  pData Pointer to data buffer
1121   * @param  Size Amount of data to be sent
1122   * @param  Timeout Timeout duration
1123   * @retval HAL status
1124   */
HAL_I2C_Master_Transmit(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size,uint32_t Timeout)1125 HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
1126                                           uint16_t Size, uint32_t Timeout)
1127 {
1128   uint32_t tickstart;
1129 
1130   if (hi2c->State == HAL_I2C_STATE_READY)
1131   {
1132     /* Process Locked */
1133     __HAL_LOCK(hi2c);
1134 
1135     /* Init tickstart for timeout management*/
1136     tickstart = HAL_GetTick();
1137 
1138     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
1139     {
1140       return HAL_ERROR;
1141     }
1142 
1143     hi2c->State     = HAL_I2C_STATE_BUSY_TX;
1144     hi2c->Mode      = HAL_I2C_MODE_MASTER;
1145     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
1146 
1147     /* Prepare transfer parameters */
1148     hi2c->pBuffPtr  = pData;
1149     hi2c->XferCount = Size;
1150     hi2c->XferISR   = NULL;
1151 
1152     /* Send Slave Address */
1153     /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
1154     if (hi2c->XferCount > MAX_NBYTE_SIZE)
1155     {
1156       hi2c->XferSize = MAX_NBYTE_SIZE;
1157       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
1158                          I2C_GENERATE_START_WRITE);
1159     }
1160     else
1161     {
1162       hi2c->XferSize = hi2c->XferCount;
1163       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
1164                          I2C_GENERATE_START_WRITE);
1165     }
1166 
1167     while (hi2c->XferCount > 0U)
1168     {
1169       /* Wait until TXIS flag is set */
1170       if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
1171       {
1172         return HAL_ERROR;
1173       }
1174       /* Write data to TXDR */
1175       hi2c->Instance->TXDR = *hi2c->pBuffPtr;
1176 
1177       /* Increment Buffer pointer */
1178       hi2c->pBuffPtr++;
1179 
1180       hi2c->XferCount--;
1181       hi2c->XferSize--;
1182 
1183       if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
1184       {
1185         /* Wait until TCR flag is set */
1186         if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
1187         {
1188           return HAL_ERROR;
1189         }
1190 
1191         if (hi2c->XferCount > MAX_NBYTE_SIZE)
1192         {
1193           hi2c->XferSize = MAX_NBYTE_SIZE;
1194           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
1195                              I2C_NO_STARTSTOP);
1196         }
1197         else
1198         {
1199           hi2c->XferSize = hi2c->XferCount;
1200           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
1201                              I2C_NO_STARTSTOP);
1202         }
1203       }
1204     }
1205 
1206     /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
1207     /* Wait until STOPF flag is set */
1208     if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
1209     {
1210       return HAL_ERROR;
1211     }
1212 
1213     /* Clear STOP Flag */
1214     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
1215 
1216     /* Clear Configuration Register 2 */
1217     I2C_RESET_CR2(hi2c);
1218 
1219     hi2c->State = HAL_I2C_STATE_READY;
1220     hi2c->Mode  = HAL_I2C_MODE_NONE;
1221 
1222     /* Process Unlocked */
1223     __HAL_UNLOCK(hi2c);
1224 
1225     return HAL_OK;
1226   }
1227   else
1228   {
1229     return HAL_BUSY;
1230   }
1231 }
1232 
1233 /**
1234   * @brief  Receives in master mode an amount of data in blocking mode.
1235   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1236   *                the configuration information for the specified I2C.
1237   * @param  DevAddress Target device address: The device 7 bits address value
1238   *         in datasheet must be shifted to the left before calling the interface
1239   * @param  pData Pointer to data buffer
1240   * @param  Size Amount of data to be sent
1241   * @param  Timeout Timeout duration
1242   * @retval HAL status
1243   */
HAL_I2C_Master_Receive(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size,uint32_t Timeout)1244 HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
1245                                          uint16_t Size, uint32_t Timeout)
1246 {
1247   uint32_t tickstart;
1248 
1249   if (hi2c->State == HAL_I2C_STATE_READY)
1250   {
1251     /* Process Locked */
1252     __HAL_LOCK(hi2c);
1253 
1254     /* Init tickstart for timeout management*/
1255     tickstart = HAL_GetTick();
1256 
1257     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
1258     {
1259       return HAL_ERROR;
1260     }
1261 
1262     hi2c->State     = HAL_I2C_STATE_BUSY_RX;
1263     hi2c->Mode      = HAL_I2C_MODE_MASTER;
1264     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
1265 
1266     /* Prepare transfer parameters */
1267     hi2c->pBuffPtr  = pData;
1268     hi2c->XferCount = Size;
1269     hi2c->XferISR   = NULL;
1270 
1271     /* Send Slave Address */
1272     /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
1273     if (hi2c->XferCount > MAX_NBYTE_SIZE)
1274     {
1275       hi2c->XferSize = MAX_NBYTE_SIZE;
1276       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
1277                          I2C_GENERATE_START_READ);
1278     }
1279     else
1280     {
1281       hi2c->XferSize = hi2c->XferCount;
1282       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
1283                          I2C_GENERATE_START_READ);
1284     }
1285 
1286     while (hi2c->XferCount > 0U)
1287     {
1288       /* Wait until RXNE flag is set */
1289       if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
1290       {
1291         return HAL_ERROR;
1292       }
1293 
1294       /* Read data from RXDR */
1295       *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
1296 
1297       /* Increment Buffer pointer */
1298       hi2c->pBuffPtr++;
1299 
1300       hi2c->XferSize--;
1301       hi2c->XferCount--;
1302 
1303       if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
1304       {
1305         /* Wait until TCR flag is set */
1306         if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
1307         {
1308           return HAL_ERROR;
1309         }
1310 
1311         if (hi2c->XferCount > MAX_NBYTE_SIZE)
1312         {
1313           hi2c->XferSize = MAX_NBYTE_SIZE;
1314           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
1315                              I2C_NO_STARTSTOP);
1316         }
1317         else
1318         {
1319           hi2c->XferSize = hi2c->XferCount;
1320           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
1321                              I2C_NO_STARTSTOP);
1322         }
1323       }
1324     }
1325 
1326     /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
1327     /* Wait until STOPF flag is set */
1328     if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
1329     {
1330       return HAL_ERROR;
1331     }
1332 
1333     /* Clear STOP Flag */
1334     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
1335 
1336     /* Clear Configuration Register 2 */
1337     I2C_RESET_CR2(hi2c);
1338 
1339     hi2c->State = HAL_I2C_STATE_READY;
1340     hi2c->Mode  = HAL_I2C_MODE_NONE;
1341 
1342     /* Process Unlocked */
1343     __HAL_UNLOCK(hi2c);
1344 
1345     return HAL_OK;
1346   }
1347   else
1348   {
1349     return HAL_BUSY;
1350   }
1351 }
1352 
1353 /**
1354   * @brief  Transmits in slave mode an amount of data in blocking mode.
1355   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1356   *                the configuration information for the specified I2C.
1357   * @param  pData Pointer to data buffer
1358   * @param  Size Amount of data to be sent
1359   * @param  Timeout Timeout duration
1360   * @retval HAL status
1361   */
HAL_I2C_Slave_Transmit(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size,uint32_t Timeout)1362 HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
1363                                          uint32_t Timeout)
1364 {
1365   uint32_t tickstart;
1366   uint16_t tmpXferCount;
1367   HAL_StatusTypeDef error;
1368 
1369   if (hi2c->State == HAL_I2C_STATE_READY)
1370   {
1371     if ((pData == NULL) || (Size == 0U))
1372     {
1373       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
1374       return  HAL_ERROR;
1375     }
1376     /* Process Locked */
1377     __HAL_LOCK(hi2c);
1378 
1379     /* Init tickstart for timeout management*/
1380     tickstart = HAL_GetTick();
1381 
1382     hi2c->State     = HAL_I2C_STATE_BUSY_TX;
1383     hi2c->Mode      = HAL_I2C_MODE_SLAVE;
1384     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
1385 
1386     /* Prepare transfer parameters */
1387     hi2c->pBuffPtr  = pData;
1388     hi2c->XferCount = Size;
1389     hi2c->XferISR   = NULL;
1390 
1391     /* Enable Address Acknowledge */
1392     hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
1393 
1394     /* Preload TX data if no stretch enable */
1395     if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE)
1396     {
1397       /* Preload TX register */
1398       /* Write data to TXDR */
1399       hi2c->Instance->TXDR = *hi2c->pBuffPtr;
1400 
1401       /* Increment Buffer pointer */
1402       hi2c->pBuffPtr++;
1403 
1404       hi2c->XferCount--;
1405     }
1406 
1407     /* Wait until ADDR flag is set */
1408     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
1409     {
1410       /* Disable Address Acknowledge */
1411       hi2c->Instance->CR2 |= I2C_CR2_NACK;
1412 
1413       /* Flush TX register */
1414       I2C_Flush_TXDR(hi2c);
1415 
1416       return HAL_ERROR;
1417     }
1418 
1419     /* Clear ADDR flag */
1420     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
1421 
1422     /* If 10bit addressing mode is selected */
1423     if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)
1424     {
1425       /* Wait until ADDR flag is set */
1426       if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
1427       {
1428         /* Disable Address Acknowledge */
1429         hi2c->Instance->CR2 |= I2C_CR2_NACK;
1430 
1431         /* Flush TX register */
1432         I2C_Flush_TXDR(hi2c);
1433 
1434         return HAL_ERROR;
1435       }
1436 
1437       /* Clear ADDR flag */
1438       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
1439     }
1440 
1441     /* Wait until DIR flag is set Transmitter mode */
1442     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, RESET, Timeout, tickstart) != HAL_OK)
1443     {
1444       /* Disable Address Acknowledge */
1445       hi2c->Instance->CR2 |= I2C_CR2_NACK;
1446 
1447       /* Flush TX register */
1448       I2C_Flush_TXDR(hi2c);
1449 
1450       return HAL_ERROR;
1451     }
1452 
1453     while (hi2c->XferCount > 0U)
1454     {
1455       /* Wait until TXIS flag is set */
1456       if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
1457       {
1458         /* Disable Address Acknowledge */
1459         hi2c->Instance->CR2 |= I2C_CR2_NACK;
1460         return HAL_ERROR;
1461       }
1462 
1463       /* Write data to TXDR */
1464       hi2c->Instance->TXDR = *hi2c->pBuffPtr;
1465 
1466       /* Increment Buffer pointer */
1467       hi2c->pBuffPtr++;
1468 
1469       hi2c->XferCount--;
1470     }
1471 
1472     /* Wait until AF flag is set */
1473     error = I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart);
1474 
1475     if (error != HAL_OK)
1476     {
1477       /* Check that I2C transfer finished */
1478       /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */
1479       /* Mean XferCount == 0 */
1480 
1481       tmpXferCount = hi2c->XferCount;
1482       if ((hi2c->ErrorCode == HAL_I2C_ERROR_AF) && (tmpXferCount == 0U))
1483       {
1484         /* Reset ErrorCode to NONE */
1485         hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
1486       }
1487       else
1488       {
1489         /* Disable Address Acknowledge */
1490         hi2c->Instance->CR2 |= I2C_CR2_NACK;
1491         return HAL_ERROR;
1492       }
1493     }
1494     else
1495     {
1496       /* Flush TX register */
1497       I2C_Flush_TXDR(hi2c);
1498 
1499       /* Clear AF flag */
1500       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
1501 
1502       /* Wait until STOP flag is set */
1503       if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
1504       {
1505         /* Disable Address Acknowledge */
1506         hi2c->Instance->CR2 |= I2C_CR2_NACK;
1507 
1508         return HAL_ERROR;
1509       }
1510 
1511       /* Clear STOP flag */
1512       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
1513     }
1514 
1515     /* Wait until BUSY flag is reset */
1516     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK)
1517     {
1518       /* Disable Address Acknowledge */
1519       hi2c->Instance->CR2 |= I2C_CR2_NACK;
1520       return HAL_ERROR;
1521     }
1522 
1523     /* Disable Address Acknowledge */
1524     hi2c->Instance->CR2 |= I2C_CR2_NACK;
1525 
1526     hi2c->State = HAL_I2C_STATE_READY;
1527     hi2c->Mode  = HAL_I2C_MODE_NONE;
1528 
1529     /* Process Unlocked */
1530     __HAL_UNLOCK(hi2c);
1531 
1532     return HAL_OK;
1533   }
1534   else
1535   {
1536     return HAL_BUSY;
1537   }
1538 }
1539 
1540 /**
1541   * @brief  Receive in slave mode an amount of data in blocking mode
1542   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1543   *                the configuration information for the specified I2C.
1544   * @param  pData Pointer to data buffer
1545   * @param  Size Amount of data to be sent
1546   * @param  Timeout Timeout duration
1547   * @retval HAL status
1548   */
HAL_I2C_Slave_Receive(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size,uint32_t Timeout)1549 HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
1550                                         uint32_t Timeout)
1551 {
1552   uint32_t tickstart;
1553 
1554   if (hi2c->State == HAL_I2C_STATE_READY)
1555   {
1556     if ((pData == NULL) || (Size == 0U))
1557     {
1558       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
1559       return  HAL_ERROR;
1560     }
1561     /* Process Locked */
1562     __HAL_LOCK(hi2c);
1563 
1564     /* Init tickstart for timeout management*/
1565     tickstart = HAL_GetTick();
1566 
1567     hi2c->State     = HAL_I2C_STATE_BUSY_RX;
1568     hi2c->Mode      = HAL_I2C_MODE_SLAVE;
1569     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
1570 
1571     /* Prepare transfer parameters */
1572     hi2c->pBuffPtr  = pData;
1573     hi2c->XferCount = Size;
1574     hi2c->XferSize = hi2c->XferCount;
1575     hi2c->XferISR   = NULL;
1576 
1577     /* Enable Address Acknowledge */
1578     hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
1579 
1580     /* Wait until ADDR flag is set */
1581     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
1582     {
1583       /* Disable Address Acknowledge */
1584       hi2c->Instance->CR2 |= I2C_CR2_NACK;
1585       return HAL_ERROR;
1586     }
1587 
1588     /* Clear ADDR flag */
1589     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
1590 
1591     /* Wait until DIR flag is reset Receiver mode */
1592     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, SET, Timeout, tickstart) != HAL_OK)
1593     {
1594       /* Disable Address Acknowledge */
1595       hi2c->Instance->CR2 |= I2C_CR2_NACK;
1596       return HAL_ERROR;
1597     }
1598 
1599     while (hi2c->XferCount > 0U)
1600     {
1601       /* Wait until RXNE flag is set */
1602       if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
1603       {
1604         /* Disable Address Acknowledge */
1605         hi2c->Instance->CR2 |= I2C_CR2_NACK;
1606 
1607         /* Store Last receive data if any */
1608         if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET)
1609         {
1610           /* Read data from RXDR */
1611           *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
1612 
1613           /* Increment Buffer pointer */
1614           hi2c->pBuffPtr++;
1615 
1616           hi2c->XferCount--;
1617           hi2c->XferSize--;
1618         }
1619 
1620         return HAL_ERROR;
1621       }
1622 
1623       /* Read data from RXDR */
1624       *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
1625 
1626       /* Increment Buffer pointer */
1627       hi2c->pBuffPtr++;
1628 
1629       hi2c->XferCount--;
1630       hi2c->XferSize--;
1631     }
1632 
1633     /* Wait until STOP flag is set */
1634     if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
1635     {
1636       /* Disable Address Acknowledge */
1637       hi2c->Instance->CR2 |= I2C_CR2_NACK;
1638       return HAL_ERROR;
1639     }
1640 
1641     /* Clear STOP flag */
1642     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
1643 
1644     /* Wait until BUSY flag is reset */
1645     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK)
1646     {
1647       /* Disable Address Acknowledge */
1648       hi2c->Instance->CR2 |= I2C_CR2_NACK;
1649       return HAL_ERROR;
1650     }
1651 
1652     /* Disable Address Acknowledge */
1653     hi2c->Instance->CR2 |= I2C_CR2_NACK;
1654 
1655     hi2c->State = HAL_I2C_STATE_READY;
1656     hi2c->Mode  = HAL_I2C_MODE_NONE;
1657 
1658     /* Process Unlocked */
1659     __HAL_UNLOCK(hi2c);
1660 
1661     return HAL_OK;
1662   }
1663   else
1664   {
1665     return HAL_BUSY;
1666   }
1667 }
1668 
1669 /**
1670   * @brief  Transmit in master mode an amount of data in non-blocking mode with Interrupt
1671   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1672   *                the configuration information for the specified I2C.
1673   * @param  DevAddress Target device address: The device 7 bits address value
1674   *         in datasheet must be shifted to the left before calling the interface
1675   * @param  pData Pointer to data buffer
1676   * @param  Size Amount of data to be sent
1677   * @retval HAL status
1678   */
HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size)1679 HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
1680                                              uint16_t Size)
1681 {
1682   uint32_t xfermode;
1683 
1684   if (hi2c->State == HAL_I2C_STATE_READY)
1685   {
1686     if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
1687     {
1688       return HAL_BUSY;
1689     }
1690 
1691     /* Process Locked */
1692     __HAL_LOCK(hi2c);
1693 
1694     hi2c->State       = HAL_I2C_STATE_BUSY_TX;
1695     hi2c->Mode        = HAL_I2C_MODE_MASTER;
1696     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
1697 
1698     /* Prepare transfer parameters */
1699     hi2c->pBuffPtr    = pData;
1700     hi2c->XferCount   = Size;
1701     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
1702     hi2c->XferISR     = I2C_Master_ISR_IT;
1703 
1704     if (hi2c->XferCount > MAX_NBYTE_SIZE)
1705     {
1706       hi2c->XferSize = MAX_NBYTE_SIZE;
1707       xfermode = I2C_RELOAD_MODE;
1708     }
1709     else
1710     {
1711       hi2c->XferSize = hi2c->XferCount;
1712       xfermode = I2C_AUTOEND_MODE;
1713     }
1714 
1715     /* Send Slave Address */
1716     /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */
1717     /* Check if the Autonomous mode is enabled */
1718     if ((hi2c->Instance->AUTOCR & I2C_AUTOCR_TRIGEN) == I2C_AUTOCR_TRIGEN)
1719     {
1720       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_NO_START_WRITE);
1721     }
1722     else
1723     {
1724       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_WRITE);
1725     }
1726 
1727     /* Process Unlocked */
1728     __HAL_UNLOCK(hi2c);
1729 
1730     /* Note : The I2C interrupts must be enabled after unlocking current process
1731               to avoid the risk of I2C interrupt handle execution before current
1732               process unlock */
1733 
1734     /* Enable ERR, TC, STOP, NACK, TXI interrupt */
1735     /* possible to enable all of these */
1736     /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
1737       I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
1738     I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
1739 
1740     return HAL_OK;
1741   }
1742   else
1743   {
1744     return HAL_BUSY;
1745   }
1746 }
1747 
1748 /**
1749   * @brief  Receive in master mode an amount of data in non-blocking mode with Interrupt
1750   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1751   *                the configuration information for the specified I2C.
1752   * @param  DevAddress Target device address: The device 7 bits address value
1753   *         in datasheet must be shifted to the left before calling the interface
1754   * @param  pData Pointer to data buffer
1755   * @param  Size Amount of data to be sent
1756   * @retval HAL status
1757   */
HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size)1758 HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
1759                                             uint16_t Size)
1760 {
1761   uint32_t xfermode;
1762 
1763   if (hi2c->State == HAL_I2C_STATE_READY)
1764   {
1765     if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
1766     {
1767       return HAL_BUSY;
1768     }
1769 
1770     /* Process Locked */
1771     __HAL_LOCK(hi2c);
1772 
1773     hi2c->State       = HAL_I2C_STATE_BUSY_RX;
1774     hi2c->Mode        = HAL_I2C_MODE_MASTER;
1775     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
1776 
1777     /* Prepare transfer parameters */
1778     hi2c->pBuffPtr    = pData;
1779     hi2c->XferCount   = Size;
1780     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
1781     hi2c->XferISR     = I2C_Master_ISR_IT;
1782 
1783     if (hi2c->XferCount > MAX_NBYTE_SIZE)
1784     {
1785       hi2c->XferSize = MAX_NBYTE_SIZE;
1786       xfermode = I2C_RELOAD_MODE;
1787     }
1788     else
1789     {
1790       hi2c->XferSize = hi2c->XferCount;
1791       xfermode = I2C_AUTOEND_MODE;
1792     }
1793 
1794     /* Send Slave Address */
1795     /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */
1796     /* Check if the Autonomous mode is enabled */
1797     if ((hi2c->Instance->AUTOCR & I2C_AUTOCR_TRIGEN) == I2C_AUTOCR_TRIGEN)
1798     {
1799       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_NO_START_READ);
1800     }
1801     else
1802     {
1803       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ);
1804     }
1805 
1806     /* Process Unlocked */
1807     __HAL_UNLOCK(hi2c);
1808 
1809     /* Note : The I2C interrupts must be enabled after unlocking current process
1810               to avoid the risk of I2C interrupt handle execution before current
1811               process unlock */
1812 
1813     /* Enable ERR, TC, STOP, NACK, RXI interrupt */
1814     /* possible to enable all of these */
1815     /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
1816       I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
1817     I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT);
1818 
1819     return HAL_OK;
1820   }
1821   else
1822   {
1823     return HAL_BUSY;
1824   }
1825 }
1826 
1827 /**
1828   * @brief  Transmit in slave mode an amount of data in non-blocking mode with Interrupt
1829   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1830   *                the configuration information for the specified I2C.
1831   * @param  pData Pointer to data buffer
1832   * @param  Size Amount of data to be sent
1833   * @retval HAL status
1834   */
HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size)1835 HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
1836 {
1837   if (hi2c->State == HAL_I2C_STATE_READY)
1838   {
1839     /* Process Locked */
1840     __HAL_LOCK(hi2c);
1841 
1842     hi2c->State       = HAL_I2C_STATE_BUSY_TX;
1843     hi2c->Mode        = HAL_I2C_MODE_SLAVE;
1844     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
1845 
1846     /* Enable Address Acknowledge */
1847     hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
1848 
1849     /* Prepare transfer parameters */
1850     hi2c->pBuffPtr    = pData;
1851     hi2c->XferCount   = Size;
1852     hi2c->XferSize    = hi2c->XferCount;
1853     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
1854     hi2c->XferISR     = I2C_Slave_ISR_IT;
1855 
1856     /* Preload TX data if no stretch enable */
1857     if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE)
1858     {
1859       /* Preload TX register */
1860       /* Write data to TXDR */
1861       hi2c->Instance->TXDR = *hi2c->pBuffPtr;
1862 
1863       /* Increment Buffer pointer */
1864       hi2c->pBuffPtr++;
1865 
1866       hi2c->XferCount--;
1867       hi2c->XferSize--;
1868     }
1869 
1870     /* Process Unlocked */
1871     __HAL_UNLOCK(hi2c);
1872 
1873     /* Note : The I2C interrupts must be enabled after unlocking current process
1874               to avoid the risk of I2C interrupt handle execution before current
1875               process unlock */
1876 
1877     /* Enable ERR, TC, STOP, NACK, TXI interrupt */
1878     /* possible to enable all of these */
1879     /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
1880       I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
1881     I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT | I2C_XFER_LISTEN_IT);
1882 
1883     return HAL_OK;
1884   }
1885   else
1886   {
1887     return HAL_BUSY;
1888   }
1889 }
1890 
1891 /**
1892   * @brief  Receive in slave mode an amount of data in non-blocking mode with Interrupt
1893   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1894   *                the configuration information for the specified I2C.
1895   * @param  pData Pointer to data buffer
1896   * @param  Size Amount of data to be sent
1897   * @retval HAL status
1898   */
HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size)1899 HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
1900 {
1901   if (hi2c->State == HAL_I2C_STATE_READY)
1902   {
1903     /* Process Locked */
1904     __HAL_LOCK(hi2c);
1905 
1906     hi2c->State       = HAL_I2C_STATE_BUSY_RX;
1907     hi2c->Mode        = HAL_I2C_MODE_SLAVE;
1908     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
1909 
1910     /* Enable Address Acknowledge */
1911     hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
1912 
1913     /* Prepare transfer parameters */
1914     hi2c->pBuffPtr    = pData;
1915     hi2c->XferCount   = Size;
1916     hi2c->XferSize    = hi2c->XferCount;
1917     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
1918     hi2c->XferISR     = I2C_Slave_ISR_IT;
1919 
1920     /* Process Unlocked */
1921     __HAL_UNLOCK(hi2c);
1922 
1923     /* Note : The I2C interrupts must be enabled after unlocking current process
1924               to avoid the risk of I2C interrupt handle execution before current
1925               process unlock */
1926 
1927     /* Enable ERR, TC, STOP, NACK, RXI interrupt */
1928     /* possible to enable all of these */
1929     /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
1930       I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
1931     I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT);
1932 
1933     return HAL_OK;
1934   }
1935   else
1936   {
1937     return HAL_BUSY;
1938   }
1939 }
1940 
1941 #if defined(HAL_DMA_MODULE_ENABLED)
1942 /**
1943   * @brief  Transmit in master mode an amount of data in non-blocking mode with DMA
1944   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
1945   *                the configuration information for the specified I2C.
1946   * @param  DevAddress Target device address: The device 7 bits address value
1947   *         in datasheet must be shifted to the left before calling the interface
1948   * @param  pData Pointer to data buffer
1949   * @param  Size Amount of data to be sent
1950   * @retval HAL status
1951   */
HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size)1952 HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
1953                                               uint16_t Size)
1954 {
1955   uint32_t xfermode;
1956   HAL_StatusTypeDef dmaxferstatus;
1957 
1958   if (hi2c->State == HAL_I2C_STATE_READY)
1959   {
1960     if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
1961     {
1962       return HAL_BUSY;
1963     }
1964 
1965     /* Process Locked */
1966     __HAL_LOCK(hi2c);
1967 
1968     hi2c->State       = HAL_I2C_STATE_BUSY_TX;
1969     hi2c->Mode        = HAL_I2C_MODE_MASTER;
1970     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
1971 
1972     /* Prepare transfer parameters */
1973     hi2c->pBuffPtr    = pData;
1974     hi2c->XferCount   = Size;
1975     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
1976     hi2c->XferISR     = I2C_Master_ISR_DMA;
1977 
1978     if (hi2c->XferCount > MAX_NBYTE_SIZE)
1979     {
1980       hi2c->XferSize = MAX_NBYTE_SIZE;
1981       xfermode = I2C_RELOAD_MODE;
1982     }
1983     else
1984     {
1985       hi2c->XferSize = hi2c->XferCount;
1986       xfermode = I2C_AUTOEND_MODE;
1987     }
1988 
1989     if (hi2c->XferSize > 0U)
1990     {
1991       if (hi2c->hdmatx != NULL)
1992       {
1993         /* Set the I2C DMA transfer complete callback */
1994         hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt;
1995 
1996         /* Set the DMA error callback */
1997         hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
1998 
1999         /* Set the unused DMA callbacks to NULL */
2000         hi2c->hdmatx->XferHalfCpltCallback = NULL;
2001         hi2c->hdmatx->XferAbortCallback = NULL;
2002 
2003         /* Enable the DMA channel */
2004         if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
2005         {
2006           if (hi2c->hdmatx->LinkedListQueue != NULL)
2007           {
2008             /* Set DMA data size */
2009             hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
2010 
2011             /* Set DMA source address */
2012             hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData;
2013 
2014             /* Set DMA destination address */
2015             hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \
2016               = (uint32_t)&hi2c->Instance->TXDR;
2017 
2018             dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx);
2019           }
2020           else
2021           {
2022             /* Update I2C state */
2023             hi2c->State     = HAL_I2C_STATE_READY;
2024             hi2c->Mode      = HAL_I2C_MODE_NONE;
2025 
2026             /* Update I2C error code */
2027             hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
2028 
2029             /* Process Unlocked */
2030             __HAL_UNLOCK(hi2c);
2031 
2032             return HAL_ERROR;
2033           }
2034         }
2035         else
2036         {
2037           dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR,
2038                                            hi2c->XferSize);
2039         }
2040       }
2041       else
2042       {
2043         /* Update I2C state */
2044         hi2c->State     = HAL_I2C_STATE_READY;
2045         hi2c->Mode      = HAL_I2C_MODE_NONE;
2046 
2047         /* Update I2C error code */
2048         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
2049 
2050         /* Process Unlocked */
2051         __HAL_UNLOCK(hi2c);
2052 
2053         return HAL_ERROR;
2054       }
2055 
2056       if (dmaxferstatus == HAL_OK)
2057       {
2058         /* Send Slave Address */
2059         /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
2060         /* Check if the Autonomous mode is enabled */
2061         if ((hi2c->Instance->AUTOCR & I2C_AUTOCR_TRIGEN) == I2C_AUTOCR_TRIGEN)
2062         {
2063           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode,
2064                              I2C_GENERATE_NO_START_WRITE);
2065         }
2066         else
2067         {
2068           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_WRITE);
2069         }
2070 
2071         /* Update XferCount value */
2072         hi2c->XferCount -= hi2c->XferSize;
2073 
2074         /* Process Unlocked */
2075         __HAL_UNLOCK(hi2c);
2076 
2077         /* Note : The I2C interrupts must be enabled after unlocking current process
2078                   to avoid the risk of I2C interrupt handle execution before current
2079                   process unlock */
2080         /* Enable ERR and NACK interrupts */
2081         I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
2082 
2083         /* Enable DMA Request */
2084         hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
2085       }
2086       else
2087       {
2088         /* Update I2C state */
2089         hi2c->State     = HAL_I2C_STATE_READY;
2090         hi2c->Mode      = HAL_I2C_MODE_NONE;
2091 
2092         /* Update I2C error code */
2093         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
2094 
2095         /* Process Unlocked */
2096         __HAL_UNLOCK(hi2c);
2097 
2098         return HAL_ERROR;
2099       }
2100     }
2101     else
2102     {
2103       /* Update Transfer ISR function pointer */
2104       hi2c->XferISR = I2C_Master_ISR_IT;
2105 
2106       /* Send Slave Address */
2107       /* Set NBYTES to write and generate START condition */
2108       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
2109                          I2C_GENERATE_START_WRITE);
2110 
2111       /* Process Unlocked */
2112       __HAL_UNLOCK(hi2c);
2113 
2114       /* Note : The I2C interrupts must be enabled after unlocking current process
2115                 to avoid the risk of I2C interrupt handle execution before current
2116                 process unlock */
2117       /* Enable ERR, TC, STOP, NACK, TXI interrupt */
2118       /* possible to enable all of these */
2119       /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
2120         I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
2121       I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
2122     }
2123 
2124     return HAL_OK;
2125   }
2126   else
2127   {
2128     return HAL_BUSY;
2129   }
2130 }
2131 
2132 /**
2133   * @brief  Receive in master mode an amount of data in non-blocking mode with DMA
2134   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
2135   *                the configuration information for the specified I2C.
2136   * @param  DevAddress Target device address: The device 7 bits address value
2137   *         in datasheet must be shifted to the left before calling the interface
2138   * @param  pData Pointer to data buffer
2139   * @param  Size Amount of data to be sent
2140   * @retval HAL status
2141   */
HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size)2142 HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
2143                                              uint16_t Size)
2144 {
2145   uint32_t xfermode;
2146   HAL_StatusTypeDef dmaxferstatus;
2147 
2148   if (hi2c->State == HAL_I2C_STATE_READY)
2149   {
2150     if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
2151     {
2152       return HAL_BUSY;
2153     }
2154 
2155     /* Process Locked */
2156     __HAL_LOCK(hi2c);
2157 
2158     hi2c->State       = HAL_I2C_STATE_BUSY_RX;
2159     hi2c->Mode        = HAL_I2C_MODE_MASTER;
2160     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
2161 
2162     /* Prepare transfer parameters */
2163     hi2c->pBuffPtr    = pData;
2164     hi2c->XferCount   = Size;
2165     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
2166     hi2c->XferISR     = I2C_Master_ISR_DMA;
2167 
2168     if (hi2c->XferCount > MAX_NBYTE_SIZE)
2169     {
2170       hi2c->XferSize = MAX_NBYTE_SIZE;
2171       xfermode = I2C_RELOAD_MODE;
2172     }
2173     else
2174     {
2175       hi2c->XferSize = hi2c->XferCount;
2176       xfermode = I2C_AUTOEND_MODE;
2177     }
2178 
2179     if (hi2c->XferSize > 0U)
2180     {
2181       if (hi2c->hdmarx != NULL)
2182       {
2183         /* Set the I2C DMA transfer complete callback */
2184         hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt;
2185 
2186         /* Set the DMA error callback */
2187         hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
2188 
2189         /* Set the unused DMA callbacks to NULL */
2190         hi2c->hdmarx->XferHalfCpltCallback = NULL;
2191         hi2c->hdmarx->XferAbortCallback = NULL;
2192 
2193         /* Enable the DMA channel */
2194         if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
2195         {
2196           if (hi2c->hdmarx->LinkedListQueue != NULL)
2197           {
2198             /* Set DMA data size */
2199             hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
2200 
2201             /* Set DMA source address */
2202             hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \
2203               = (uint32_t)&hi2c->Instance->RXDR;
2204 
2205             /* Set DMA destination address */
2206             hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData;
2207 
2208             dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx);
2209           }
2210           else
2211           {
2212             /* Update I2C state */
2213             hi2c->State     = HAL_I2C_STATE_READY;
2214             hi2c->Mode      = HAL_I2C_MODE_NONE;
2215 
2216             /* Update I2C error code */
2217             hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
2218 
2219             /* Process Unlocked */
2220             __HAL_UNLOCK(hi2c);
2221 
2222             return HAL_ERROR;
2223           }
2224         }
2225         else
2226         {
2227           dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData,
2228                                            hi2c->XferSize);
2229         }
2230       }
2231       else
2232       {
2233         /* Update I2C state */
2234         hi2c->State     = HAL_I2C_STATE_READY;
2235         hi2c->Mode      = HAL_I2C_MODE_NONE;
2236 
2237         /* Update I2C error code */
2238         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
2239 
2240         /* Process Unlocked */
2241         __HAL_UNLOCK(hi2c);
2242 
2243         return HAL_ERROR;
2244       }
2245 
2246       if (dmaxferstatus == HAL_OK)
2247       {
2248         /* Send Slave Address */
2249         /* Set NBYTES to read and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
2250         /* Check if the Autonomous mode is enabled */
2251         if ((hi2c->Instance->AUTOCR & I2C_AUTOCR_TRIGEN) == I2C_AUTOCR_TRIGEN)
2252         {
2253           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode,
2254                              I2C_GENERATE_NO_START_READ);
2255         }
2256         else
2257         {
2258           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ);
2259         }
2260 
2261         /* Update XferCount value */
2262         hi2c->XferCount -= hi2c->XferSize;
2263 
2264         /* Process Unlocked */
2265         __HAL_UNLOCK(hi2c);
2266 
2267         /* Note : The I2C interrupts must be enabled after unlocking current process
2268                   to avoid the risk of I2C interrupt handle execution before current
2269                   process unlock */
2270         /* Enable ERR and NACK interrupts */
2271         I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
2272 
2273         /* Enable DMA Request */
2274         hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
2275       }
2276       else
2277       {
2278         /* Update I2C state */
2279         hi2c->State     = HAL_I2C_STATE_READY;
2280         hi2c->Mode      = HAL_I2C_MODE_NONE;
2281 
2282         /* Update I2C error code */
2283         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
2284 
2285         /* Process Unlocked */
2286         __HAL_UNLOCK(hi2c);
2287 
2288         return HAL_ERROR;
2289       }
2290     }
2291     else
2292     {
2293       /* Update Transfer ISR function pointer */
2294       hi2c->XferISR = I2C_Master_ISR_IT;
2295 
2296       /* Send Slave Address */
2297       /* Set NBYTES to read and generate START condition */
2298       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
2299                          I2C_GENERATE_START_READ);
2300 
2301       /* Process Unlocked */
2302       __HAL_UNLOCK(hi2c);
2303 
2304       /* Note : The I2C interrupts must be enabled after unlocking current process
2305                 to avoid the risk of I2C interrupt handle execution before current
2306                 process unlock */
2307       /* Enable ERR, TC, STOP, NACK, RXI interrupt */
2308       /* possible to enable all of these */
2309       /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
2310         I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
2311       I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT);
2312     }
2313 
2314     return HAL_OK;
2315   }
2316   else
2317   {
2318     return HAL_BUSY;
2319   }
2320 }
2321 
2322 /**
2323   * @brief  Transmit in slave mode an amount of data in non-blocking mode with DMA
2324   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
2325   *                the configuration information for the specified I2C.
2326   * @param  pData Pointer to data buffer
2327   * @param  Size Amount of data to be sent
2328   * @retval HAL status
2329   */
HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size)2330 HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
2331 {
2332   HAL_StatusTypeDef dmaxferstatus;
2333 
2334   if (hi2c->State == HAL_I2C_STATE_READY)
2335   {
2336     if ((pData == NULL) || (Size == 0U))
2337     {
2338       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
2339       return  HAL_ERROR;
2340     }
2341     /* Process Locked */
2342     __HAL_LOCK(hi2c);
2343 
2344     hi2c->State       = HAL_I2C_STATE_BUSY_TX;
2345     hi2c->Mode        = HAL_I2C_MODE_SLAVE;
2346     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
2347 
2348     /* Prepare transfer parameters */
2349     hi2c->pBuffPtr    = pData;
2350     hi2c->XferCount   = Size;
2351     hi2c->XferSize    = hi2c->XferCount;
2352     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
2353     hi2c->XferISR     = I2C_Slave_ISR_DMA;
2354 
2355     /* Preload TX data if no stretch enable */
2356     if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE)
2357     {
2358       /* Preload TX register */
2359       /* Write data to TXDR */
2360       hi2c->Instance->TXDR = *hi2c->pBuffPtr;
2361 
2362       /* Increment Buffer pointer */
2363       hi2c->pBuffPtr++;
2364 
2365       hi2c->XferCount--;
2366       hi2c->XferSize--;
2367     }
2368 
2369     if (hi2c->XferCount != 0U)
2370     {
2371       if (hi2c->hdmatx != NULL)
2372       {
2373         /* Set the I2C DMA transfer complete callback */
2374         hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt;
2375 
2376         /* Set the DMA error callback */
2377         hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
2378 
2379         /* Set the unused DMA callbacks to NULL */
2380         hi2c->hdmatx->XferHalfCpltCallback = NULL;
2381         hi2c->hdmatx->XferAbortCallback = NULL;
2382 
2383         /* Enable the DMA channel */
2384         if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
2385         {
2386           if (hi2c->hdmatx->LinkedListQueue != NULL)
2387           {
2388             /* Set DMA data size */
2389             hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
2390 
2391             /* Set DMA source address */
2392             hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2c->pBuffPtr;
2393 
2394             /* Set DMA destination address */
2395             hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \
2396               = (uint32_t)&hi2c->Instance->TXDR;
2397 
2398             dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx);
2399           }
2400           else
2401           {
2402             /* Update I2C state */
2403             hi2c->State     = HAL_I2C_STATE_LISTEN;
2404             hi2c->Mode      = HAL_I2C_MODE_NONE;
2405 
2406             /* Update I2C error code */
2407             hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
2408 
2409             /* Process Unlocked */
2410             __HAL_UNLOCK(hi2c);
2411 
2412             return HAL_ERROR;
2413           }
2414         }
2415         else
2416         {
2417           dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx,
2418                                            (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR,
2419                                            hi2c->XferSize);
2420         }
2421       }
2422       else
2423       {
2424         /* Update I2C state */
2425         hi2c->State     = HAL_I2C_STATE_LISTEN;
2426         hi2c->Mode      = HAL_I2C_MODE_NONE;
2427 
2428         /* Update I2C error code */
2429         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
2430 
2431         /* Process Unlocked */
2432         __HAL_UNLOCK(hi2c);
2433 
2434         return HAL_ERROR;
2435       }
2436 
2437       if (dmaxferstatus == HAL_OK)
2438       {
2439         /* Enable Address Acknowledge */
2440         hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
2441 
2442         /* Process Unlocked */
2443         __HAL_UNLOCK(hi2c);
2444 
2445         /* Note : The I2C interrupts must be enabled after unlocking current process
2446                   to avoid the risk of I2C interrupt handle execution before current
2447                   process unlock */
2448         /* Enable ERR, STOP, NACK, ADDR interrupts */
2449         I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
2450 
2451         /* Enable DMA Request */
2452         hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
2453       }
2454       else
2455       {
2456         /* Update I2C state */
2457         hi2c->State     = HAL_I2C_STATE_LISTEN;
2458         hi2c->Mode      = HAL_I2C_MODE_NONE;
2459 
2460         /* Update I2C error code */
2461         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
2462 
2463         /* Process Unlocked */
2464         __HAL_UNLOCK(hi2c);
2465 
2466         return HAL_ERROR;
2467       }
2468     }
2469     else
2470     {
2471       /* Enable Address Acknowledge */
2472       hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
2473 
2474       /* Process Unlocked */
2475       __HAL_UNLOCK(hi2c);
2476 
2477       /* Note : The I2C interrupts must be enabled after unlocking current process
2478       to avoid the risk of I2C interrupt handle execution before current
2479       process unlock */
2480       /* Enable ERR, STOP, NACK, ADDR interrupts */
2481       I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
2482     }
2483 
2484     return HAL_OK;
2485   }
2486   else
2487   {
2488     return HAL_BUSY;
2489   }
2490 }
2491 
2492 /**
2493   * @brief  Receive in slave mode an amount of data in non-blocking mode with DMA
2494   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
2495   *                the configuration information for the specified I2C.
2496   * @param  pData Pointer to data buffer
2497   * @param  Size Amount of data to be sent
2498   * @retval HAL status
2499   */
HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size)2500 HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
2501 {
2502   HAL_StatusTypeDef dmaxferstatus;
2503 
2504   if (hi2c->State == HAL_I2C_STATE_READY)
2505   {
2506     if ((pData == NULL) || (Size == 0U))
2507     {
2508       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
2509       return  HAL_ERROR;
2510     }
2511     /* Process Locked */
2512     __HAL_LOCK(hi2c);
2513 
2514     hi2c->State       = HAL_I2C_STATE_BUSY_RX;
2515     hi2c->Mode        = HAL_I2C_MODE_SLAVE;
2516     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
2517 
2518     /* Prepare transfer parameters */
2519     hi2c->pBuffPtr    = pData;
2520     hi2c->XferCount   = Size;
2521     hi2c->XferSize    = hi2c->XferCount;
2522     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
2523     hi2c->XferISR     = I2C_Slave_ISR_DMA;
2524 
2525     if (hi2c->hdmarx != NULL)
2526     {
2527       /* Set the I2C DMA transfer complete callback */
2528       hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt;
2529 
2530       /* Set the DMA error callback */
2531       hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
2532 
2533       /* Set the unused DMA callbacks to NULL */
2534       hi2c->hdmarx->XferHalfCpltCallback = NULL;
2535       hi2c->hdmarx->XferAbortCallback = NULL;
2536 
2537       /* Enable the DMA channel */
2538       if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
2539       {
2540         if (hi2c->hdmarx->LinkedListQueue != NULL)
2541         {
2542           /* Set DMA data size */
2543           hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
2544 
2545           /* Set DMA source address */
2546           hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \
2547             = (uint32_t)&hi2c->Instance->RXDR;
2548 
2549           /* Set DMA destination address */
2550           hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData;
2551 
2552           dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx);
2553         }
2554         else
2555         {
2556           /* Update I2C state */
2557           hi2c->State     = HAL_I2C_STATE_LISTEN;
2558           hi2c->Mode      = HAL_I2C_MODE_NONE;
2559 
2560           /* Update I2C error code */
2561           hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
2562 
2563           /* Process Unlocked */
2564           __HAL_UNLOCK(hi2c);
2565 
2566           return HAL_ERROR;
2567         }
2568       }
2569       else
2570       {
2571         dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData,
2572                                          hi2c->XferSize);
2573       }
2574     }
2575     else
2576     {
2577       /* Update I2C state */
2578       hi2c->State     = HAL_I2C_STATE_LISTEN;
2579       hi2c->Mode      = HAL_I2C_MODE_NONE;
2580 
2581       /* Update I2C error code */
2582       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
2583 
2584       /* Process Unlocked */
2585       __HAL_UNLOCK(hi2c);
2586 
2587       return HAL_ERROR;
2588     }
2589 
2590     if (dmaxferstatus == HAL_OK)
2591     {
2592       /* Enable Address Acknowledge */
2593       hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
2594 
2595       /* Process Unlocked */
2596       __HAL_UNLOCK(hi2c);
2597 
2598       /* Note : The I2C interrupts must be enabled after unlocking current process
2599                 to avoid the risk of I2C interrupt handle execution before current
2600                 process unlock */
2601       /* Enable ERR, STOP, NACK, ADDR interrupts */
2602       I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
2603 
2604       /* Enable DMA Request */
2605       hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
2606     }
2607     else
2608     {
2609       /* Update I2C state */
2610       hi2c->State     = HAL_I2C_STATE_LISTEN;
2611       hi2c->Mode      = HAL_I2C_MODE_NONE;
2612 
2613       /* Update I2C error code */
2614       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
2615 
2616       /* Process Unlocked */
2617       __HAL_UNLOCK(hi2c);
2618 
2619       return HAL_ERROR;
2620     }
2621 
2622     return HAL_OK;
2623   }
2624   else
2625   {
2626     return HAL_BUSY;
2627   }
2628 }
2629 #endif /* HAL_DMA_MODULE_ENABLED */
2630 
2631 /**
2632   * @brief  Write an amount of data in blocking mode to a specific memory address
2633   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
2634   *                the configuration information for the specified I2C.
2635   * @param  DevAddress Target device address: The device 7 bits address value
2636   *         in datasheet must be shifted to the left before calling the interface
2637   * @param  MemAddress Internal memory address
2638   * @param  MemAddSize Size of internal memory address
2639   * @param  pData Pointer to data buffer
2640   * @param  Size Amount of data to be sent
2641   * @param  Timeout Timeout duration
2642   * @retval HAL status
2643   */
HAL_I2C_Mem_Write(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint16_t MemAddress,uint16_t MemAddSize,uint8_t * pData,uint16_t Size,uint32_t Timeout)2644 HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
2645                                     uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)
2646 {
2647   uint32_t tickstart;
2648 
2649   /* Check the parameters */
2650   assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
2651 
2652   if (hi2c->State == HAL_I2C_STATE_READY)
2653   {
2654     if ((pData == NULL) || (Size == 0U))
2655     {
2656       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
2657       return  HAL_ERROR;
2658     }
2659 
2660     /* Process Locked */
2661     __HAL_LOCK(hi2c);
2662 
2663     /* Init tickstart for timeout management*/
2664     tickstart = HAL_GetTick();
2665 
2666     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
2667     {
2668       return HAL_ERROR;
2669     }
2670 
2671     hi2c->State     = HAL_I2C_STATE_BUSY_TX;
2672     hi2c->Mode      = HAL_I2C_MODE_MEM;
2673     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
2674 
2675     /* Prepare transfer parameters */
2676     hi2c->pBuffPtr  = pData;
2677     hi2c->XferCount = Size;
2678     hi2c->XferISR   = NULL;
2679 
2680     /* Send Slave Address and Memory Address */
2681     if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK)
2682     {
2683       /* Process Unlocked */
2684       __HAL_UNLOCK(hi2c);
2685       return HAL_ERROR;
2686     }
2687 
2688     /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */
2689     if (hi2c->XferCount > MAX_NBYTE_SIZE)
2690     {
2691       hi2c->XferSize = MAX_NBYTE_SIZE;
2692       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP);
2693     }
2694     else
2695     {
2696       hi2c->XferSize = hi2c->XferCount;
2697       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP);
2698     }
2699 
2700     do
2701     {
2702       /* Wait until TXIS flag is set */
2703       if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
2704       {
2705         return HAL_ERROR;
2706       }
2707 
2708       /* Write data to TXDR */
2709       hi2c->Instance->TXDR = *hi2c->pBuffPtr;
2710 
2711       /* Increment Buffer pointer */
2712       hi2c->pBuffPtr++;
2713 
2714       hi2c->XferCount--;
2715       hi2c->XferSize--;
2716 
2717       if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
2718       {
2719         /* Wait until TCR flag is set */
2720         if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
2721         {
2722           return HAL_ERROR;
2723         }
2724 
2725         if (hi2c->XferCount > MAX_NBYTE_SIZE)
2726         {
2727           hi2c->XferSize = MAX_NBYTE_SIZE;
2728           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
2729                              I2C_NO_STARTSTOP);
2730         }
2731         else
2732         {
2733           hi2c->XferSize = hi2c->XferCount;
2734           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
2735                              I2C_NO_STARTSTOP);
2736         }
2737       }
2738 
2739     } while (hi2c->XferCount > 0U);
2740 
2741     /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
2742     /* Wait until STOPF flag is reset */
2743     if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
2744     {
2745       return HAL_ERROR;
2746     }
2747 
2748     /* Clear STOP Flag */
2749     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
2750 
2751     /* Clear Configuration Register 2 */
2752     I2C_RESET_CR2(hi2c);
2753 
2754     hi2c->State = HAL_I2C_STATE_READY;
2755     hi2c->Mode  = HAL_I2C_MODE_NONE;
2756 
2757     /* Process Unlocked */
2758     __HAL_UNLOCK(hi2c);
2759 
2760     return HAL_OK;
2761   }
2762   else
2763   {
2764     return HAL_BUSY;
2765   }
2766 }
2767 
2768 /**
2769   * @brief  Read an amount of data in blocking mode from a specific memory address
2770   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
2771   *                the configuration information for the specified I2C.
2772   * @param  DevAddress Target device address: The device 7 bits address value
2773   *         in datasheet must be shifted to the left before calling the interface
2774   * @param  MemAddress Internal memory address
2775   * @param  MemAddSize Size of internal memory address
2776   * @param  pData Pointer to data buffer
2777   * @param  Size Amount of data to be sent
2778   * @param  Timeout Timeout duration
2779   * @retval HAL status
2780   */
HAL_I2C_Mem_Read(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint16_t MemAddress,uint16_t MemAddSize,uint8_t * pData,uint16_t Size,uint32_t Timeout)2781 HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
2782                                    uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)
2783 {
2784   uint32_t tickstart;
2785 
2786   /* Check the parameters */
2787   assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
2788 
2789   if (hi2c->State == HAL_I2C_STATE_READY)
2790   {
2791     if ((pData == NULL) || (Size == 0U))
2792     {
2793       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
2794       return  HAL_ERROR;
2795     }
2796 
2797     /* Process Locked */
2798     __HAL_LOCK(hi2c);
2799 
2800     /* Init tickstart for timeout management*/
2801     tickstart = HAL_GetTick();
2802 
2803     if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
2804     {
2805       return HAL_ERROR;
2806     }
2807 
2808     hi2c->State     = HAL_I2C_STATE_BUSY_RX;
2809     hi2c->Mode      = HAL_I2C_MODE_MEM;
2810     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
2811 
2812     /* Prepare transfer parameters */
2813     hi2c->pBuffPtr  = pData;
2814     hi2c->XferCount = Size;
2815     hi2c->XferISR   = NULL;
2816 
2817     /* Send Slave Address and Memory Address */
2818     if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK)
2819     {
2820       /* Process Unlocked */
2821       __HAL_UNLOCK(hi2c);
2822       return HAL_ERROR;
2823     }
2824 
2825     /* Send Slave Address */
2826     /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
2827     if (hi2c->XferCount > MAX_NBYTE_SIZE)
2828     {
2829       hi2c->XferSize = MAX_NBYTE_SIZE;
2830       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
2831                          I2C_GENERATE_START_READ);
2832     }
2833     else
2834     {
2835       hi2c->XferSize = hi2c->XferCount;
2836       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
2837                          I2C_GENERATE_START_READ);
2838     }
2839 
2840     do
2841     {
2842       /* Wait until RXNE flag is set */
2843       if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout, tickstart) != HAL_OK)
2844       {
2845         return HAL_ERROR;
2846       }
2847 
2848       /* Read data from RXDR */
2849       *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
2850 
2851       /* Increment Buffer pointer */
2852       hi2c->pBuffPtr++;
2853 
2854       hi2c->XferSize--;
2855       hi2c->XferCount--;
2856 
2857       if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
2858       {
2859         /* Wait until TCR flag is set */
2860         if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
2861         {
2862           return HAL_ERROR;
2863         }
2864 
2865         if (hi2c->XferCount > MAX_NBYTE_SIZE)
2866         {
2867           hi2c->XferSize = MAX_NBYTE_SIZE;
2868           I2C_TransferConfig(hi2c, DevAddress, (uint8_t) hi2c->XferSize, I2C_RELOAD_MODE,
2869                              I2C_NO_STARTSTOP);
2870         }
2871         else
2872         {
2873           hi2c->XferSize = hi2c->XferCount;
2874           I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
2875                              I2C_NO_STARTSTOP);
2876         }
2877       }
2878     } while (hi2c->XferCount > 0U);
2879 
2880     /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
2881     /* Wait until STOPF flag is reset */
2882     if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
2883     {
2884       return HAL_ERROR;
2885     }
2886 
2887     /* Clear STOP Flag */
2888     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
2889 
2890     /* Clear Configuration Register 2 */
2891     I2C_RESET_CR2(hi2c);
2892 
2893     hi2c->State = HAL_I2C_STATE_READY;
2894     hi2c->Mode  = HAL_I2C_MODE_NONE;
2895 
2896     /* Process Unlocked */
2897     __HAL_UNLOCK(hi2c);
2898 
2899     return HAL_OK;
2900   }
2901   else
2902   {
2903     return HAL_BUSY;
2904   }
2905 }
2906 /**
2907   * @brief  Write an amount of data in non-blocking mode with Interrupt to a specific memory address
2908   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
2909   *                the configuration information for the specified I2C.
2910   * @param  DevAddress Target device address: The device 7 bits address value
2911   *         in datasheet must be shifted to the left before calling the interface
2912   * @param  MemAddress Internal memory address
2913   * @param  MemAddSize Size of internal memory address
2914   * @param  pData Pointer to data buffer
2915   * @param  Size Amount of data to be sent
2916   * @retval HAL status
2917   */
HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint16_t MemAddress,uint16_t MemAddSize,uint8_t * pData,uint16_t Size)2918 HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
2919                                        uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
2920 {
2921   /* Check the parameters */
2922   assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
2923 
2924   if (hi2c->State == HAL_I2C_STATE_READY)
2925   {
2926     if ((pData == NULL) || (Size == 0U))
2927     {
2928       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
2929       return  HAL_ERROR;
2930     }
2931 
2932     if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
2933     {
2934       return HAL_BUSY;
2935     }
2936 
2937     /* Process Locked */
2938     __HAL_LOCK(hi2c);
2939 
2940     hi2c->State       = HAL_I2C_STATE_BUSY_TX;
2941     hi2c->Mode        = HAL_I2C_MODE_MEM;
2942     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
2943 
2944     /* Prepare transfer parameters */
2945     hi2c->XferSize    = 0U;
2946     hi2c->pBuffPtr    = pData;
2947     hi2c->XferCount   = Size;
2948     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
2949     hi2c->XferISR     = I2C_Mem_ISR_IT;
2950     hi2c->Devaddress  = DevAddress;
2951 
2952     /* If Memory address size is 8Bit */
2953     if (MemAddSize == I2C_MEMADD_SIZE_8BIT)
2954     {
2955       /* Prefetch Memory Address */
2956       hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
2957 
2958       /* Reset Memaddress content */
2959       hi2c->Memaddress = 0xFFFFFFFFU;
2960     }
2961     /* If Memory address size is 16Bit */
2962     else
2963     {
2964       /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */
2965       hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress);
2966 
2967       /* Prepare Memaddress buffer for LSB part */
2968       hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress);
2969     }
2970     /* Send Slave Address and Memory Address */
2971     I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE);
2972 
2973     /* Process Unlocked */
2974     __HAL_UNLOCK(hi2c);
2975 
2976     /* Note : The I2C interrupts must be enabled after unlocking current process
2977               to avoid the risk of I2C interrupt handle execution before current
2978               process unlock */
2979 
2980     /* Enable ERR, TC, STOP, NACK, TXI interrupt */
2981     /* possible to enable all of these */
2982     /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
2983       I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
2984     I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
2985 
2986     return HAL_OK;
2987   }
2988   else
2989   {
2990     return HAL_BUSY;
2991   }
2992 }
2993 
2994 /**
2995   * @brief  Read an amount of data in non-blocking mode with Interrupt from a specific memory address
2996   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
2997   *                the configuration information for the specified I2C.
2998   * @param  DevAddress Target device address: The device 7 bits address value
2999   *         in datasheet must be shifted to the left before calling the interface
3000   * @param  MemAddress Internal memory address
3001   * @param  MemAddSize Size of internal memory address
3002   * @param  pData Pointer to data buffer
3003   * @param  Size Amount of data to be sent
3004   * @retval HAL status
3005   */
HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint16_t MemAddress,uint16_t MemAddSize,uint8_t * pData,uint16_t Size)3006 HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
3007                                       uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
3008 {
3009   /* Check the parameters */
3010   assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
3011 
3012   if (hi2c->State == HAL_I2C_STATE_READY)
3013   {
3014     if ((pData == NULL) || (Size == 0U))
3015     {
3016       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
3017       return  HAL_ERROR;
3018     }
3019 
3020     if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
3021     {
3022       return HAL_BUSY;
3023     }
3024 
3025     /* Process Locked */
3026     __HAL_LOCK(hi2c);
3027 
3028     hi2c->State       = HAL_I2C_STATE_BUSY_RX;
3029     hi2c->Mode        = HAL_I2C_MODE_MEM;
3030     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
3031 
3032     /* Prepare transfer parameters */
3033     hi2c->pBuffPtr    = pData;
3034     hi2c->XferCount   = Size;
3035     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
3036     hi2c->XferISR     = I2C_Mem_ISR_IT;
3037     hi2c->Devaddress  = DevAddress;
3038 
3039     /* If Memory address size is 8Bit */
3040     if (MemAddSize == I2C_MEMADD_SIZE_8BIT)
3041     {
3042       /* Prefetch Memory Address */
3043       hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
3044 
3045       /* Reset Memaddress content */
3046       hi2c->Memaddress = 0xFFFFFFFFU;
3047     }
3048     /* If Memory address size is 16Bit */
3049     else
3050     {
3051       /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */
3052       hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress);
3053 
3054       /* Prepare Memaddress buffer for LSB part */
3055       hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress);
3056     }
3057     /* Send Slave Address and Memory Address */
3058     I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE);
3059 
3060     /* Process Unlocked */
3061     __HAL_UNLOCK(hi2c);
3062 
3063     /* Note : The I2C interrupts must be enabled after unlocking current process
3064               to avoid the risk of I2C interrupt handle execution before current
3065               process unlock */
3066 
3067     /* Enable ERR, TC, STOP, NACK, TXI interrupt */
3068     /* possible to enable all of these */
3069     /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
3070       I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
3071     I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
3072 
3073     return HAL_OK;
3074   }
3075   else
3076   {
3077     return HAL_BUSY;
3078   }
3079 }
3080 
3081 #if defined(HAL_DMA_MODULE_ENABLED)
3082 /**
3083   * @brief  Write an amount of data in non-blocking mode with DMA to a specific memory address
3084   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
3085   *                the configuration information for the specified I2C.
3086   * @param  DevAddress Target device address: The device 7 bits address value
3087   *         in datasheet must be shifted to the left before calling the interface
3088   * @param  MemAddress Internal memory address
3089   * @param  MemAddSize Size of internal memory address
3090   * @param  pData Pointer to data buffer
3091   * @param  Size Amount of data to be sent
3092   * @retval HAL status
3093   */
HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint16_t MemAddress,uint16_t MemAddSize,uint8_t * pData,uint16_t Size)3094 HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
3095                                         uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
3096 {
3097   HAL_StatusTypeDef dmaxferstatus;
3098 
3099   /* Check the parameters */
3100   assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
3101 
3102   if (hi2c->State == HAL_I2C_STATE_READY)
3103   {
3104     if ((pData == NULL) || (Size == 0U))
3105     {
3106       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
3107       return  HAL_ERROR;
3108     }
3109 
3110     if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
3111     {
3112       return HAL_BUSY;
3113     }
3114 
3115     /* Process Locked */
3116     __HAL_LOCK(hi2c);
3117 
3118     hi2c->State       = HAL_I2C_STATE_BUSY_TX;
3119     hi2c->Mode        = HAL_I2C_MODE_MEM;
3120     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
3121 
3122     /* Prepare transfer parameters */
3123     hi2c->pBuffPtr    = pData;
3124     hi2c->XferCount   = Size;
3125     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
3126     hi2c->XferISR     = I2C_Mem_ISR_DMA;
3127     hi2c->Devaddress  = DevAddress;
3128 
3129     if (hi2c->XferCount > MAX_NBYTE_SIZE)
3130     {
3131       hi2c->XferSize = MAX_NBYTE_SIZE;
3132     }
3133     else
3134     {
3135       hi2c->XferSize = hi2c->XferCount;
3136     }
3137 
3138     /* If Memory address size is 8Bit */
3139     if (MemAddSize == I2C_MEMADD_SIZE_8BIT)
3140     {
3141       /* Prefetch Memory Address */
3142       hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
3143 
3144       /* Reset Memaddress content */
3145       hi2c->Memaddress = 0xFFFFFFFFU;
3146     }
3147     /* If Memory address size is 16Bit */
3148     else
3149     {
3150       /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */
3151       hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress);
3152 
3153       /* Prepare Memaddress buffer for LSB part */
3154       hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress);
3155     }
3156 
3157     if (hi2c->hdmatx != NULL)
3158     {
3159       /* Set the I2C DMA transfer complete callback */
3160       hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt;
3161 
3162       /* Set the DMA error callback */
3163       hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
3164 
3165       /* Set the unused DMA callbacks to NULL */
3166       hi2c->hdmatx->XferHalfCpltCallback = NULL;
3167       hi2c->hdmatx->XferAbortCallback = NULL;
3168 
3169       /* Enable the DMA channel */
3170       if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
3171       {
3172         if (hi2c->hdmatx->LinkedListQueue != NULL)
3173         {
3174           /* Set DMA data size */
3175           hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
3176 
3177           /* Set DMA source address */
3178           hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData;
3179 
3180           /* Set DMA destination address */
3181           hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \
3182             = (uint32_t)&hi2c->Instance->TXDR;
3183 
3184           dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx);
3185         }
3186         else
3187         {
3188           /* Update I2C state */
3189           hi2c->State     = HAL_I2C_STATE_READY;
3190           hi2c->Mode      = HAL_I2C_MODE_NONE;
3191 
3192           /* Update I2C error code */
3193           hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
3194 
3195           /* Process Unlocked */
3196           __HAL_UNLOCK(hi2c);
3197 
3198           return HAL_ERROR;
3199         }
3200       }
3201       else
3202       {
3203         dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR,
3204                                          hi2c->XferSize);
3205       }
3206     }
3207     else
3208     {
3209       /* Update I2C state */
3210       hi2c->State     = HAL_I2C_STATE_READY;
3211       hi2c->Mode      = HAL_I2C_MODE_NONE;
3212 
3213       /* Update I2C error code */
3214       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
3215 
3216       /* Process Unlocked */
3217       __HAL_UNLOCK(hi2c);
3218 
3219       return HAL_ERROR;
3220     }
3221 
3222     if (dmaxferstatus == HAL_OK)
3223     {
3224       /* Send Slave Address and Memory Address */
3225       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE);
3226 
3227       /* Process Unlocked */
3228       __HAL_UNLOCK(hi2c);
3229 
3230       /* Note : The I2C interrupts must be enabled after unlocking current process
3231                 to avoid the risk of I2C interrupt handle execution before current
3232                 process unlock */
3233       /* Enable ERR, TC, STOP, NACK, TXI interrupt */
3234       /* possible to enable all of these */
3235       /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
3236         I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
3237       I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
3238     }
3239     else
3240     {
3241       /* Update I2C state */
3242       hi2c->State     = HAL_I2C_STATE_READY;
3243       hi2c->Mode      = HAL_I2C_MODE_NONE;
3244 
3245       /* Update I2C error code */
3246       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
3247 
3248       /* Process Unlocked */
3249       __HAL_UNLOCK(hi2c);
3250 
3251       return HAL_ERROR;
3252     }
3253 
3254     return HAL_OK;
3255   }
3256   else
3257   {
3258     return HAL_BUSY;
3259   }
3260 }
3261 
3262 /**
3263   * @brief  Reads an amount of data in non-blocking mode with DMA from a specific memory address.
3264   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
3265   *                the configuration information for the specified I2C.
3266   * @param  DevAddress Target device address: The device 7 bits address value
3267   *         in datasheet must be shifted to the left before calling the interface
3268   * @param  MemAddress Internal memory address
3269   * @param  MemAddSize Size of internal memory address
3270   * @param  pData Pointer to data buffer
3271   * @param  Size Amount of data to be read
3272   * @retval HAL status
3273   */
HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint16_t MemAddress,uint16_t MemAddSize,uint8_t * pData,uint16_t Size)3274 HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
3275                                        uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
3276 {
3277   HAL_StatusTypeDef dmaxferstatus;
3278 
3279   /* Check the parameters */
3280   assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
3281 
3282   if (hi2c->State == HAL_I2C_STATE_READY)
3283   {
3284     if ((pData == NULL) || (Size == 0U))
3285     {
3286       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
3287       return  HAL_ERROR;
3288     }
3289 
3290     if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
3291     {
3292       return HAL_BUSY;
3293     }
3294 
3295     /* Process Locked */
3296     __HAL_LOCK(hi2c);
3297 
3298     hi2c->State       = HAL_I2C_STATE_BUSY_RX;
3299     hi2c->Mode        = HAL_I2C_MODE_MEM;
3300     hi2c->ErrorCode   = HAL_I2C_ERROR_NONE;
3301 
3302     /* Prepare transfer parameters */
3303     hi2c->pBuffPtr    = pData;
3304     hi2c->XferCount   = Size;
3305     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
3306     hi2c->XferISR     = I2C_Mem_ISR_DMA;
3307     hi2c->Devaddress  = DevAddress;
3308 
3309     if (hi2c->XferCount > MAX_NBYTE_SIZE)
3310     {
3311       hi2c->XferSize = MAX_NBYTE_SIZE;
3312     }
3313     else
3314     {
3315       hi2c->XferSize = hi2c->XferCount;
3316     }
3317 
3318     /* If Memory address size is 8Bit */
3319     if (MemAddSize == I2C_MEMADD_SIZE_8BIT)
3320     {
3321       /* Prefetch Memory Address */
3322       hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
3323 
3324       /* Reset Memaddress content */
3325       hi2c->Memaddress = 0xFFFFFFFFU;
3326     }
3327     /* If Memory address size is 16Bit */
3328     else
3329     {
3330       /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */
3331       hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress);
3332 
3333       /* Prepare Memaddress buffer for LSB part */
3334       hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress);
3335     }
3336 
3337     if (hi2c->hdmarx != NULL)
3338     {
3339       /* Set the I2C DMA transfer complete callback */
3340       hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt;
3341 
3342       /* Set the DMA error callback */
3343       hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
3344 
3345       /* Set the unused DMA callbacks to NULL */
3346       hi2c->hdmarx->XferHalfCpltCallback = NULL;
3347       hi2c->hdmarx->XferAbortCallback = NULL;
3348 
3349       /* Enable the DMA channel */
3350       if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
3351       {
3352         if (hi2c->hdmarx->LinkedListQueue != NULL)
3353         {
3354           /* Set DMA data size */
3355           hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
3356 
3357           /* Set DMA source address */
3358           hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \
3359             = (uint32_t)&hi2c->Instance->RXDR;
3360 
3361           /* Set DMA destination address */
3362           hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData;
3363 
3364           dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx);
3365         }
3366         else
3367         {
3368           /* Update I2C state */
3369           hi2c->State     = HAL_I2C_STATE_READY;
3370           hi2c->Mode      = HAL_I2C_MODE_NONE;
3371 
3372           /* Update I2C error code */
3373           hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
3374 
3375           /* Process Unlocked */
3376           __HAL_UNLOCK(hi2c);
3377 
3378           return HAL_ERROR;
3379         }
3380       }
3381       else
3382       {
3383         dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData,
3384                                          hi2c->XferSize);
3385       }
3386     }
3387     else
3388     {
3389       /* Update I2C state */
3390       hi2c->State     = HAL_I2C_STATE_READY;
3391       hi2c->Mode      = HAL_I2C_MODE_NONE;
3392 
3393       /* Update I2C error code */
3394       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
3395 
3396       /* Process Unlocked */
3397       __HAL_UNLOCK(hi2c);
3398 
3399       return HAL_ERROR;
3400     }
3401 
3402     if (dmaxferstatus == HAL_OK)
3403     {
3404       /* Send Slave Address and Memory Address */
3405       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE);
3406 
3407       /* Process Unlocked */
3408       __HAL_UNLOCK(hi2c);
3409 
3410       /* Note : The I2C interrupts must be enabled after unlocking current process
3411                 to avoid the risk of I2C interrupt handle execution before current
3412                 process unlock */
3413       /* Enable ERR, TC, STOP, NACK, TXI interrupt */
3414       /* possible to enable all of these */
3415       /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
3416         I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
3417       I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
3418     }
3419     else
3420     {
3421       /* Update I2C state */
3422       hi2c->State     = HAL_I2C_STATE_READY;
3423       hi2c->Mode      = HAL_I2C_MODE_NONE;
3424 
3425       /* Update I2C error code */
3426       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
3427 
3428       /* Process Unlocked */
3429       __HAL_UNLOCK(hi2c);
3430 
3431       return HAL_ERROR;
3432     }
3433 
3434     return HAL_OK;
3435   }
3436   else
3437   {
3438     return HAL_BUSY;
3439   }
3440 }
3441 #endif /* HAL_DMA_MODULE_ENABLED */
3442 
3443 /**
3444   * @brief  Checks if target device is ready for communication.
3445   * @note   This function is used with Memory devices
3446   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
3447   *                the configuration information for the specified I2C.
3448   * @param  DevAddress Target device address: The device 7 bits address value
3449   *         in datasheet must be shifted to the left before calling the interface
3450   * @param  Trials Number of trials
3451   * @param  Timeout Timeout duration
3452   * @retval HAL status
3453   */
HAL_I2C_IsDeviceReady(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint32_t Trials,uint32_t Timeout)3454 HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials,
3455                                         uint32_t Timeout)
3456 {
3457   uint32_t tickstart;
3458 
3459   __IO uint32_t I2C_Trials = 0UL;
3460 
3461   HAL_StatusTypeDef status = HAL_OK;
3462 
3463   FlagStatus tmp1;
3464   FlagStatus tmp2;
3465 
3466   if (hi2c->State == HAL_I2C_STATE_READY)
3467   {
3468     if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
3469     {
3470       return HAL_BUSY;
3471     }
3472 
3473     /* Process Locked */
3474     __HAL_LOCK(hi2c);
3475 
3476     hi2c->State = HAL_I2C_STATE_BUSY;
3477     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
3478 
3479     do
3480     {
3481       /* Generate Start */
3482       hi2c->Instance->CR2 = I2C_GENERATE_START(hi2c->Init.AddressingMode, DevAddress);
3483 
3484       /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
3485       /* Wait until STOPF flag is set or a NACK flag is set*/
3486       tickstart = HAL_GetTick();
3487 
3488       tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF);
3489       tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF);
3490 
3491       while ((tmp1 == RESET) && (tmp2 == RESET))
3492       {
3493         if (Timeout != HAL_MAX_DELAY)
3494         {
3495           if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
3496           {
3497             /* Update I2C state */
3498             hi2c->State = HAL_I2C_STATE_READY;
3499 
3500             /* Update I2C error code */
3501             hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
3502 
3503             /* Process Unlocked */
3504             __HAL_UNLOCK(hi2c);
3505 
3506             return HAL_ERROR;
3507           }
3508         }
3509 
3510         tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF);
3511         tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF);
3512       }
3513 
3514       /* Check if the NACKF flag has not been set */
3515       if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == RESET)
3516       {
3517         /* Wait until STOPF flag is reset */
3518         if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK)
3519         {
3520           /* A non acknowledge appear during STOP Flag waiting process, a new trial must be performed */
3521           if (hi2c->ErrorCode == HAL_I2C_ERROR_AF)
3522           {
3523             /* Clear STOP Flag */
3524             __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
3525 
3526             /* Reset the error code for next trial */
3527             hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
3528           }
3529           else
3530           {
3531             status = HAL_ERROR;
3532           }
3533         }
3534         else
3535         {
3536           /* A acknowledge appear during STOP Flag waiting process, this mean that device respond to its address */
3537 
3538           /* Clear STOP Flag */
3539           __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
3540 
3541           /* Device is ready */
3542           hi2c->State = HAL_I2C_STATE_READY;
3543 
3544           /* Process Unlocked */
3545           __HAL_UNLOCK(hi2c);
3546 
3547           return HAL_OK;
3548         }
3549       }
3550       else
3551       {
3552         /* A non acknowledge is detected, this mean that device not respond to its address,
3553            a new trial must be performed */
3554 
3555         /* Clear NACK Flag */
3556         __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
3557 
3558         /* Wait until STOPF flag is reset */
3559         if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK)
3560         {
3561           status = HAL_ERROR;
3562         }
3563         else
3564         {
3565           /* Clear STOP Flag, auto generated with autoend*/
3566           __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
3567         }
3568       }
3569 
3570       /* Increment Trials */
3571       I2C_Trials++;
3572 
3573       if ((I2C_Trials < Trials) && (status == HAL_ERROR))
3574       {
3575         status = HAL_OK;
3576       }
3577 
3578     } while (I2C_Trials < Trials);
3579 
3580     /* Update I2C state */
3581     hi2c->State = HAL_I2C_STATE_READY;
3582 
3583     /* Update I2C error code */
3584     hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
3585 
3586     /* Process Unlocked */
3587     __HAL_UNLOCK(hi2c);
3588 
3589     return HAL_ERROR;
3590   }
3591   else
3592   {
3593     return HAL_BUSY;
3594   }
3595 }
3596 
3597 /**
3598   * @brief  Sequential transmit in master I2C mode an amount of data in non-blocking mode with Interrupt.
3599   * @note   This interface allow to manage repeated start condition when a direction change during transfer
3600   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
3601   *                the configuration information for the specified I2C.
3602   * @param  DevAddress Target device address: The device 7 bits address value
3603   *         in datasheet must be shifted to the left before calling the interface
3604   * @param  pData Pointer to data buffer
3605   * @param  Size Amount of data to be sent
3606   * @param  XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
3607   * @retval HAL status
3608   */
HAL_I2C_Master_Seq_Transmit_IT(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size,uint32_t XferOptions)3609 HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
3610                                                  uint16_t Size, uint32_t XferOptions)
3611 {
3612   uint32_t xfermode;
3613   uint32_t xferrequest = I2C_GENERATE_START_WRITE;
3614 
3615   /* Check the parameters */
3616   assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
3617 
3618   if (hi2c->State == HAL_I2C_STATE_READY)
3619   {
3620     /* Process Locked */
3621     __HAL_LOCK(hi2c);
3622 
3623     hi2c->State     = HAL_I2C_STATE_BUSY_TX;
3624     hi2c->Mode      = HAL_I2C_MODE_MASTER;
3625     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
3626 
3627     /* Prepare transfer parameters */
3628     hi2c->pBuffPtr    = pData;
3629     hi2c->XferCount   = Size;
3630     hi2c->XferOptions = XferOptions;
3631     hi2c->XferISR     = I2C_Master_ISR_IT;
3632 
3633     /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */
3634     if (hi2c->XferCount > MAX_NBYTE_SIZE)
3635     {
3636       hi2c->XferSize = MAX_NBYTE_SIZE;
3637       xfermode = I2C_RELOAD_MODE;
3638     }
3639     else
3640     {
3641       hi2c->XferSize = hi2c->XferCount;
3642       xfermode = hi2c->XferOptions;
3643     }
3644 
3645     /* If transfer direction not change and there is no request to start another frame,
3646        do not generate Restart Condition */
3647     /* Mean Previous state is same as current state */
3648     if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) && \
3649         (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0))
3650     {
3651       xferrequest = I2C_NO_STARTSTOP;
3652     }
3653     else
3654     {
3655       /* Convert OTHER_xxx XferOptions if any */
3656       I2C_ConvertOtherXferOptions(hi2c);
3657 
3658       /* Update xfermode accordingly if no reload is necessary */
3659       if (hi2c->XferCount <= MAX_NBYTE_SIZE)
3660       {
3661         xfermode = hi2c->XferOptions;
3662       }
3663     }
3664 
3665     /* Send Slave Address and set NBYTES to write */
3666     I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest);
3667 
3668     /* Process Unlocked */
3669     __HAL_UNLOCK(hi2c);
3670 
3671     /* Note : The I2C interrupts must be enabled after unlocking current process
3672               to avoid the risk of I2C interrupt handle execution before current
3673               process unlock */
3674     /* Enable ERR, TC, STOP, NACK, TXI interrupt */
3675     /* possible to enable all of these */
3676     /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
3677        I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
3678     I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
3679 
3680     return HAL_OK;
3681   }
3682   else
3683   {
3684     return HAL_BUSY;
3685   }
3686 }
3687 
3688 #if defined(HAL_DMA_MODULE_ENABLED)
3689 /**
3690   * @brief  Sequential transmit in master I2C mode an amount of data in non-blocking mode with DMA.
3691   * @note   This interface allow to manage repeated start condition when a direction change during transfer
3692   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
3693   *                the configuration information for the specified I2C.
3694   * @param  DevAddress Target device address: The device 7 bits address value
3695   *         in datasheet must be shifted to the left before calling the interface
3696   * @param  pData Pointer to data buffer
3697   * @param  Size Amount of data to be sent
3698   * @param  XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
3699   * @retval HAL status
3700   */
HAL_I2C_Master_Seq_Transmit_DMA(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size,uint32_t XferOptions)3701 HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
3702                                                   uint16_t Size, uint32_t XferOptions)
3703 {
3704   uint32_t xfermode;
3705   uint32_t xferrequest = I2C_GENERATE_START_WRITE;
3706   HAL_StatusTypeDef dmaxferstatus;
3707 
3708   /* Check the parameters */
3709   assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
3710 
3711   if (hi2c->State == HAL_I2C_STATE_READY)
3712   {
3713     /* Process Locked */
3714     __HAL_LOCK(hi2c);
3715 
3716     hi2c->State     = HAL_I2C_STATE_BUSY_TX;
3717     hi2c->Mode      = HAL_I2C_MODE_MASTER;
3718     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
3719 
3720     /* Prepare transfer parameters */
3721     hi2c->pBuffPtr    = pData;
3722     hi2c->XferCount   = Size;
3723     hi2c->XferOptions = XferOptions;
3724     hi2c->XferISR     = I2C_Master_ISR_DMA;
3725 
3726     /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */
3727     if (hi2c->XferCount > MAX_NBYTE_SIZE)
3728     {
3729       hi2c->XferSize = MAX_NBYTE_SIZE;
3730       xfermode = I2C_RELOAD_MODE;
3731     }
3732     else
3733     {
3734       hi2c->XferSize = hi2c->XferCount;
3735       xfermode = hi2c->XferOptions;
3736     }
3737 
3738     /* If transfer direction not change and there is no request to start another frame,
3739        do not generate Restart Condition */
3740     /* Mean Previous state is same as current state */
3741     if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) && \
3742         (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0))
3743     {
3744       xferrequest = I2C_NO_STARTSTOP;
3745     }
3746     else
3747     {
3748       /* Convert OTHER_xxx XferOptions if any */
3749       I2C_ConvertOtherXferOptions(hi2c);
3750 
3751       /* Update xfermode accordingly if no reload is necessary */
3752       if (hi2c->XferCount <= MAX_NBYTE_SIZE)
3753       {
3754         xfermode = hi2c->XferOptions;
3755       }
3756     }
3757 
3758     if (hi2c->XferSize > 0U)
3759     {
3760       if (hi2c->hdmatx != NULL)
3761       {
3762         /* Set the I2C DMA transfer complete callback */
3763         hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt;
3764 
3765         /* Set the DMA error callback */
3766         hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
3767 
3768         /* Set the unused DMA callbacks to NULL */
3769         hi2c->hdmatx->XferHalfCpltCallback = NULL;
3770         hi2c->hdmatx->XferAbortCallback = NULL;
3771 
3772         /* Enable the DMA channel */
3773         if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
3774         {
3775           if (hi2c->hdmatx->LinkedListQueue != NULL)
3776           {
3777             /* Set DMA data size */
3778             hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
3779 
3780             /* Set DMA source address */
3781             hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData;
3782 
3783             /* Set DMA destination address */
3784             hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \
3785               = (uint32_t)&hi2c->Instance->TXDR;
3786 
3787             dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx);
3788           }
3789           else
3790           {
3791             /* Update I2C state */
3792             hi2c->State     = HAL_I2C_STATE_READY;
3793             hi2c->Mode      = HAL_I2C_MODE_NONE;
3794 
3795             /* Update I2C error code */
3796             hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
3797 
3798             /* Process Unlocked */
3799             __HAL_UNLOCK(hi2c);
3800 
3801             return HAL_ERROR;
3802           }
3803         }
3804         else
3805         {
3806           dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR,
3807                                            hi2c->XferSize);
3808         }
3809       }
3810       else
3811       {
3812         /* Update I2C state */
3813         hi2c->State     = HAL_I2C_STATE_READY;
3814         hi2c->Mode      = HAL_I2C_MODE_NONE;
3815 
3816         /* Update I2C error code */
3817         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
3818 
3819         /* Process Unlocked */
3820         __HAL_UNLOCK(hi2c);
3821 
3822         return HAL_ERROR;
3823       }
3824 
3825       if (dmaxferstatus == HAL_OK)
3826       {
3827         /* Send Slave Address and set NBYTES to write */
3828         I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest);
3829 
3830         /* Update XferCount value */
3831         hi2c->XferCount -= hi2c->XferSize;
3832 
3833         /* Process Unlocked */
3834         __HAL_UNLOCK(hi2c);
3835 
3836         /* Note : The I2C interrupts must be enabled after unlocking current process
3837                   to avoid the risk of I2C interrupt handle execution before current
3838                   process unlock */
3839         /* Enable ERR and NACK interrupts */
3840         I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
3841 
3842         /* Enable DMA Request */
3843         hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
3844       }
3845       else
3846       {
3847         /* Update I2C state */
3848         hi2c->State     = HAL_I2C_STATE_READY;
3849         hi2c->Mode      = HAL_I2C_MODE_NONE;
3850 
3851         /* Update I2C error code */
3852         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
3853 
3854         /* Process Unlocked */
3855         __HAL_UNLOCK(hi2c);
3856 
3857         return HAL_ERROR;
3858       }
3859     }
3860     else
3861     {
3862       /* Update Transfer ISR function pointer */
3863       hi2c->XferISR = I2C_Master_ISR_IT;
3864 
3865       /* Send Slave Address */
3866       /* Set NBYTES to write and generate START condition */
3867       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
3868                          I2C_GENERATE_START_WRITE);
3869 
3870       /* Process Unlocked */
3871       __HAL_UNLOCK(hi2c);
3872 
3873       /* Note : The I2C interrupts must be enabled after unlocking current process
3874                 to avoid the risk of I2C interrupt handle execution before current
3875                 process unlock */
3876       /* Enable ERR, TC, STOP, NACK, TXI interrupt */
3877       /* possible to enable all of these */
3878       /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
3879         I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
3880       I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
3881     }
3882 
3883     return HAL_OK;
3884   }
3885   else
3886   {
3887     return HAL_BUSY;
3888   }
3889 }
3890 #endif /* HAL_DMA_MODULE_ENABLED */
3891 
3892 /**
3893   * @brief  Sequential receive in master I2C mode an amount of data in non-blocking mode with Interrupt
3894   * @note   This interface allow to manage repeated start condition when a direction change during transfer
3895   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
3896   *                the configuration information for the specified I2C.
3897   * @param  DevAddress Target device address: The device 7 bits address value
3898   *         in datasheet must be shifted to the left before calling the interface
3899   * @param  pData Pointer to data buffer
3900   * @param  Size Amount of data to be sent
3901   * @param  XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
3902   * @retval HAL status
3903   */
HAL_I2C_Master_Seq_Receive_IT(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size,uint32_t XferOptions)3904 HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
3905                                                 uint16_t Size, uint32_t XferOptions)
3906 {
3907   uint32_t xfermode;
3908   uint32_t xferrequest = I2C_GENERATE_START_READ;
3909 
3910   /* Check the parameters */
3911   assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
3912 
3913   if (hi2c->State == HAL_I2C_STATE_READY)
3914   {
3915     /* Process Locked */
3916     __HAL_LOCK(hi2c);
3917 
3918     hi2c->State     = HAL_I2C_STATE_BUSY_RX;
3919     hi2c->Mode      = HAL_I2C_MODE_MASTER;
3920     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
3921 
3922     /* Prepare transfer parameters */
3923     hi2c->pBuffPtr    = pData;
3924     hi2c->XferCount   = Size;
3925     hi2c->XferOptions = XferOptions;
3926     hi2c->XferISR     = I2C_Master_ISR_IT;
3927 
3928     /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */
3929     if (hi2c->XferCount > MAX_NBYTE_SIZE)
3930     {
3931       hi2c->XferSize = MAX_NBYTE_SIZE;
3932       xfermode = I2C_RELOAD_MODE;
3933     }
3934     else
3935     {
3936       hi2c->XferSize = hi2c->XferCount;
3937       xfermode = hi2c->XferOptions;
3938     }
3939 
3940     /* If transfer direction not change and there is no request to start another frame,
3941        do not generate Restart Condition */
3942     /* Mean Previous state is same as current state */
3943     if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) && \
3944         (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0))
3945     {
3946       xferrequest = I2C_NO_STARTSTOP;
3947     }
3948     else
3949     {
3950       /* Convert OTHER_xxx XferOptions if any */
3951       I2C_ConvertOtherXferOptions(hi2c);
3952 
3953       /* Update xfermode accordingly if no reload is necessary */
3954       if (hi2c->XferCount <= MAX_NBYTE_SIZE)
3955       {
3956         xfermode = hi2c->XferOptions;
3957       }
3958     }
3959 
3960     /* Send Slave Address and set NBYTES to read */
3961     I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest);
3962 
3963     /* Process Unlocked */
3964     __HAL_UNLOCK(hi2c);
3965 
3966     /* Note : The I2C interrupts must be enabled after unlocking current process
3967               to avoid the risk of I2C interrupt handle execution before current
3968               process unlock */
3969     I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT);
3970 
3971     return HAL_OK;
3972   }
3973   else
3974   {
3975     return HAL_BUSY;
3976   }
3977 }
3978 
3979 #if defined(HAL_DMA_MODULE_ENABLED)
3980 /**
3981   * @brief  Sequential receive in master I2C mode an amount of data in non-blocking mode with DMA
3982   * @note   This interface allow to manage repeated start condition when a direction change during transfer
3983   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
3984   *                the configuration information for the specified I2C.
3985   * @param  DevAddress Target device address: The device 7 bits address value
3986   *         in datasheet must be shifted to the left before calling the interface
3987   * @param  pData Pointer to data buffer
3988   * @param  Size Amount of data to be sent
3989   * @param  XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
3990   * @retval HAL status
3991   */
HAL_I2C_Master_Seq_Receive_DMA(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t * pData,uint16_t Size,uint32_t XferOptions)3992 HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
3993                                                  uint16_t Size, uint32_t XferOptions)
3994 {
3995   uint32_t xfermode;
3996   uint32_t xferrequest = I2C_GENERATE_START_READ;
3997   HAL_StatusTypeDef dmaxferstatus;
3998 
3999   /* Check the parameters */
4000   assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
4001 
4002   if (hi2c->State == HAL_I2C_STATE_READY)
4003   {
4004     /* Process Locked */
4005     __HAL_LOCK(hi2c);
4006 
4007     hi2c->State     = HAL_I2C_STATE_BUSY_RX;
4008     hi2c->Mode      = HAL_I2C_MODE_MASTER;
4009     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
4010 
4011     /* Prepare transfer parameters */
4012     hi2c->pBuffPtr    = pData;
4013     hi2c->XferCount   = Size;
4014     hi2c->XferOptions = XferOptions;
4015     hi2c->XferISR     = I2C_Master_ISR_DMA;
4016 
4017     /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */
4018     if (hi2c->XferCount > MAX_NBYTE_SIZE)
4019     {
4020       hi2c->XferSize = MAX_NBYTE_SIZE;
4021       xfermode = I2C_RELOAD_MODE;
4022     }
4023     else
4024     {
4025       hi2c->XferSize = hi2c->XferCount;
4026       xfermode = hi2c->XferOptions;
4027     }
4028 
4029     /* If transfer direction not change and there is no request to start another frame,
4030        do not generate Restart Condition */
4031     /* Mean Previous state is same as current state */
4032     if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) && \
4033         (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0))
4034     {
4035       xferrequest = I2C_NO_STARTSTOP;
4036     }
4037     else
4038     {
4039       /* Convert OTHER_xxx XferOptions if any */
4040       I2C_ConvertOtherXferOptions(hi2c);
4041 
4042       /* Update xfermode accordingly if no reload is necessary */
4043       if (hi2c->XferCount <= MAX_NBYTE_SIZE)
4044       {
4045         xfermode = hi2c->XferOptions;
4046       }
4047     }
4048 
4049     if (hi2c->XferSize > 0U)
4050     {
4051       if (hi2c->hdmarx != NULL)
4052       {
4053         /* Set the I2C DMA transfer complete callback */
4054         hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt;
4055 
4056         /* Set the DMA error callback */
4057         hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
4058 
4059         /* Set the unused DMA callbacks to NULL */
4060         hi2c->hdmarx->XferHalfCpltCallback = NULL;
4061         hi2c->hdmarx->XferAbortCallback = NULL;
4062 
4063         /* Enable the DMA channel */
4064         if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
4065         {
4066           if (hi2c->hdmarx->LinkedListQueue != NULL)
4067           {
4068             /* Set DMA data size */
4069             hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
4070 
4071             /* Set DMA source address */
4072             hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \
4073               = (uint32_t)&hi2c->Instance->RXDR;
4074 
4075             /* Set DMA destination address */
4076             hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData;
4077 
4078             dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx);
4079           }
4080           else
4081           {
4082             hi2c->State     = HAL_I2C_STATE_READY;
4083             hi2c->Mode      = HAL_I2C_MODE_NONE;
4084 
4085             /* Update I2C error code */
4086             hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
4087 
4088             /* Process Unlocked */
4089             __HAL_UNLOCK(hi2c);
4090 
4091             return HAL_ERROR;
4092           }
4093         }
4094         else
4095         {
4096           dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData,
4097                                            hi2c->XferSize);
4098         }
4099       }
4100       else
4101       {
4102         /* Update I2C state */
4103         hi2c->State     = HAL_I2C_STATE_READY;
4104         hi2c->Mode      = HAL_I2C_MODE_NONE;
4105 
4106         /* Update I2C error code */
4107         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
4108 
4109         /* Process Unlocked */
4110         __HAL_UNLOCK(hi2c);
4111 
4112         return HAL_ERROR;
4113       }
4114 
4115       if (dmaxferstatus == HAL_OK)
4116       {
4117         /* Send Slave Address and set NBYTES to read */
4118         I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest);
4119 
4120         /* Update XferCount value */
4121         hi2c->XferCount -= hi2c->XferSize;
4122 
4123         /* Process Unlocked */
4124         __HAL_UNLOCK(hi2c);
4125 
4126         /* Note : The I2C interrupts must be enabled after unlocking current process
4127                   to avoid the risk of I2C interrupt handle execution before current
4128                   process unlock */
4129         /* Enable ERR and NACK interrupts */
4130         I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
4131 
4132         /* Enable DMA Request */
4133         hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
4134       }
4135       else
4136       {
4137         /* Update I2C state */
4138         hi2c->State     = HAL_I2C_STATE_READY;
4139         hi2c->Mode      = HAL_I2C_MODE_NONE;
4140 
4141         /* Update I2C error code */
4142         hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
4143 
4144         /* Process Unlocked */
4145         __HAL_UNLOCK(hi2c);
4146 
4147         return HAL_ERROR;
4148       }
4149     }
4150     else
4151     {
4152       /* Update Transfer ISR function pointer */
4153       hi2c->XferISR = I2C_Master_ISR_IT;
4154 
4155       /* Send Slave Address */
4156       /* Set NBYTES to read and generate START condition */
4157       I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
4158                          I2C_GENERATE_START_READ);
4159 
4160       /* Process Unlocked */
4161       __HAL_UNLOCK(hi2c);
4162 
4163       /* Note : The I2C interrupts must be enabled after unlocking current process
4164                 to avoid the risk of I2C interrupt handle execution before current
4165                 process unlock */
4166       /* Enable ERR, TC, STOP, NACK, RXI interrupt */
4167       /* possible to enable all of these */
4168       /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
4169         I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
4170       I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT);
4171     }
4172 
4173     return HAL_OK;
4174   }
4175   else
4176   {
4177     return HAL_BUSY;
4178   }
4179 }
4180 #endif /* HAL_DMA_MODULE_ENABLED */
4181 
4182 /**
4183   * @brief  Sequential transmit in slave/device I2C mode an amount of data in non-blocking mode with Interrupt
4184   * @note   This interface allow to manage repeated start condition when a direction change during transfer
4185   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
4186   *                the configuration information for the specified I2C.
4187   * @param  pData Pointer to data buffer
4188   * @param  Size Amount of data to be sent
4189   * @param  XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
4190   * @retval HAL status
4191   */
HAL_I2C_Slave_Seq_Transmit_IT(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size,uint32_t XferOptions)4192 HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
4193                                                 uint32_t XferOptions)
4194 {
4195   /* Declaration of tmp to prevent undefined behavior of volatile usage */
4196   FlagStatus tmp;
4197 
4198   /* Check the parameters */
4199   assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
4200 
4201   if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
4202   {
4203     if ((pData == NULL) || (Size == 0U))
4204     {
4205       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
4206       return  HAL_ERROR;
4207     }
4208 
4209     /* Disable Interrupts, to prevent preemption during treatment in case of multicall */
4210     I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT);
4211 
4212     /* Process Locked */
4213     __HAL_LOCK(hi2c);
4214 
4215     /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */
4216     /* and then toggle the HAL slave RX state to TX state */
4217     if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN)
4218     {
4219       /* Disable associated Interrupts */
4220       I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
4221 
4222 #if defined(HAL_DMA_MODULE_ENABLED)
4223       /* Abort DMA Xfer if any */
4224       if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN)
4225       {
4226         hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
4227 
4228         if (hi2c->hdmarx != NULL)
4229         {
4230           /* Set the I2C DMA Abort callback :
4231            will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
4232           hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort;
4233 
4234           /* Abort DMA RX */
4235           if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK)
4236           {
4237             /* Call Directly XferAbortCallback function in case of error */
4238             hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx);
4239           }
4240         }
4241       }
4242 #endif /* HAL_DMA_MODULE_ENABLED */
4243     }
4244 
4245     hi2c->State     = HAL_I2C_STATE_BUSY_TX_LISTEN;
4246     hi2c->Mode      = HAL_I2C_MODE_SLAVE;
4247     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
4248 
4249     /* Enable Address Acknowledge */
4250     hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
4251 
4252     /* Prepare transfer parameters */
4253     hi2c->pBuffPtr    = pData;
4254     hi2c->XferCount   = Size;
4255     hi2c->XferSize    = hi2c->XferCount;
4256     hi2c->XferOptions = XferOptions;
4257     hi2c->XferISR     = I2C_Slave_ISR_IT;
4258 
4259     tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR);
4260     if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_RECEIVE) && (tmp != RESET))
4261     {
4262       /* Clear ADDR flag after prepare the transfer parameters */
4263       /* This action will generate an acknowledge to the Master */
4264       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
4265     }
4266 
4267     /* Process Unlocked */
4268     __HAL_UNLOCK(hi2c);
4269 
4270     /* Note : The I2C interrupts must be enabled after unlocking current process
4271     to avoid the risk of I2C interrupt handle execution before current
4272     process unlock */
4273     /* REnable ADDR interrupt */
4274     I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT | I2C_XFER_LISTEN_IT);
4275 
4276     return HAL_OK;
4277   }
4278   else
4279   {
4280     return HAL_ERROR;
4281   }
4282 }
4283 
4284 #if defined(HAL_DMA_MODULE_ENABLED)
4285 /**
4286   * @brief  Sequential transmit in slave/device I2C mode an amount of data in non-blocking mode with DMA
4287   * @note   This interface allow to manage repeated start condition when a direction change during transfer
4288   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
4289   *                the configuration information for the specified I2C.
4290   * @param  pData Pointer to data buffer
4291   * @param  Size Amount of data to be sent
4292   * @param  XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
4293   * @retval HAL status
4294   */
HAL_I2C_Slave_Seq_Transmit_DMA(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size,uint32_t XferOptions)4295 HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
4296                                                  uint32_t XferOptions)
4297 {
4298   /* Declaration of tmp to prevent undefined behavior of volatile usage */
4299   FlagStatus tmp;
4300   HAL_StatusTypeDef dmaxferstatus;
4301 
4302   /* Check the parameters */
4303   assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
4304 
4305   if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
4306   {
4307     if ((pData == NULL) || (Size == 0U))
4308     {
4309       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
4310       return  HAL_ERROR;
4311     }
4312 
4313     /* Process Locked */
4314     __HAL_LOCK(hi2c);
4315 
4316     /* Disable Interrupts, to prevent preemption during treatment in case of multicall */
4317     I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT);
4318 
4319     /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */
4320     /* and then toggle the HAL slave RX state to TX state */
4321     if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN)
4322     {
4323       /* Disable associated Interrupts */
4324       I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
4325 
4326       if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN)
4327       {
4328         /* Abort DMA Xfer if any */
4329         if (hi2c->hdmarx != NULL)
4330         {
4331           hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
4332 
4333           /* Set the I2C DMA Abort callback :
4334           will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
4335           hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort;
4336 
4337           /* Abort DMA RX */
4338           if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK)
4339           {
4340             /* Call Directly XferAbortCallback function in case of error */
4341             hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx);
4342           }
4343         }
4344       }
4345     }
4346     else if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN)
4347     {
4348       if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN)
4349       {
4350         hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
4351 
4352         /* Abort DMA Xfer if any */
4353         if (hi2c->hdmatx != NULL)
4354         {
4355           /* Set the I2C DMA Abort callback :
4356           will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
4357           hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort;
4358 
4359           /* Abort DMA TX */
4360           if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK)
4361           {
4362             /* Call Directly XferAbortCallback function in case of error */
4363             hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx);
4364           }
4365         }
4366       }
4367     }
4368     else
4369     {
4370       /* Nothing to do */
4371     }
4372 
4373     hi2c->State     = HAL_I2C_STATE_BUSY_TX_LISTEN;
4374     hi2c->Mode      = HAL_I2C_MODE_SLAVE;
4375     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
4376 
4377     /* Enable Address Acknowledge */
4378     hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
4379 
4380     /* Prepare transfer parameters */
4381     hi2c->pBuffPtr    = pData;
4382     hi2c->XferCount   = Size;
4383     hi2c->XferSize    = hi2c->XferCount;
4384     hi2c->XferOptions = XferOptions;
4385     hi2c->XferISR     = I2C_Slave_ISR_DMA;
4386 
4387     if (hi2c->hdmatx != NULL)
4388     {
4389       /* Set the I2C DMA transfer complete callback */
4390       hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt;
4391 
4392       /* Set the DMA error callback */
4393       hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
4394 
4395       /* Set the unused DMA callbacks to NULL */
4396       hi2c->hdmatx->XferHalfCpltCallback = NULL;
4397       hi2c->hdmatx->XferAbortCallback = NULL;
4398 
4399       /* Enable the DMA channel */
4400       if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
4401       {
4402         if (hi2c->hdmatx->LinkedListQueue != NULL)
4403         {
4404           /* Set DMA data size */
4405           hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
4406 
4407           /* Set DMA source address */
4408           hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData;
4409 
4410           /* Set DMA destination address */
4411           hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \
4412             = (uint32_t)&hi2c->Instance->TXDR;
4413 
4414           dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx);
4415         }
4416         else
4417         {
4418           /* Update I2C state */
4419           hi2c->State     = HAL_I2C_STATE_LISTEN;
4420           hi2c->Mode      = HAL_I2C_MODE_NONE;
4421 
4422           /* Update I2C error code */
4423           hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
4424 
4425           /* Process Unlocked */
4426           __HAL_UNLOCK(hi2c);
4427 
4428           return HAL_ERROR;
4429         }
4430       }
4431       else
4432       {
4433         dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR,
4434                                          hi2c->XferSize);
4435       }
4436     }
4437     else
4438     {
4439       /* Update I2C state */
4440       hi2c->State     = HAL_I2C_STATE_LISTEN;
4441       hi2c->Mode      = HAL_I2C_MODE_NONE;
4442 
4443       /* Update I2C error code */
4444       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
4445 
4446       /* Process Unlocked */
4447       __HAL_UNLOCK(hi2c);
4448 
4449       return HAL_ERROR;
4450     }
4451 
4452     if (dmaxferstatus == HAL_OK)
4453     {
4454       /* Update XferCount value */
4455       hi2c->XferCount -= hi2c->XferSize;
4456 
4457       /* Reset XferSize */
4458       hi2c->XferSize = 0;
4459     }
4460     else
4461     {
4462       /* Update I2C state */
4463       hi2c->State     = HAL_I2C_STATE_LISTEN;
4464       hi2c->Mode      = HAL_I2C_MODE_NONE;
4465 
4466       /* Update I2C error code */
4467       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
4468 
4469       /* Process Unlocked */
4470       __HAL_UNLOCK(hi2c);
4471 
4472       return HAL_ERROR;
4473     }
4474 
4475     tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR);
4476     if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_RECEIVE) && (tmp != RESET))
4477     {
4478       /* Clear ADDR flag after prepare the transfer parameters */
4479       /* This action will generate an acknowledge to the Master */
4480       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
4481     }
4482 
4483     /* Process Unlocked */
4484     __HAL_UNLOCK(hi2c);
4485 
4486     /* Enable DMA Request */
4487     hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
4488 
4489     /* Note : The I2C interrupts must be enabled after unlocking current process
4490     to avoid the risk of I2C interrupt handle execution before current
4491     process unlock */
4492     /* Enable ERR, STOP, NACK, ADDR interrupts */
4493     I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
4494 
4495     return HAL_OK;
4496   }
4497   else
4498   {
4499     return HAL_ERROR;
4500   }
4501 }
4502 #endif /* HAL_DMA_MODULE_ENABLED */
4503 
4504 /**
4505   * @brief  Sequential receive in slave/device I2C mode an amount of data in non-blocking mode with Interrupt
4506   * @note   This interface allow to manage repeated start condition when a direction change during transfer
4507   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
4508   *                the configuration information for the specified I2C.
4509   * @param  pData Pointer to data buffer
4510   * @param  Size Amount of data to be sent
4511   * @param  XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
4512   * @retval HAL status
4513   */
HAL_I2C_Slave_Seq_Receive_IT(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size,uint32_t XferOptions)4514 HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
4515                                                uint32_t XferOptions)
4516 {
4517   /* Declaration of tmp to prevent undefined behavior of volatile usage */
4518   FlagStatus tmp;
4519 
4520   /* Check the parameters */
4521   assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
4522 
4523   if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
4524   {
4525     if ((pData == NULL) || (Size == 0U))
4526     {
4527       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
4528       return  HAL_ERROR;
4529     }
4530 
4531     /* Disable Interrupts, to prevent preemption during treatment in case of multicall */
4532     I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT);
4533 
4534     /* Process Locked */
4535     __HAL_LOCK(hi2c);
4536 
4537     /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */
4538     /* and then toggle the HAL slave TX state to RX state */
4539     if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN)
4540     {
4541       /* Disable associated Interrupts */
4542       I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
4543 
4544 #if defined(HAL_DMA_MODULE_ENABLED)
4545       if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN)
4546       {
4547         hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
4548 
4549         /* Abort DMA Xfer if any */
4550         if (hi2c->hdmatx != NULL)
4551         {
4552           /* Set the I2C DMA Abort callback :
4553            will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
4554           hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort;
4555 
4556           /* Abort DMA TX */
4557           if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK)
4558           {
4559             /* Call Directly XferAbortCallback function in case of error */
4560             hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx);
4561           }
4562         }
4563       }
4564 #endif /* HAL_DMA_MODULE_ENABLED */
4565     }
4566 
4567     hi2c->State     = HAL_I2C_STATE_BUSY_RX_LISTEN;
4568     hi2c->Mode      = HAL_I2C_MODE_SLAVE;
4569     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
4570 
4571     /* Enable Address Acknowledge */
4572     hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
4573 
4574     /* Prepare transfer parameters */
4575     hi2c->pBuffPtr    = pData;
4576     hi2c->XferCount   = Size;
4577     hi2c->XferSize    = hi2c->XferCount;
4578     hi2c->XferOptions = XferOptions;
4579     hi2c->XferISR     = I2C_Slave_ISR_IT;
4580 
4581     tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR);
4582     if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_TRANSMIT) && (tmp != RESET))
4583     {
4584       /* Clear ADDR flag after prepare the transfer parameters */
4585       /* This action will generate an acknowledge to the Master */
4586       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
4587     }
4588 
4589     /* Process Unlocked */
4590     __HAL_UNLOCK(hi2c);
4591 
4592     /* Note : The I2C interrupts must be enabled after unlocking current process
4593     to avoid the risk of I2C interrupt handle execution before current
4594     process unlock */
4595     /* REnable ADDR interrupt */
4596     I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT);
4597 
4598     return HAL_OK;
4599   }
4600   else
4601   {
4602     return HAL_ERROR;
4603   }
4604 }
4605 
4606 #if defined(HAL_DMA_MODULE_ENABLED)
4607 /**
4608   * @brief  Sequential receive in slave/device I2C mode an amount of data in non-blocking mode with DMA
4609   * @note   This interface allow to manage repeated start condition when a direction change during transfer
4610   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
4611   *                the configuration information for the specified I2C.
4612   * @param  pData Pointer to data buffer
4613   * @param  Size Amount of data to be sent
4614   * @param  XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
4615   * @retval HAL status
4616   */
HAL_I2C_Slave_Seq_Receive_DMA(I2C_HandleTypeDef * hi2c,uint8_t * pData,uint16_t Size,uint32_t XferOptions)4617 HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
4618                                                 uint32_t XferOptions)
4619 {
4620   /* Declaration of tmp to prevent undefined behavior of volatile usage */
4621   FlagStatus tmp;
4622   HAL_StatusTypeDef dmaxferstatus;
4623 
4624   /* Check the parameters */
4625   assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
4626 
4627   if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
4628   {
4629     if ((pData == NULL) || (Size == 0U))
4630     {
4631       hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
4632       return  HAL_ERROR;
4633     }
4634 
4635     /* Disable Interrupts, to prevent preemption during treatment in case of multicall */
4636     I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT);
4637 
4638     /* Process Locked */
4639     __HAL_LOCK(hi2c);
4640 
4641     /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */
4642     /* and then toggle the HAL slave TX state to RX state */
4643     if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN)
4644     {
4645       /* Disable associated Interrupts */
4646       I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
4647 
4648       if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN)
4649       {
4650         /* Abort DMA Xfer if any */
4651         if (hi2c->hdmatx != NULL)
4652         {
4653           hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
4654 
4655           /* Set the I2C DMA Abort callback :
4656            will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
4657           hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort;
4658 
4659           /* Abort DMA TX */
4660           if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK)
4661           {
4662             /* Call Directly XferAbortCallback function in case of error */
4663             hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx);
4664           }
4665         }
4666       }
4667     }
4668     else if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN)
4669     {
4670       if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN)
4671       {
4672         hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
4673 
4674         /* Abort DMA Xfer if any */
4675         if (hi2c->hdmarx != NULL)
4676         {
4677           /* Set the I2C DMA Abort callback :
4678            will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
4679           hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort;
4680 
4681           /* Abort DMA RX */
4682           if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK)
4683           {
4684             /* Call Directly XferAbortCallback function in case of error */
4685             hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx);
4686           }
4687         }
4688       }
4689     }
4690     else
4691     {
4692       /* Nothing to do */
4693     }
4694 
4695     hi2c->State     = HAL_I2C_STATE_BUSY_RX_LISTEN;
4696     hi2c->Mode      = HAL_I2C_MODE_SLAVE;
4697     hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
4698 
4699     /* Enable Address Acknowledge */
4700     hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
4701 
4702     /* Prepare transfer parameters */
4703     hi2c->pBuffPtr    = pData;
4704     hi2c->XferCount   = Size;
4705     hi2c->XferSize    = hi2c->XferCount;
4706     hi2c->XferOptions = XferOptions;
4707     hi2c->XferISR     = I2C_Slave_ISR_DMA;
4708 
4709     if (hi2c->hdmarx != NULL)
4710     {
4711       /* Set the I2C DMA transfer complete callback */
4712       hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt;
4713 
4714       /* Set the DMA error callback */
4715       hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
4716 
4717       /* Set the unused DMA callbacks to NULL */
4718       hi2c->hdmarx->XferHalfCpltCallback = NULL;
4719       hi2c->hdmarx->XferAbortCallback = NULL;
4720 
4721       /* Enable the DMA channel */
4722       if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
4723       {
4724         if (hi2c->hdmarx->LinkedListQueue != NULL)
4725         {
4726           /* Set DMA data size */
4727           hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
4728 
4729           /* Set DMA source address */
4730           hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \
4731             = (uint32_t)&hi2c->Instance->RXDR;
4732 
4733           /* Set DMA destination address */
4734           hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData;
4735 
4736           dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx);
4737         }
4738         else
4739         {
4740           /* Update I2C state */
4741           hi2c->State     = HAL_I2C_STATE_LISTEN;
4742           hi2c->Mode      = HAL_I2C_MODE_NONE;
4743 
4744           /* Update I2C error code */
4745           hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
4746 
4747           /* Process Unlocked */
4748           __HAL_UNLOCK(hi2c);
4749 
4750           return HAL_ERROR;
4751         }
4752       }
4753       else
4754       {
4755         dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData,
4756                                          hi2c->XferSize);
4757       }
4758     }
4759     else
4760     {
4761       /* Update I2C state */
4762       hi2c->State     = HAL_I2C_STATE_LISTEN;
4763       hi2c->Mode      = HAL_I2C_MODE_NONE;
4764 
4765       /* Update I2C error code */
4766       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
4767 
4768       /* Process Unlocked */
4769       __HAL_UNLOCK(hi2c);
4770 
4771       return HAL_ERROR;
4772     }
4773 
4774     if (dmaxferstatus == HAL_OK)
4775     {
4776       /* Update XferCount value */
4777       hi2c->XferCount -= hi2c->XferSize;
4778 
4779       /* Reset XferSize */
4780       hi2c->XferSize = 0;
4781     }
4782     else
4783     {
4784       /* Update I2C state */
4785       hi2c->State     = HAL_I2C_STATE_LISTEN;
4786       hi2c->Mode      = HAL_I2C_MODE_NONE;
4787 
4788       /* Update I2C error code */
4789       hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
4790 
4791       /* Process Unlocked */
4792       __HAL_UNLOCK(hi2c);
4793 
4794       return HAL_ERROR;
4795     }
4796 
4797     tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR);
4798     if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_TRANSMIT) && (tmp != RESET))
4799     {
4800       /* Clear ADDR flag after prepare the transfer parameters */
4801       /* This action will generate an acknowledge to the Master */
4802       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
4803     }
4804 
4805     /* Process Unlocked */
4806     __HAL_UNLOCK(hi2c);
4807 
4808     /* Enable DMA Request */
4809     hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
4810 
4811     /* Note : The I2C interrupts must be enabled after unlocking current process
4812     to avoid the risk of I2C interrupt handle execution before current
4813     process unlock */
4814     /* REnable ADDR interrupt */
4815     I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT);
4816 
4817     return HAL_OK;
4818   }
4819   else
4820   {
4821     return HAL_ERROR;
4822   }
4823 }
4824 #endif /* HAL_DMA_MODULE_ENABLED */
4825 
4826 /**
4827   * @brief  Enable the Address listen mode with Interrupt.
4828   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
4829   *                the configuration information for the specified I2C.
4830   * @retval HAL status
4831   */
HAL_I2C_EnableListen_IT(I2C_HandleTypeDef * hi2c)4832 HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c)
4833 {
4834   if (hi2c->State == HAL_I2C_STATE_READY)
4835   {
4836     hi2c->State = HAL_I2C_STATE_LISTEN;
4837     hi2c->XferISR = I2C_Slave_ISR_IT;
4838 
4839     /* Enable the Address Match interrupt */
4840     I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
4841 
4842     return HAL_OK;
4843   }
4844   else
4845   {
4846     return HAL_BUSY;
4847   }
4848 }
4849 
4850 /**
4851   * @brief  Disable the Address listen mode with Interrupt.
4852   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
4853   *                the configuration information for the specified I2C
4854   * @retval HAL status
4855   */
HAL_I2C_DisableListen_IT(I2C_HandleTypeDef * hi2c)4856 HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c)
4857 {
4858   /* Declaration of tmp to prevent undefined behavior of volatile usage */
4859   uint32_t tmp;
4860 
4861   /* Disable Address listen mode only if a transfer is not ongoing */
4862   if (hi2c->State == HAL_I2C_STATE_LISTEN)
4863   {
4864     tmp = (uint32_t)(hi2c->State) & I2C_STATE_MSK;
4865     hi2c->PreviousState = tmp | (uint32_t)(hi2c->Mode);
4866     hi2c->State = HAL_I2C_STATE_READY;
4867     hi2c->Mode = HAL_I2C_MODE_NONE;
4868     hi2c->XferISR = NULL;
4869 
4870     /* Disable the Address Match interrupt */
4871     I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
4872 
4873     return HAL_OK;
4874   }
4875   else
4876   {
4877     return HAL_BUSY;
4878   }
4879 }
4880 
4881 /**
4882   * @brief  Abort a master or memory I2C IT or DMA process communication with Interrupt.
4883   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
4884   *                the configuration information for the specified I2C.
4885   * @param  DevAddress Target device address: The device 7 bits address value
4886   *         in datasheet must be shifted to the left before calling the interface
4887   * @retval HAL status
4888   */
HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef * hi2c,uint16_t DevAddress)4889 HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress)
4890 {
4891   HAL_I2C_ModeTypeDef tmp_mode = hi2c->Mode;
4892 
4893   if ((tmp_mode == HAL_I2C_MODE_MASTER) || (tmp_mode == HAL_I2C_MODE_MEM))
4894   {
4895     /* Process Locked */
4896     __HAL_LOCK(hi2c);
4897 
4898     /* Disable Interrupts and Store Previous state */
4899     if (hi2c->State == HAL_I2C_STATE_BUSY_TX)
4900     {
4901       I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
4902       hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX;
4903     }
4904     else if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
4905     {
4906       I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
4907       hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX;
4908     }
4909     else
4910     {
4911       /* Do nothing */
4912     }
4913 
4914     /* Set State at HAL_I2C_STATE_ABORT */
4915     hi2c->State = HAL_I2C_STATE_ABORT;
4916 
4917     /* Set NBYTES to 1 to generate a dummy read on I2C peripheral */
4918     /* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */
4919     I2C_TransferConfig(hi2c, DevAddress, 1, I2C_AUTOEND_MODE, I2C_GENERATE_STOP);
4920 
4921     /* Process Unlocked */
4922     __HAL_UNLOCK(hi2c);
4923 
4924     /* Note : The I2C interrupts must be enabled after unlocking current process
4925               to avoid the risk of I2C interrupt handle execution before current
4926               process unlock */
4927     I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT);
4928 
4929     return HAL_OK;
4930   }
4931   else
4932   {
4933     /* Wrong usage of abort function */
4934     /* This function should be used only in case of abort monitored by master device */
4935     return HAL_ERROR;
4936   }
4937 }
4938 
4939 /**
4940   * @}
4941   */
4942 
4943 /** @defgroup I2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks
4944   * @{
4945   */
4946 
4947 /**
4948   * @brief  This function handles I2C event interrupt request.
4949   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
4950   *                the configuration information for the specified I2C.
4951   * @retval None
4952   */
HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef * hi2c)4953 void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c) /* Derogation MISRAC2012-Rule-8.13 */
4954 {
4955   /* Get current IT Flags and IT sources value */
4956   uint32_t itflags   = READ_REG(hi2c->Instance->ISR);
4957   uint32_t itsources = READ_REG(hi2c->Instance->CR1);
4958 
4959   /* I2C events treatment -------------------------------------*/
4960   if (hi2c->XferISR != NULL)
4961   {
4962     hi2c->XferISR(hi2c, itflags, itsources);
4963   }
4964 }
4965 
4966 /**
4967   * @brief  This function handles I2C error interrupt request.
4968   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
4969   *                the configuration information for the specified I2C.
4970   * @retval None
4971   */
HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef * hi2c)4972 void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c)
4973 {
4974   uint32_t itflags   = READ_REG(hi2c->Instance->ISR);
4975   uint32_t itsources = READ_REG(hi2c->Instance->CR1);
4976   uint32_t tmperror;
4977 
4978   /* I2C Bus error interrupt occurred ------------------------------------*/
4979   if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_BERR) != RESET) && \
4980       (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET))
4981   {
4982     hi2c->ErrorCode |= HAL_I2C_ERROR_BERR;
4983 
4984     /* Clear BERR flag */
4985     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR);
4986   }
4987 
4988   /* I2C Over-Run/Under-Run interrupt occurred ----------------------------------------*/
4989   if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_OVR) != RESET) && \
4990       (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET))
4991   {
4992     hi2c->ErrorCode |= HAL_I2C_ERROR_OVR;
4993 
4994     /* Clear OVR flag */
4995     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR);
4996   }
4997 
4998   /* I2C Arbitration Loss error interrupt occurred -------------------------------------*/
4999   if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_ARLO) != RESET) && \
5000       (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET))
5001   {
5002     hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO;
5003 
5004     /* Clear ARLO flag */
5005     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO);
5006   }
5007 
5008   /* Store current volatile hi2c->ErrorCode, misra rule */
5009   tmperror = hi2c->ErrorCode;
5010 
5011   /* Call the Error Callback in case of Error detected */
5012   if ((tmperror & (HAL_I2C_ERROR_BERR | HAL_I2C_ERROR_OVR | HAL_I2C_ERROR_ARLO)) !=  HAL_I2C_ERROR_NONE)
5013   {
5014     I2C_ITError(hi2c, tmperror);
5015   }
5016 }
5017 
5018 /**
5019   * @brief  Master Tx Transfer completed callback.
5020   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5021   *                the configuration information for the specified I2C.
5022   * @retval None
5023   */
HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef * hi2c)5024 __weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c)
5025 {
5026   /* Prevent unused argument(s) compilation warning */
5027   UNUSED(hi2c);
5028 
5029   /* NOTE : This function should not be modified, when the callback is needed,
5030             the HAL_I2C_MasterTxCpltCallback could be implemented in the user file
5031    */
5032 }
5033 
5034 /**
5035   * @brief  Master Rx Transfer completed callback.
5036   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5037   *                the configuration information for the specified I2C.
5038   * @retval None
5039   */
HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef * hi2c)5040 __weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c)
5041 {
5042   /* Prevent unused argument(s) compilation warning */
5043   UNUSED(hi2c);
5044 
5045   /* NOTE : This function should not be modified, when the callback is needed,
5046             the HAL_I2C_MasterRxCpltCallback could be implemented in the user file
5047    */
5048 }
5049 
5050 /** @brief  Slave Tx Transfer completed callback.
5051   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5052   *                the configuration information for the specified I2C.
5053   * @retval None
5054   */
HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef * hi2c)5055 __weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c)
5056 {
5057   /* Prevent unused argument(s) compilation warning */
5058   UNUSED(hi2c);
5059 
5060   /* NOTE : This function should not be modified, when the callback is needed,
5061             the HAL_I2C_SlaveTxCpltCallback could be implemented in the user file
5062    */
5063 }
5064 
5065 /**
5066   * @brief  Slave Rx Transfer completed callback.
5067   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5068   *                the configuration information for the specified I2C.
5069   * @retval None
5070   */
HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef * hi2c)5071 __weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c)
5072 {
5073   /* Prevent unused argument(s) compilation warning */
5074   UNUSED(hi2c);
5075 
5076   /* NOTE : This function should not be modified, when the callback is needed,
5077             the HAL_I2C_SlaveRxCpltCallback could be implemented in the user file
5078    */
5079 }
5080 
5081 /**
5082   * @brief  Slave Address Match callback.
5083   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5084   *                the configuration information for the specified I2C.
5085   * @param  TransferDirection Master request Transfer Direction (Write/Read), value of @ref I2C_XFERDIRECTION
5086   * @param  AddrMatchCode Address Match Code
5087   * @retval None
5088   */
HAL_I2C_AddrCallback(I2C_HandleTypeDef * hi2c,uint8_t TransferDirection,uint16_t AddrMatchCode)5089 __weak void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode)
5090 {
5091   /* Prevent unused argument(s) compilation warning */
5092   UNUSED(hi2c);
5093   UNUSED(TransferDirection);
5094   UNUSED(AddrMatchCode);
5095 
5096   /* NOTE : This function should not be modified, when the callback is needed,
5097             the HAL_I2C_AddrCallback() could be implemented in the user file
5098    */
5099 }
5100 
5101 /**
5102   * @brief  Listen Complete callback.
5103   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5104   *                the configuration information for the specified I2C.
5105   * @retval None
5106   */
HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef * hi2c)5107 __weak void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c)
5108 {
5109   /* Prevent unused argument(s) compilation warning */
5110   UNUSED(hi2c);
5111 
5112   /* NOTE : This function should not be modified, when the callback is needed,
5113             the HAL_I2C_ListenCpltCallback() could be implemented in the user file
5114    */
5115 }
5116 
5117 /**
5118   * @brief  Memory Tx Transfer completed callback.
5119   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5120   *                the configuration information for the specified I2C.
5121   * @retval None
5122   */
HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef * hi2c)5123 __weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c)
5124 {
5125   /* Prevent unused argument(s) compilation warning */
5126   UNUSED(hi2c);
5127 
5128   /* NOTE : This function should not be modified, when the callback is needed,
5129             the HAL_I2C_MemTxCpltCallback could be implemented in the user file
5130    */
5131 }
5132 
5133 /**
5134   * @brief  Memory Rx Transfer completed callback.
5135   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5136   *                the configuration information for the specified I2C.
5137   * @retval None
5138   */
HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef * hi2c)5139 __weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c)
5140 {
5141   /* Prevent unused argument(s) compilation warning */
5142   UNUSED(hi2c);
5143 
5144   /* NOTE : This function should not be modified, when the callback is needed,
5145             the HAL_I2C_MemRxCpltCallback could be implemented in the user file
5146    */
5147 }
5148 
5149 /**
5150   * @brief  I2C error callback.
5151   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5152   *                the configuration information for the specified I2C.
5153   * @retval None
5154   */
HAL_I2C_ErrorCallback(I2C_HandleTypeDef * hi2c)5155 __weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c)
5156 {
5157   /* Prevent unused argument(s) compilation warning */
5158   UNUSED(hi2c);
5159 
5160   /* NOTE : This function should not be modified, when the callback is needed,
5161             the HAL_I2C_ErrorCallback could be implemented in the user file
5162    */
5163 }
5164 
5165 /**
5166   * @brief  I2C abort callback.
5167   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5168   *                the configuration information for the specified I2C.
5169   * @retval None
5170   */
HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef * hi2c)5171 __weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c)
5172 {
5173   /* Prevent unused argument(s) compilation warning */
5174   UNUSED(hi2c);
5175 
5176   /* NOTE : This function should not be modified, when the callback is needed,
5177             the HAL_I2C_AbortCpltCallback could be implemented in the user file
5178    */
5179 }
5180 
5181 /**
5182   * @}
5183   */
5184 
5185 /** @defgroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions
5186   *  @brief   Peripheral State, Mode and Error functions
5187   *
5188 @verbatim
5189  ===============================================================================
5190             ##### Peripheral State, Mode and Error functions #####
5191  ===============================================================================
5192     [..]
5193     This subsection permit to get in run-time the status of the peripheral
5194     and the data flow.
5195 
5196 @endverbatim
5197   * @{
5198   */
5199 
5200 /**
5201   * @brief  Return the I2C handle state.
5202   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5203   *                the configuration information for the specified I2C.
5204   * @retval HAL state
5205   */
HAL_I2C_GetState(const I2C_HandleTypeDef * hi2c)5206 HAL_I2C_StateTypeDef HAL_I2C_GetState(const I2C_HandleTypeDef *hi2c)
5207 {
5208   /* Return I2C handle state */
5209   return hi2c->State;
5210 }
5211 
5212 /**
5213   * @brief  Returns the I2C Master, Slave, Memory or no mode.
5214   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5215   *         the configuration information for I2C module
5216   * @retval HAL mode
5217   */
HAL_I2C_GetMode(const I2C_HandleTypeDef * hi2c)5218 HAL_I2C_ModeTypeDef HAL_I2C_GetMode(const I2C_HandleTypeDef *hi2c)
5219 {
5220   return hi2c->Mode;
5221 }
5222 
5223 /**
5224   * @brief  Return the I2C error code.
5225   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5226   *              the configuration information for the specified I2C.
5227   * @retval I2C Error Code
5228   */
HAL_I2C_GetError(const I2C_HandleTypeDef * hi2c)5229 uint32_t HAL_I2C_GetError(const I2C_HandleTypeDef *hi2c)
5230 {
5231   return hi2c->ErrorCode;
5232 }
5233 
5234 /**
5235   * @}
5236   */
5237 
5238 /**
5239   * @}
5240   */
5241 
5242 /** @addtogroup I2C_Private_Functions
5243   * @{
5244   */
5245 
5246 /**
5247   * @brief  Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with Interrupt.
5248   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5249   *                the configuration information for the specified I2C.
5250   * @param  ITFlags Interrupt flags to handle.
5251   * @param  ITSources Interrupt sources enabled.
5252   * @retval HAL status
5253   */
I2C_Master_ISR_IT(struct __I2C_HandleTypeDef * hi2c,uint32_t ITFlags,uint32_t ITSources)5254 static HAL_StatusTypeDef I2C_Master_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
5255                                            uint32_t ITSources)
5256 {
5257   uint16_t devaddress;
5258   uint32_t tmpITFlags = ITFlags;
5259 
5260   /* Process Locked */
5261   __HAL_LOCK(hi2c);
5262 
5263   if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \
5264       (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
5265   {
5266     /* Clear NACK Flag */
5267     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
5268 
5269     /* Set corresponding Error Code */
5270     /* No need to generate STOP, it is automatically done */
5271     /* Error callback will be send during stop flag treatment */
5272     hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
5273 
5274     /* Flush TX register */
5275     I2C_Flush_TXDR(hi2c);
5276   }
5277   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \
5278            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET))
5279   {
5280     /* Remove RXNE flag on temporary variable as read done */
5281     tmpITFlags &= ~I2C_FLAG_RXNE;
5282 
5283     /* Read data from RXDR */
5284     *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
5285 
5286     /* Increment Buffer pointer */
5287     hi2c->pBuffPtr++;
5288 
5289     hi2c->XferSize--;
5290     hi2c->XferCount--;
5291   }
5292   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \
5293            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET))
5294   {
5295     /* Write data to TXDR */
5296     hi2c->Instance->TXDR = *hi2c->pBuffPtr;
5297 
5298     /* Increment Buffer pointer */
5299     hi2c->pBuffPtr++;
5300 
5301     hi2c->XferSize--;
5302     hi2c->XferCount--;
5303   }
5304   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TCR) != RESET) && \
5305            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
5306   {
5307     if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
5308     {
5309       devaddress = (uint16_t)(hi2c->Instance->CR2 & I2C_CR2_SADD);
5310 
5311       if (hi2c->XferCount > MAX_NBYTE_SIZE)
5312       {
5313         hi2c->XferSize = MAX_NBYTE_SIZE;
5314         I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP);
5315       }
5316       else
5317       {
5318         hi2c->XferSize = hi2c->XferCount;
5319         if (hi2c->XferOptions != I2C_NO_OPTION_FRAME)
5320         {
5321           I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize,
5322                              hi2c->XferOptions, I2C_NO_STARTSTOP);
5323         }
5324         else
5325         {
5326           I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize,
5327                              I2C_AUTOEND_MODE, I2C_NO_STARTSTOP);
5328         }
5329       }
5330     }
5331     else
5332     {
5333       /* Call TxCpltCallback() if no stop mode is set */
5334       if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE)
5335       {
5336         /* Call I2C Master Sequential complete process */
5337         I2C_ITMasterSeqCplt(hi2c);
5338       }
5339       else
5340       {
5341         /* Wrong size Status regarding TCR flag event */
5342         /* Call the corresponding callback to inform upper layer of End of Transfer */
5343         I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
5344       }
5345     }
5346   }
5347   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TC) != RESET) && \
5348            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
5349   {
5350     if (hi2c->XferCount == 0U)
5351     {
5352       if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE)
5353       {
5354         /* Generate a stop condition in case of no transfer option */
5355         if (hi2c->XferOptions == I2C_NO_OPTION_FRAME)
5356         {
5357           /* Generate Stop */
5358           hi2c->Instance->CR2 |= I2C_CR2_STOP;
5359         }
5360         else
5361         {
5362           /* Call I2C Master Sequential complete process */
5363           I2C_ITMasterSeqCplt(hi2c);
5364         }
5365       }
5366     }
5367     else
5368     {
5369       /* Wrong size Status regarding TC flag event */
5370       /* Call the corresponding callback to inform upper layer of End of Transfer */
5371       I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
5372     }
5373   }
5374   else
5375   {
5376     /* Nothing to do */
5377   }
5378 
5379   if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \
5380       (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
5381   {
5382     /* Call I2C Master complete process */
5383     I2C_ITMasterCplt(hi2c, tmpITFlags);
5384   }
5385 
5386   /* Process Unlocked */
5387   __HAL_UNLOCK(hi2c);
5388 
5389   return HAL_OK;
5390 }
5391 
5392 /**
5393   * @brief  Interrupt Sub-Routine which handle the Interrupt Flags Memory Mode with Interrupt.
5394   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5395   *                the configuration information for the specified I2C.
5396   * @param  ITFlags Interrupt flags to handle.
5397   * @param  ITSources Interrupt sources enabled.
5398   * @retval HAL status
5399   */
I2C_Mem_ISR_IT(struct __I2C_HandleTypeDef * hi2c,uint32_t ITFlags,uint32_t ITSources)5400 static HAL_StatusTypeDef I2C_Mem_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
5401                                         uint32_t ITSources)
5402 {
5403   uint32_t direction = I2C_GENERATE_START_WRITE;
5404   uint32_t tmpITFlags = ITFlags;
5405 
5406   /* Process Locked */
5407   __HAL_LOCK(hi2c);
5408 
5409   if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \
5410       (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
5411   {
5412     /* Clear NACK Flag */
5413     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
5414 
5415     /* Set corresponding Error Code */
5416     /* No need to generate STOP, it is automatically done */
5417     /* Error callback will be send during stop flag treatment */
5418     hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
5419 
5420     /* Flush TX register */
5421     I2C_Flush_TXDR(hi2c);
5422   }
5423   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \
5424            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET))
5425   {
5426     /* Remove RXNE flag on temporary variable as read done */
5427     tmpITFlags &= ~I2C_FLAG_RXNE;
5428 
5429     /* Read data from RXDR */
5430     *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
5431 
5432     /* Increment Buffer pointer */
5433     hi2c->pBuffPtr++;
5434 
5435     hi2c->XferSize--;
5436     hi2c->XferCount--;
5437   }
5438   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \
5439            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET))
5440   {
5441     if (hi2c->Memaddress == 0xFFFFFFFFU)
5442     {
5443       /* Write data to TXDR */
5444       hi2c->Instance->TXDR = *hi2c->pBuffPtr;
5445 
5446       /* Increment Buffer pointer */
5447       hi2c->pBuffPtr++;
5448 
5449       hi2c->XferSize--;
5450       hi2c->XferCount--;
5451     }
5452     else
5453     {
5454       /* Write LSB part of Memory Address */
5455       hi2c->Instance->TXDR = hi2c->Memaddress;
5456 
5457       /* Reset Memaddress content */
5458       hi2c->Memaddress = 0xFFFFFFFFU;
5459     }
5460   }
5461   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TCR) != RESET) && \
5462            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
5463   {
5464     if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
5465     {
5466       if (hi2c->XferCount > MAX_NBYTE_SIZE)
5467       {
5468         hi2c->XferSize = MAX_NBYTE_SIZE;
5469         I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize,
5470                            I2C_RELOAD_MODE, I2C_NO_STARTSTOP);
5471       }
5472       else
5473       {
5474         hi2c->XferSize = hi2c->XferCount;
5475         I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize,
5476                            I2C_AUTOEND_MODE, I2C_NO_STARTSTOP);
5477       }
5478     }
5479     else
5480     {
5481       /* Wrong size Status regarding TCR flag event */
5482       /* Call the corresponding callback to inform upper layer of End of Transfer */
5483       I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
5484     }
5485   }
5486   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TC) != RESET) && \
5487            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
5488   {
5489     /* Disable Interrupt related to address step */
5490     I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
5491 
5492     /* Enable ERR, TC, STOP, NACK and RXI interrupts */
5493     I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT);
5494 
5495     if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
5496     {
5497       direction = I2C_GENERATE_START_READ;
5498     }
5499 
5500     if (hi2c->XferCount > MAX_NBYTE_SIZE)
5501     {
5502       hi2c->XferSize = MAX_NBYTE_SIZE;
5503 
5504       /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
5505       I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize,
5506                          I2C_RELOAD_MODE, direction);
5507     }
5508     else
5509     {
5510       hi2c->XferSize = hi2c->XferCount;
5511 
5512       /* Set NBYTES to write and generate RESTART */
5513       I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize,
5514                          I2C_AUTOEND_MODE, direction);
5515     }
5516   }
5517   else
5518   {
5519     /* Nothing to do */
5520   }
5521 
5522   if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \
5523       (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
5524   {
5525     /* Call I2C Master complete process */
5526     I2C_ITMasterCplt(hi2c, tmpITFlags);
5527   }
5528 
5529   /* Process Unlocked */
5530   __HAL_UNLOCK(hi2c);
5531 
5532   return HAL_OK;
5533 }
5534 
5535 /**
5536   * @brief  Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with Interrupt.
5537   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5538   *                the configuration information for the specified I2C.
5539   * @param  ITFlags Interrupt flags to handle.
5540   * @param  ITSources Interrupt sources enabled.
5541   * @retval HAL status
5542   */
I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef * hi2c,uint32_t ITFlags,uint32_t ITSources)5543 static HAL_StatusTypeDef I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
5544                                           uint32_t ITSources)
5545 {
5546   uint32_t tmpoptions = hi2c->XferOptions;
5547   uint32_t tmpITFlags = ITFlags;
5548 
5549   /* Process locked */
5550   __HAL_LOCK(hi2c);
5551 
5552   /* Check if STOPF is set */
5553   if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \
5554       (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
5555   {
5556     /* Call I2C Slave complete process */
5557     I2C_ITSlaveCplt(hi2c, tmpITFlags);
5558   }
5559   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \
5560            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
5561   {
5562     /* Check that I2C transfer finished */
5563     /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */
5564     /* Mean XferCount == 0*/
5565     /* So clear Flag NACKF only */
5566     if (hi2c->XferCount == 0U)
5567     {
5568       if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME))
5569         /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for
5570            Warning[Pa134]: left and right operands are identical */
5571       {
5572         /* Call I2C Listen complete process */
5573         I2C_ITListenCplt(hi2c, tmpITFlags);
5574       }
5575       else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME))
5576       {
5577         /* Clear NACK Flag */
5578         __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
5579 
5580         /* Flush TX register */
5581         I2C_Flush_TXDR(hi2c);
5582 
5583         /* Last Byte is Transmitted */
5584         /* Call I2C Slave Sequential complete process */
5585         I2C_ITSlaveSeqCplt(hi2c);
5586       }
5587       else
5588       {
5589         /* Clear NACK Flag */
5590         __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
5591       }
5592     }
5593     else
5594     {
5595       /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/
5596       /* Clear NACK Flag */
5597       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
5598 
5599       /* Set ErrorCode corresponding to a Non-Acknowledge */
5600       hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
5601 
5602       if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME))
5603       {
5604         /* Call the corresponding callback to inform upper layer of End of Transfer */
5605         I2C_ITError(hi2c, hi2c->ErrorCode);
5606       }
5607     }
5608   }
5609   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \
5610            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET))
5611   {
5612     if (hi2c->XferCount > 0U)
5613     {
5614       /* Read data from RXDR */
5615       *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
5616 
5617       /* Increment Buffer pointer */
5618       hi2c->pBuffPtr++;
5619 
5620       hi2c->XferSize--;
5621       hi2c->XferCount--;
5622     }
5623 
5624     if ((hi2c->XferCount == 0U) && \
5625         (tmpoptions != I2C_NO_OPTION_FRAME))
5626     {
5627       /* Call I2C Slave Sequential complete process */
5628       I2C_ITSlaveSeqCplt(hi2c);
5629     }
5630   }
5631   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_ADDR) != RESET) && \
5632            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_ADDRI) != RESET))
5633   {
5634     I2C_ITAddrCplt(hi2c, tmpITFlags);
5635   }
5636   else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \
5637            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET))
5638   {
5639     /* Write data to TXDR only if XferCount not reach "0" */
5640     /* A TXIS flag can be set, during STOP treatment      */
5641     /* Check if all Data have already been sent */
5642     /* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */
5643     if (hi2c->XferCount > 0U)
5644     {
5645       /* Write data to TXDR */
5646       hi2c->Instance->TXDR = *hi2c->pBuffPtr;
5647 
5648       /* Increment Buffer pointer */
5649       hi2c->pBuffPtr++;
5650 
5651       hi2c->XferCount--;
5652       hi2c->XferSize--;
5653     }
5654     else
5655     {
5656       if ((tmpoptions == I2C_NEXT_FRAME) || (tmpoptions == I2C_FIRST_FRAME))
5657       {
5658         /* Last Byte is Transmitted */
5659         /* Call I2C Slave Sequential complete process */
5660         I2C_ITSlaveSeqCplt(hi2c);
5661       }
5662     }
5663   }
5664   else
5665   {
5666     /* Nothing to do */
5667   }
5668 
5669   /* Process Unlocked */
5670   __HAL_UNLOCK(hi2c);
5671 
5672   return HAL_OK;
5673 }
5674 
5675 #if defined(HAL_DMA_MODULE_ENABLED)
5676 /**
5677   * @brief  Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with DMA.
5678   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5679   *                the configuration information for the specified I2C.
5680   * @param  ITFlags Interrupt flags to handle.
5681   * @param  ITSources Interrupt sources enabled.
5682   * @retval HAL status
5683   */
I2C_Master_ISR_DMA(struct __I2C_HandleTypeDef * hi2c,uint32_t ITFlags,uint32_t ITSources)5684 static HAL_StatusTypeDef I2C_Master_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
5685                                             uint32_t ITSources)
5686 {
5687   uint16_t devaddress;
5688   uint32_t xfermode;
5689 
5690   /* Process Locked */
5691   __HAL_LOCK(hi2c);
5692 
5693   if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \
5694       (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
5695   {
5696     /* Clear NACK Flag */
5697     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
5698 
5699     /* Set corresponding Error Code */
5700     hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
5701 
5702     /* No need to generate STOP, it is automatically done */
5703     /* But enable STOP interrupt, to treat it */
5704     /* Error callback will be send during stop flag treatment */
5705     I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT);
5706 
5707     /* Flush TX register */
5708     I2C_Flush_TXDR(hi2c);
5709   }
5710   else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TCR) != RESET) && \
5711            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
5712   {
5713     /* Disable TC interrupt */
5714     __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_TCI);
5715 
5716     if (hi2c->XferCount != 0U)
5717     {
5718       /* Recover Slave address */
5719       devaddress = (uint16_t)(hi2c->Instance->CR2 & I2C_CR2_SADD);
5720 
5721       /* Prepare the new XferSize to transfer */
5722       if (hi2c->XferCount > MAX_NBYTE_SIZE)
5723       {
5724         hi2c->XferSize = MAX_NBYTE_SIZE;
5725         xfermode = I2C_RELOAD_MODE;
5726       }
5727       else
5728       {
5729         hi2c->XferSize = hi2c->XferCount;
5730         if (hi2c->XferOptions != I2C_NO_OPTION_FRAME)
5731         {
5732           xfermode = hi2c->XferOptions;
5733         }
5734         else
5735         {
5736           xfermode = I2C_AUTOEND_MODE;
5737         }
5738       }
5739 
5740       /* Set the new XferSize in Nbytes register */
5741       I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, xfermode, I2C_NO_STARTSTOP);
5742 
5743       /* Update XferCount value */
5744       hi2c->XferCount -= hi2c->XferSize;
5745 
5746       /* Enable DMA Request */
5747       if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
5748       {
5749         hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
5750       }
5751       else
5752       {
5753         hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
5754       }
5755     }
5756     else
5757     {
5758       /* Call TxCpltCallback() if no stop mode is set */
5759       if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE)
5760       {
5761         /* Call I2C Master Sequential complete process */
5762         I2C_ITMasterSeqCplt(hi2c);
5763       }
5764       else
5765       {
5766         /* Wrong size Status regarding TCR flag event */
5767         /* Call the corresponding callback to inform upper layer of End of Transfer */
5768         I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
5769       }
5770     }
5771   }
5772   else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TC) != RESET) && \
5773            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
5774   {
5775     if (hi2c->XferCount == 0U)
5776     {
5777       if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE)
5778       {
5779         /* Generate a stop condition in case of no transfer option */
5780         if (hi2c->XferOptions == I2C_NO_OPTION_FRAME)
5781         {
5782           /* Generate Stop */
5783           hi2c->Instance->CR2 |= I2C_CR2_STOP;
5784         }
5785         else
5786         {
5787           /* Call I2C Master Sequential complete process */
5788           I2C_ITMasterSeqCplt(hi2c);
5789         }
5790       }
5791     }
5792     else
5793     {
5794       /* Wrong size Status regarding TC flag event */
5795       /* Call the corresponding callback to inform upper layer of End of Transfer */
5796       I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
5797     }
5798   }
5799   else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \
5800            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
5801   {
5802     /* Call I2C Master complete process */
5803     I2C_ITMasterCplt(hi2c, ITFlags);
5804   }
5805   else
5806   {
5807     /* Nothing to do */
5808   }
5809 
5810   /* Process Unlocked */
5811   __HAL_UNLOCK(hi2c);
5812 
5813   return HAL_OK;
5814 }
5815 
5816 /**
5817   * @brief  Interrupt Sub-Routine which handle the Interrupt Flags Memory Mode with DMA.
5818   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5819   *                the configuration information for the specified I2C.
5820   * @param  ITFlags Interrupt flags to handle.
5821   * @param  ITSources Interrupt sources enabled.
5822   * @retval HAL status
5823   */
I2C_Mem_ISR_DMA(struct __I2C_HandleTypeDef * hi2c,uint32_t ITFlags,uint32_t ITSources)5824 static HAL_StatusTypeDef I2C_Mem_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
5825                                          uint32_t ITSources)
5826 {
5827   uint32_t direction = I2C_GENERATE_START_WRITE;
5828 
5829   /* Process Locked */
5830   __HAL_LOCK(hi2c);
5831 
5832   if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \
5833       (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
5834   {
5835     /* Clear NACK Flag */
5836     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
5837 
5838     /* Set corresponding Error Code */
5839     hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
5840 
5841     /* No need to generate STOP, it is automatically done */
5842     /* But enable STOP interrupt, to treat it */
5843     /* Error callback will be send during stop flag treatment */
5844     I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT);
5845 
5846     /* Flush TX register */
5847     I2C_Flush_TXDR(hi2c);
5848   }
5849   else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TXIS) != RESET) && \
5850            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET))
5851   {
5852     /* Write LSB part of Memory Address */
5853     hi2c->Instance->TXDR = hi2c->Memaddress;
5854 
5855     /* Reset Memaddress content */
5856     hi2c->Memaddress = 0xFFFFFFFFU;
5857   }
5858   else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TCR) != RESET) && \
5859            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
5860   {
5861     /* Disable Interrupt related to address step */
5862     I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
5863 
5864     /* Enable only Error interrupt */
5865     I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
5866 
5867     if (hi2c->XferCount != 0U)
5868     {
5869       /* Prepare the new XferSize to transfer */
5870       if (hi2c->XferCount > MAX_NBYTE_SIZE)
5871       {
5872         hi2c->XferSize = MAX_NBYTE_SIZE;
5873         I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize,
5874                            I2C_RELOAD_MODE, I2C_NO_STARTSTOP);
5875       }
5876       else
5877       {
5878         hi2c->XferSize = hi2c->XferCount;
5879         I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize,
5880                            I2C_AUTOEND_MODE, I2C_NO_STARTSTOP);
5881       }
5882 
5883       /* Update XferCount value */
5884       hi2c->XferCount -= hi2c->XferSize;
5885 
5886       /* Enable DMA Request */
5887       if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
5888       {
5889         hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
5890       }
5891       else
5892       {
5893         hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
5894       }
5895     }
5896     else
5897     {
5898       /* Wrong size Status regarding TCR flag event */
5899       /* Call the corresponding callback to inform upper layer of End of Transfer */
5900       I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
5901     }
5902   }
5903   else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TC) != RESET) && \
5904            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
5905   {
5906     /* Disable Interrupt related to address step */
5907     I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
5908 
5909     /* Enable only Error and NACK interrupt for data transfer */
5910     I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
5911 
5912     if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
5913     {
5914       direction = I2C_GENERATE_START_READ;
5915     }
5916 
5917     if (hi2c->XferCount > MAX_NBYTE_SIZE)
5918     {
5919       hi2c->XferSize = MAX_NBYTE_SIZE;
5920 
5921       /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
5922       I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize,
5923                          I2C_RELOAD_MODE, direction);
5924     }
5925     else
5926     {
5927       hi2c->XferSize = hi2c->XferCount;
5928 
5929       /* Set NBYTES to write and generate RESTART */
5930       I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize,
5931                          I2C_AUTOEND_MODE, direction);
5932     }
5933 
5934     /* Update XferCount value */
5935     hi2c->XferCount -= hi2c->XferSize;
5936 
5937     /* Enable DMA Request */
5938     if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
5939     {
5940       hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
5941     }
5942     else
5943     {
5944       hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
5945     }
5946   }
5947   else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \
5948            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
5949   {
5950     /* Call I2C Master complete process */
5951     I2C_ITMasterCplt(hi2c, ITFlags);
5952   }
5953   else
5954   {
5955     /* Nothing to do */
5956   }
5957 
5958   /* Process Unlocked */
5959   __HAL_UNLOCK(hi2c);
5960 
5961   return HAL_OK;
5962 }
5963 
5964 /**
5965   * @brief  Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with DMA.
5966   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
5967   *                the configuration information for the specified I2C.
5968   * @param  ITFlags Interrupt flags to handle.
5969   * @param  ITSources Interrupt sources enabled.
5970   * @retval HAL status
5971   */
I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef * hi2c,uint32_t ITFlags,uint32_t ITSources)5972 static HAL_StatusTypeDef I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
5973                                            uint32_t ITSources)
5974 {
5975   uint32_t tmpoptions = hi2c->XferOptions;
5976   uint32_t treatdmanack = 0U;
5977   HAL_I2C_StateTypeDef tmpstate;
5978 
5979   /* Process locked */
5980   __HAL_LOCK(hi2c);
5981 
5982   /* Check if STOPF is set */
5983   if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \
5984       (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
5985   {
5986     /* Call I2C Slave complete process */
5987     I2C_ITSlaveCplt(hi2c, ITFlags);
5988   }
5989   else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \
5990            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
5991   {
5992     /* Check that I2C transfer finished */
5993     /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */
5994     /* Mean XferCount == 0 */
5995     /* So clear Flag NACKF only */
5996     if ((I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_TXDMAEN) != RESET) ||
5997         (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_RXDMAEN) != RESET))
5998     {
5999       /* Split check of hdmarx, for MISRA compliance */
6000       if (hi2c->hdmarx != NULL)
6001       {
6002         if (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_RXDMAEN) != RESET)
6003         {
6004           if (I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx) == 0U)
6005           {
6006             treatdmanack = 1U;
6007           }
6008         }
6009       }
6010 
6011       /* Split check of hdmatx, for MISRA compliance  */
6012       if (hi2c->hdmatx != NULL)
6013       {
6014         if (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_TXDMAEN) != RESET)
6015         {
6016           if (I2C_GET_DMA_REMAIN_DATA(hi2c->hdmatx) == 0U)
6017           {
6018             treatdmanack = 1U;
6019           }
6020         }
6021       }
6022 
6023       if (treatdmanack == 1U)
6024       {
6025         if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME))
6026           /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for
6027              Warning[Pa134]: left and right operands are identical */
6028         {
6029           /* Call I2C Listen complete process */
6030           I2C_ITListenCplt(hi2c, ITFlags);
6031         }
6032         else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME))
6033         {
6034           /* Clear NACK Flag */
6035           __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6036 
6037           /* Flush TX register */
6038           I2C_Flush_TXDR(hi2c);
6039 
6040           /* Last Byte is Transmitted */
6041           /* Call I2C Slave Sequential complete process */
6042           I2C_ITSlaveSeqCplt(hi2c);
6043         }
6044         else
6045         {
6046           /* Clear NACK Flag */
6047           __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6048         }
6049       }
6050       else
6051       {
6052         /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/
6053         /* Clear NACK Flag */
6054         __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6055 
6056         /* Set ErrorCode corresponding to a Non-Acknowledge */
6057         hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
6058 
6059         /* Store current hi2c->State, solve MISRA2012-Rule-13.5 */
6060         tmpstate = hi2c->State;
6061 
6062         if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME))
6063         {
6064           if ((tmpstate == HAL_I2C_STATE_BUSY_TX) || (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN))
6065           {
6066             hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX;
6067           }
6068           else if ((tmpstate == HAL_I2C_STATE_BUSY_RX) || (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN))
6069           {
6070             hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX;
6071           }
6072           else
6073           {
6074             /* Do nothing */
6075           }
6076 
6077           /* Call the corresponding callback to inform upper layer of End of Transfer */
6078           I2C_ITError(hi2c, hi2c->ErrorCode);
6079         }
6080       }
6081     }
6082     else
6083     {
6084       /* Only Clear NACK Flag, no DMA treatment is pending */
6085       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6086     }
6087   }
6088   else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_ADDR) != RESET) && \
6089            (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_ADDRI) != RESET))
6090   {
6091     I2C_ITAddrCplt(hi2c, ITFlags);
6092   }
6093   else
6094   {
6095     /* Nothing to do */
6096   }
6097 
6098   /* Process Unlocked */
6099   __HAL_UNLOCK(hi2c);
6100 
6101   return HAL_OK;
6102 }
6103 #endif /* HAL_DMA_MODULE_ENABLED */
6104 
6105 /**
6106   * @brief  Master sends target device address followed by internal memory address for write request.
6107   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
6108   *                the configuration information for the specified I2C.
6109   * @param  DevAddress Target device address: The device 7 bits address value
6110   *         in datasheet must be shifted to the left before calling the interface
6111   * @param  MemAddress Internal memory address
6112   * @param  MemAddSize Size of internal memory address
6113   * @param  Timeout Timeout duration
6114   * @param  Tickstart Tick start value
6115   * @retval HAL status
6116   */
I2C_RequestMemoryWrite(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint16_t MemAddress,uint16_t MemAddSize,uint32_t Timeout,uint32_t Tickstart)6117 static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
6118                                                 uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout,
6119                                                 uint32_t Tickstart)
6120 {
6121   I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE);
6122 
6123   /* Wait until TXIS flag is set */
6124   if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
6125   {
6126     return HAL_ERROR;
6127   }
6128 
6129   /* If Memory address size is 8Bit */
6130   if (MemAddSize == I2C_MEMADD_SIZE_8BIT)
6131   {
6132     /* Send Memory Address */
6133     hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
6134   }
6135   /* If Memory address size is 16Bit */
6136   else
6137   {
6138     /* Send MSB of Memory Address */
6139     hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress);
6140 
6141     /* Wait until TXIS flag is set */
6142     if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
6143     {
6144       return HAL_ERROR;
6145     }
6146 
6147     /* Send LSB of Memory Address */
6148     hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
6149   }
6150 
6151   /* Wait until TCR flag is set */
6152   if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, Tickstart) != HAL_OK)
6153   {
6154     return HAL_ERROR;
6155   }
6156 
6157   return HAL_OK;
6158 }
6159 
6160 /**
6161   * @brief  Master sends target device address followed by internal memory address for read request.
6162   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
6163   *                the configuration information for the specified I2C.
6164   * @param  DevAddress Target device address: The device 7 bits address value
6165   *         in datasheet must be shifted to the left before calling the interface
6166   * @param  MemAddress Internal memory address
6167   * @param  MemAddSize Size of internal memory address
6168   * @param  Timeout Timeout duration
6169   * @param  Tickstart Tick start value
6170   * @retval HAL status
6171   */
I2C_RequestMemoryRead(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint16_t MemAddress,uint16_t MemAddSize,uint32_t Timeout,uint32_t Tickstart)6172 static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
6173                                                uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout,
6174                                                uint32_t Tickstart)
6175 {
6176   I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE);
6177 
6178   /* Wait until TXIS flag is set */
6179   if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
6180   {
6181     return HAL_ERROR;
6182   }
6183 
6184   /* If Memory address size is 8Bit */
6185   if (MemAddSize == I2C_MEMADD_SIZE_8BIT)
6186   {
6187     /* Send Memory Address */
6188     hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
6189   }
6190   /* If Memory address size is 16Bit */
6191   else
6192   {
6193     /* Send MSB of Memory Address */
6194     hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress);
6195 
6196     /* Wait until TXIS flag is set */
6197     if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
6198     {
6199       return HAL_ERROR;
6200     }
6201 
6202     /* Send LSB of Memory Address */
6203     hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
6204   }
6205 
6206   /* Wait until TC flag is set */
6207   if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TC, RESET, Timeout, Tickstart) != HAL_OK)
6208   {
6209     return HAL_ERROR;
6210   }
6211 
6212   return HAL_OK;
6213 }
6214 
6215 /**
6216   * @brief  I2C Address complete process callback.
6217   * @param  hi2c I2C handle.
6218   * @param  ITFlags Interrupt flags to handle.
6219   * @retval None
6220   */
I2C_ITAddrCplt(I2C_HandleTypeDef * hi2c,uint32_t ITFlags)6221 static void I2C_ITAddrCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags)
6222 {
6223   uint8_t transferdirection;
6224   uint16_t slaveaddrcode;
6225   uint16_t ownadd1code;
6226   uint16_t ownadd2code;
6227 
6228   /* Prevent unused argument(s) compilation warning */
6229   UNUSED(ITFlags);
6230 
6231   /* In case of Listen state, need to inform upper layer of address match code event */
6232   if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
6233   {
6234     transferdirection = I2C_GET_DIR(hi2c);
6235     slaveaddrcode     = I2C_GET_ADDR_MATCH(hi2c);
6236     ownadd1code       = I2C_GET_OWN_ADDRESS1(hi2c);
6237     ownadd2code       = I2C_GET_OWN_ADDRESS2(hi2c);
6238 
6239     /* If 10bits addressing mode is selected */
6240     if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)
6241     {
6242       if ((slaveaddrcode & SLAVE_ADDR_MSK) == ((ownadd1code >> SLAVE_ADDR_SHIFT) & SLAVE_ADDR_MSK))
6243       {
6244         slaveaddrcode = ownadd1code;
6245         hi2c->AddrEventCount++;
6246         if (hi2c->AddrEventCount == 2U)
6247         {
6248           /* Reset Address Event counter */
6249           hi2c->AddrEventCount = 0U;
6250 
6251           /* Clear ADDR flag */
6252           __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
6253 
6254           /* Process Unlocked */
6255           __HAL_UNLOCK(hi2c);
6256 
6257           /* Call Slave Addr callback */
6258 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6259           hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode);
6260 #else
6261           HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode);
6262 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6263         }
6264       }
6265       else
6266       {
6267         slaveaddrcode = ownadd2code;
6268 
6269         /* Disable ADDR Interrupts */
6270         I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
6271 
6272         /* Process Unlocked */
6273         __HAL_UNLOCK(hi2c);
6274 
6275         /* Call Slave Addr callback */
6276 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6277         hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode);
6278 #else
6279         HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode);
6280 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6281       }
6282     }
6283     /* else 7 bits addressing mode is selected */
6284     else
6285     {
6286       /* Disable ADDR Interrupts */
6287       I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
6288 
6289       /* Process Unlocked */
6290       __HAL_UNLOCK(hi2c);
6291 
6292       /* Call Slave Addr callback */
6293 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6294       hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode);
6295 #else
6296       HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode);
6297 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6298     }
6299   }
6300   /* Else clear address flag only */
6301   else
6302   {
6303     /* Clear ADDR flag */
6304     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
6305 
6306     /* Process Unlocked */
6307     __HAL_UNLOCK(hi2c);
6308   }
6309 }
6310 
6311 /**
6312   * @brief  I2C Master sequential complete process.
6313   * @param  hi2c I2C handle.
6314   * @retval None
6315   */
I2C_ITMasterSeqCplt(I2C_HandleTypeDef * hi2c)6316 static void I2C_ITMasterSeqCplt(I2C_HandleTypeDef *hi2c)
6317 {
6318   /* Reset I2C handle mode */
6319   hi2c->Mode = HAL_I2C_MODE_NONE;
6320 
6321   /* No Generate Stop, to permit restart mode */
6322   /* The stop will be done at the end of transfer, when I2C_AUTOEND_MODE enable */
6323   if (hi2c->State == HAL_I2C_STATE_BUSY_TX)
6324   {
6325     hi2c->State         = HAL_I2C_STATE_READY;
6326     hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX;
6327     hi2c->XferISR       = NULL;
6328 
6329     /* Disable Interrupts */
6330     I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
6331 
6332     /* Process Unlocked */
6333     __HAL_UNLOCK(hi2c);
6334 
6335     /* Call the corresponding callback to inform upper layer of End of Transfer */
6336 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6337     hi2c->MasterTxCpltCallback(hi2c);
6338 #else
6339     HAL_I2C_MasterTxCpltCallback(hi2c);
6340 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6341   }
6342   /* hi2c->State == HAL_I2C_STATE_BUSY_RX */
6343   else
6344   {
6345     hi2c->State         = HAL_I2C_STATE_READY;
6346     hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX;
6347     hi2c->XferISR       = NULL;
6348 
6349     /* Disable Interrupts */
6350     I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
6351 
6352     /* Process Unlocked */
6353     __HAL_UNLOCK(hi2c);
6354 
6355     /* Call the corresponding callback to inform upper layer of End of Transfer */
6356 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6357     hi2c->MasterRxCpltCallback(hi2c);
6358 #else
6359     HAL_I2C_MasterRxCpltCallback(hi2c);
6360 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6361   }
6362 }
6363 
6364 /**
6365   * @brief  I2C Slave sequential complete process.
6366   * @param  hi2c I2C handle.
6367   * @retval None
6368   */
I2C_ITSlaveSeqCplt(I2C_HandleTypeDef * hi2c)6369 static void I2C_ITSlaveSeqCplt(I2C_HandleTypeDef *hi2c)
6370 {
6371   uint32_t tmpcr1value = READ_REG(hi2c->Instance->CR1);
6372 
6373   /* Reset I2C handle mode */
6374   hi2c->Mode = HAL_I2C_MODE_NONE;
6375 
6376 #if defined(HAL_DMA_MODULE_ENABLED)
6377   /* If a DMA is ongoing, Update handle size context */
6378   if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_TXDMAEN) != RESET)
6379   {
6380     /* Disable DMA Request */
6381     hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
6382   }
6383   else if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_RXDMAEN) != RESET)
6384   {
6385     /* Disable DMA Request */
6386     hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
6387   }
6388   else
6389   {
6390     /* Do nothing */
6391   }
6392 #endif /* HAL_DMA_MODULE_ENABLED */
6393 
6394   if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN)
6395   {
6396     /* Remove HAL_I2C_STATE_SLAVE_BUSY_TX, keep only HAL_I2C_STATE_LISTEN */
6397     hi2c->State         = HAL_I2C_STATE_LISTEN;
6398     hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX;
6399 
6400     /* Disable Interrupts */
6401     I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
6402 
6403     /* Process Unlocked */
6404     __HAL_UNLOCK(hi2c);
6405 
6406     /* Call the corresponding callback to inform upper layer of End of Transfer */
6407 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6408     hi2c->SlaveTxCpltCallback(hi2c);
6409 #else
6410     HAL_I2C_SlaveTxCpltCallback(hi2c);
6411 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6412   }
6413 
6414   else if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN)
6415   {
6416     /* Remove HAL_I2C_STATE_SLAVE_BUSY_RX, keep only HAL_I2C_STATE_LISTEN */
6417     hi2c->State         = HAL_I2C_STATE_LISTEN;
6418     hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX;
6419 
6420     /* Disable Interrupts */
6421     I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
6422 
6423     /* Process Unlocked */
6424     __HAL_UNLOCK(hi2c);
6425 
6426     /* Call the corresponding callback to inform upper layer of End of Transfer */
6427 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6428     hi2c->SlaveRxCpltCallback(hi2c);
6429 #else
6430     HAL_I2C_SlaveRxCpltCallback(hi2c);
6431 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6432   }
6433   else
6434   {
6435     /* Nothing to do */
6436   }
6437 }
6438 
6439 /**
6440   * @brief  I2C Master complete process.
6441   * @param  hi2c I2C handle.
6442   * @param  ITFlags Interrupt flags to handle.
6443   * @retval None
6444   */
I2C_ITMasterCplt(I2C_HandleTypeDef * hi2c,uint32_t ITFlags)6445 static void I2C_ITMasterCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags)
6446 {
6447   uint32_t tmperror;
6448   uint32_t tmpITFlags = ITFlags;
6449   __IO uint32_t tmpreg;
6450 
6451   /* Clear STOP Flag */
6452   __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
6453 
6454   /* Disable Interrupts and Store Previous state */
6455   if (hi2c->State == HAL_I2C_STATE_BUSY_TX)
6456   {
6457     I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
6458     hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX;
6459   }
6460   else if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
6461   {
6462     I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
6463     hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX;
6464   }
6465   else
6466   {
6467     /* Do nothing */
6468   }
6469 
6470   /* Clear Configuration Register 2 */
6471   I2C_RESET_CR2(hi2c);
6472 
6473   /* Reset handle parameters */
6474   hi2c->XferISR       = NULL;
6475   hi2c->XferOptions   = I2C_NO_OPTION_FRAME;
6476 
6477   if (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET)
6478   {
6479     /* Clear NACK Flag */
6480     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6481 
6482     /* Set acknowledge error code */
6483     hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
6484   }
6485 
6486   /* Fetch Last receive data if any */
6487   if ((hi2c->State == HAL_I2C_STATE_ABORT) && (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET))
6488   {
6489     /* Read data from RXDR */
6490     tmpreg = (uint8_t)hi2c->Instance->RXDR;
6491     UNUSED(tmpreg);
6492   }
6493 
6494   /* Flush TX register */
6495   I2C_Flush_TXDR(hi2c);
6496 
6497   /* Store current volatile hi2c->ErrorCode, misra rule */
6498   tmperror = hi2c->ErrorCode;
6499 
6500   /* Call the corresponding callback to inform upper layer of End of Transfer */
6501   if ((hi2c->State == HAL_I2C_STATE_ABORT) || (tmperror != HAL_I2C_ERROR_NONE))
6502   {
6503     /* Call the corresponding callback to inform upper layer of End of Transfer */
6504     I2C_ITError(hi2c, hi2c->ErrorCode);
6505   }
6506   /* hi2c->State == HAL_I2C_STATE_BUSY_TX */
6507   else if (hi2c->State == HAL_I2C_STATE_BUSY_TX)
6508   {
6509     hi2c->State = HAL_I2C_STATE_READY;
6510     hi2c->PreviousState = I2C_STATE_NONE;
6511 
6512     if (hi2c->Mode == HAL_I2C_MODE_MEM)
6513     {
6514       hi2c->Mode = HAL_I2C_MODE_NONE;
6515 
6516       /* Process Unlocked */
6517       __HAL_UNLOCK(hi2c);
6518 
6519       /* Call the corresponding callback to inform upper layer of End of Transfer */
6520 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6521       hi2c->MemTxCpltCallback(hi2c);
6522 #else
6523       HAL_I2C_MemTxCpltCallback(hi2c);
6524 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6525     }
6526     else
6527     {
6528       hi2c->Mode = HAL_I2C_MODE_NONE;
6529 
6530       /* Process Unlocked */
6531       __HAL_UNLOCK(hi2c);
6532 
6533       /* Call the corresponding callback to inform upper layer of End of Transfer */
6534 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6535       hi2c->MasterTxCpltCallback(hi2c);
6536 #else
6537       HAL_I2C_MasterTxCpltCallback(hi2c);
6538 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6539     }
6540   }
6541   /* hi2c->State == HAL_I2C_STATE_BUSY_RX */
6542   else if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
6543   {
6544     hi2c->State = HAL_I2C_STATE_READY;
6545     hi2c->PreviousState = I2C_STATE_NONE;
6546 
6547     if (hi2c->Mode == HAL_I2C_MODE_MEM)
6548     {
6549       hi2c->Mode = HAL_I2C_MODE_NONE;
6550 
6551       /* Process Unlocked */
6552       __HAL_UNLOCK(hi2c);
6553 
6554       /* Call the corresponding callback to inform upper layer of End of Transfer */
6555 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6556       hi2c->MemRxCpltCallback(hi2c);
6557 #else
6558       HAL_I2C_MemRxCpltCallback(hi2c);
6559 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6560     }
6561     else
6562     {
6563       hi2c->Mode = HAL_I2C_MODE_NONE;
6564 
6565       /* Process Unlocked */
6566       __HAL_UNLOCK(hi2c);
6567 
6568       /* Call the corresponding callback to inform upper layer of End of Transfer */
6569 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6570       hi2c->MasterRxCpltCallback(hi2c);
6571 #else
6572       HAL_I2C_MasterRxCpltCallback(hi2c);
6573 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6574     }
6575   }
6576   else
6577   {
6578     /* Nothing to do */
6579   }
6580 }
6581 
6582 /**
6583   * @brief  I2C Slave complete process.
6584   * @param  hi2c I2C handle.
6585   * @param  ITFlags Interrupt flags to handle.
6586   * @retval None
6587   */
I2C_ITSlaveCplt(I2C_HandleTypeDef * hi2c,uint32_t ITFlags)6588 static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags)
6589 {
6590   uint32_t tmpcr1value = READ_REG(hi2c->Instance->CR1);
6591   uint32_t tmpITFlags = ITFlags;
6592   uint32_t tmpoptions = hi2c->XferOptions;
6593   HAL_I2C_StateTypeDef tmpstate = hi2c->State;
6594 
6595   /* Clear STOP Flag */
6596   __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
6597 
6598   /* Disable Interrupts and Store Previous state */
6599   if ((tmpstate == HAL_I2C_STATE_BUSY_TX) || (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN))
6600   {
6601     I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT);
6602     hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX;
6603   }
6604   else if ((tmpstate == HAL_I2C_STATE_BUSY_RX) || (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN))
6605   {
6606     I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT);
6607     hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX;
6608   }
6609   else if (tmpstate == HAL_I2C_STATE_LISTEN)
6610   {
6611     I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT | I2C_XFER_RX_IT);
6612     hi2c->PreviousState = I2C_STATE_NONE;
6613   }
6614   else
6615   {
6616     /* Do nothing */
6617   }
6618 
6619   /* Disable Address Acknowledge */
6620   hi2c->Instance->CR2 |= I2C_CR2_NACK;
6621 
6622   /* Clear Configuration Register 2 */
6623   I2C_RESET_CR2(hi2c);
6624 
6625   /* Flush TX register */
6626   I2C_Flush_TXDR(hi2c);
6627 
6628 #if defined(HAL_DMA_MODULE_ENABLED)
6629   /* If a DMA is ongoing, Update handle size context */
6630   if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_TXDMAEN) != RESET)
6631   {
6632     /* Disable DMA Request */
6633     hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
6634 
6635     if (hi2c->hdmatx != NULL)
6636     {
6637       hi2c->XferCount = (uint16_t)I2C_GET_DMA_REMAIN_DATA(hi2c->hdmatx);
6638     }
6639   }
6640   else if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_RXDMAEN) != RESET)
6641   {
6642     /* Disable DMA Request */
6643     hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
6644 
6645     if (hi2c->hdmarx != NULL)
6646     {
6647       hi2c->XferCount = (uint16_t)I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx);
6648     }
6649   }
6650   else
6651   {
6652     /* Do nothing */
6653   }
6654 #endif /* HAL_DMA_MODULE_ENABLED */
6655 
6656   /* Store Last receive data if any */
6657   if (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET)
6658   {
6659     /* Remove RXNE flag on temporary variable as read done */
6660     tmpITFlags &= ~I2C_FLAG_RXNE;
6661 
6662     /* Read data from RXDR */
6663     *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
6664 
6665     /* Increment Buffer pointer */
6666     hi2c->pBuffPtr++;
6667 
6668     if ((hi2c->XferSize > 0U))
6669     {
6670       hi2c->XferSize--;
6671       hi2c->XferCount--;
6672     }
6673   }
6674 
6675   /* All data are not transferred, so set error code accordingly */
6676   if (hi2c->XferCount != 0U)
6677   {
6678     /* Set ErrorCode corresponding to a Non-Acknowledge */
6679     hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
6680   }
6681 
6682   if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \
6683       (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_IT_NACKI) != RESET))
6684   {
6685     /* Check that I2C transfer finished */
6686     /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */
6687     /* Mean XferCount == 0*/
6688     /* So clear Flag NACKF only */
6689     if (hi2c->XferCount == 0U)
6690     {
6691       if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME))
6692         /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for
6693            Warning[Pa134]: left and right operands are identical */
6694       {
6695         /* Call I2C Listen complete process */
6696         I2C_ITListenCplt(hi2c, tmpITFlags);
6697       }
6698       else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME))
6699       {
6700         /* Clear NACK Flag */
6701         __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6702 
6703         /* Flush TX register */
6704         I2C_Flush_TXDR(hi2c);
6705 
6706         /* Last Byte is Transmitted */
6707         /* Call I2C Slave Sequential complete process */
6708         I2C_ITSlaveSeqCplt(hi2c);
6709       }
6710       else
6711       {
6712         /* Clear NACK Flag */
6713         __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6714       }
6715     }
6716     else
6717     {
6718       /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/
6719       /* Clear NACK Flag */
6720       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6721 
6722       /* Set ErrorCode corresponding to a Non-Acknowledge */
6723       hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
6724 
6725       if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME))
6726       {
6727         /* Call the corresponding callback to inform upper layer of End of Transfer */
6728         I2C_ITError(hi2c, hi2c->ErrorCode);
6729       }
6730     }
6731   }
6732 
6733   hi2c->Mode = HAL_I2C_MODE_NONE;
6734   hi2c->XferISR = NULL;
6735 
6736   if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
6737   {
6738     /* Call the corresponding callback to inform upper layer of End of Transfer */
6739     I2C_ITError(hi2c, hi2c->ErrorCode);
6740 
6741     /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
6742     if (hi2c->State == HAL_I2C_STATE_LISTEN)
6743     {
6744       /* Call I2C Listen complete process */
6745       I2C_ITListenCplt(hi2c, tmpITFlags);
6746     }
6747   }
6748   else if (hi2c->XferOptions != I2C_NO_OPTION_FRAME)
6749   {
6750     /* Call the Sequential Complete callback, to inform upper layer of the end of Transfer */
6751     I2C_ITSlaveSeqCplt(hi2c);
6752 
6753     hi2c->XferOptions = I2C_NO_OPTION_FRAME;
6754     hi2c->State = HAL_I2C_STATE_READY;
6755     hi2c->PreviousState = I2C_STATE_NONE;
6756 
6757     /* Process Unlocked */
6758     __HAL_UNLOCK(hi2c);
6759 
6760     /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
6761 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6762     hi2c->ListenCpltCallback(hi2c);
6763 #else
6764     HAL_I2C_ListenCpltCallback(hi2c);
6765 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6766   }
6767   /* Call the corresponding callback to inform upper layer of End of Transfer */
6768   else if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
6769   {
6770     hi2c->State = HAL_I2C_STATE_READY;
6771     hi2c->PreviousState = I2C_STATE_NONE;
6772 
6773     /* Process Unlocked */
6774     __HAL_UNLOCK(hi2c);
6775 
6776     /* Call the corresponding callback to inform upper layer of End of Transfer */
6777 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6778     hi2c->SlaveRxCpltCallback(hi2c);
6779 #else
6780     HAL_I2C_SlaveRxCpltCallback(hi2c);
6781 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6782   }
6783   else
6784   {
6785     hi2c->State = HAL_I2C_STATE_READY;
6786     hi2c->PreviousState = I2C_STATE_NONE;
6787 
6788     /* Process Unlocked */
6789     __HAL_UNLOCK(hi2c);
6790 
6791     /* Call the corresponding callback to inform upper layer of End of Transfer */
6792 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6793     hi2c->SlaveTxCpltCallback(hi2c);
6794 #else
6795     HAL_I2C_SlaveTxCpltCallback(hi2c);
6796 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6797   }
6798 }
6799 
6800 /**
6801   * @brief  I2C Listen complete process.
6802   * @param  hi2c I2C handle.
6803   * @param  ITFlags Interrupt flags to handle.
6804   * @retval None
6805   */
I2C_ITListenCplt(I2C_HandleTypeDef * hi2c,uint32_t ITFlags)6806 static void I2C_ITListenCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags)
6807 {
6808   /* Reset handle parameters */
6809   hi2c->XferOptions = I2C_NO_OPTION_FRAME;
6810   hi2c->PreviousState = I2C_STATE_NONE;
6811   hi2c->State = HAL_I2C_STATE_READY;
6812   hi2c->Mode = HAL_I2C_MODE_NONE;
6813   hi2c->XferISR = NULL;
6814 
6815   /* Store Last receive data if any */
6816   if (I2C_CHECK_FLAG(ITFlags, I2C_FLAG_RXNE) != RESET)
6817   {
6818     /* Read data from RXDR */
6819     *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
6820 
6821     /* Increment Buffer pointer */
6822     hi2c->pBuffPtr++;
6823 
6824     if ((hi2c->XferSize > 0U))
6825     {
6826       hi2c->XferSize--;
6827       hi2c->XferCount--;
6828 
6829       /* Set ErrorCode corresponding to a Non-Acknowledge */
6830       hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
6831     }
6832   }
6833 
6834   /* Disable all Interrupts*/
6835   I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT | I2C_XFER_TX_IT);
6836 
6837   /* Clear NACK Flag */
6838   __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6839 
6840   /* Process Unlocked */
6841   __HAL_UNLOCK(hi2c);
6842 
6843   /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
6844 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
6845   hi2c->ListenCpltCallback(hi2c);
6846 #else
6847   HAL_I2C_ListenCpltCallback(hi2c);
6848 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
6849 }
6850 
6851 /**
6852   * @brief  I2C interrupts error process.
6853   * @param  hi2c I2C handle.
6854   * @param  ErrorCode Error code to handle.
6855   * @retval None
6856   */
I2C_ITError(I2C_HandleTypeDef * hi2c,uint32_t ErrorCode)6857 static void I2C_ITError(I2C_HandleTypeDef *hi2c, uint32_t ErrorCode)
6858 {
6859   HAL_I2C_StateTypeDef tmpstate = hi2c->State;
6860 
6861 #if defined(HAL_DMA_MODULE_ENABLED)
6862   uint32_t tmppreviousstate;
6863 #endif /* HAL_DMA_MODULE_ENABLED */
6864 
6865   /* Reset handle parameters */
6866   hi2c->Mode          = HAL_I2C_MODE_NONE;
6867   hi2c->XferOptions   = I2C_NO_OPTION_FRAME;
6868   hi2c->XferCount     = 0U;
6869 
6870   /* Set new error code */
6871   hi2c->ErrorCode |= ErrorCode;
6872 
6873   /* Disable Interrupts */
6874   if ((tmpstate == HAL_I2C_STATE_LISTEN)         ||
6875       (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN) ||
6876       (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN))
6877   {
6878     /* Disable all interrupts, except interrupts related to LISTEN state */
6879     I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_TX_IT);
6880 
6881     /* keep HAL_I2C_STATE_LISTEN if set */
6882     hi2c->State         = HAL_I2C_STATE_LISTEN;
6883     hi2c->XferISR       = I2C_Slave_ISR_IT;
6884   }
6885   else
6886   {
6887     /* Disable all interrupts */
6888     I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT | I2C_XFER_TX_IT);
6889 
6890     /* Flush TX register */
6891     I2C_Flush_TXDR(hi2c);
6892 
6893     /* If state is an abort treatment on going, don't change state */
6894     /* This change will be do later */
6895     if (hi2c->State != HAL_I2C_STATE_ABORT)
6896     {
6897       /* Set HAL_I2C_STATE_READY */
6898       hi2c->State         = HAL_I2C_STATE_READY;
6899 
6900       /* Check if a STOPF is detected */
6901       if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET)
6902       {
6903         if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET)
6904         {
6905           __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
6906           hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
6907         }
6908 
6909         /* Clear STOP Flag */
6910         __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
6911       }
6912 
6913     }
6914     hi2c->XferISR       = NULL;
6915   }
6916 
6917 #if defined(HAL_DMA_MODULE_ENABLED)
6918   /* Abort DMA TX transfer if any */
6919   tmppreviousstate = hi2c->PreviousState;
6920 
6921   if ((hi2c->hdmatx != NULL) && ((tmppreviousstate == I2C_STATE_MASTER_BUSY_TX) || \
6922                                  (tmppreviousstate == I2C_STATE_SLAVE_BUSY_TX)))
6923   {
6924     if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN)
6925     {
6926       hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
6927     }
6928 
6929     if (HAL_DMA_GetState(hi2c->hdmatx) != HAL_DMA_STATE_READY)
6930     {
6931       /* Set the I2C DMA Abort callback :
6932        will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
6933       hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort;
6934 
6935       /* Process Unlocked */
6936       __HAL_UNLOCK(hi2c);
6937 
6938       /* Abort DMA TX */
6939       if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK)
6940       {
6941         /* Call Directly XferAbortCallback function in case of error */
6942         hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx);
6943       }
6944     }
6945     else
6946     {
6947       I2C_TreatErrorCallback(hi2c);
6948     }
6949   }
6950   /* Abort DMA RX transfer if any */
6951   else if ((hi2c->hdmarx != NULL) && ((tmppreviousstate == I2C_STATE_MASTER_BUSY_RX) || \
6952                                       (tmppreviousstate == I2C_STATE_SLAVE_BUSY_RX)))
6953   {
6954     if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN)
6955     {
6956       hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
6957     }
6958 
6959     if (HAL_DMA_GetState(hi2c->hdmarx) != HAL_DMA_STATE_READY)
6960     {
6961       /* Set the I2C DMA Abort callback :
6962         will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
6963       hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort;
6964 
6965       /* Process Unlocked */
6966       __HAL_UNLOCK(hi2c);
6967 
6968       /* Abort DMA RX */
6969       if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK)
6970       {
6971         /* Call Directly hi2c->hdmarx->XferAbortCallback function in case of error */
6972         hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx);
6973       }
6974     }
6975     else
6976     {
6977       I2C_TreatErrorCallback(hi2c);
6978     }
6979   }
6980   else
6981 #endif /* HAL_DMA_MODULE_ENABLED */
6982   {
6983     I2C_TreatErrorCallback(hi2c);
6984   }
6985 }
6986 
6987 /**
6988   * @brief  I2C Error callback treatment.
6989   * @param  hi2c I2C handle.
6990   * @retval None
6991   */
I2C_TreatErrorCallback(I2C_HandleTypeDef * hi2c)6992 static void I2C_TreatErrorCallback(I2C_HandleTypeDef *hi2c)
6993 {
6994   if (hi2c->State == HAL_I2C_STATE_ABORT)
6995   {
6996     hi2c->State = HAL_I2C_STATE_READY;
6997     hi2c->PreviousState = I2C_STATE_NONE;
6998 
6999     /* Process Unlocked */
7000     __HAL_UNLOCK(hi2c);
7001 
7002     /* Call the corresponding callback to inform upper layer of End of Transfer */
7003 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
7004     hi2c->AbortCpltCallback(hi2c);
7005 #else
7006     HAL_I2C_AbortCpltCallback(hi2c);
7007 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
7008   }
7009   else
7010   {
7011     hi2c->PreviousState = I2C_STATE_NONE;
7012 
7013     /* Process Unlocked */
7014     __HAL_UNLOCK(hi2c);
7015 
7016     /* Call the corresponding callback to inform upper layer of End of Transfer */
7017 #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
7018     hi2c->ErrorCallback(hi2c);
7019 #else
7020     HAL_I2C_ErrorCallback(hi2c);
7021 #endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
7022   }
7023 }
7024 
7025 /**
7026   * @brief  I2C Tx data register flush process.
7027   * @param  hi2c I2C handle.
7028   * @retval None
7029   */
I2C_Flush_TXDR(I2C_HandleTypeDef * hi2c)7030 static void I2C_Flush_TXDR(I2C_HandleTypeDef *hi2c)
7031 {
7032   /* If a pending TXIS flag is set */
7033   /* Write a dummy data in TXDR to clear it */
7034   if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) != RESET)
7035   {
7036     hi2c->Instance->TXDR = 0x00U;
7037   }
7038 
7039   /* Flush TX register if not empty */
7040   if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE) == RESET)
7041   {
7042     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_TXE);
7043   }
7044 }
7045 
7046 #if defined(HAL_DMA_MODULE_ENABLED)
7047 /**
7048   * @brief  DMA I2C master transmit process complete callback.
7049   * @param  hdma DMA handle
7050   * @retval None
7051   */
I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef * hdma)7052 static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma)
7053 {
7054   HAL_StatusTypeDef dmaxferstatus = HAL_OK;
7055   /* Derogation MISRAC2012-Rule-11.5 */
7056   I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
7057 
7058   /* Disable DMA Request */
7059   hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
7060 
7061   /* If last transfer, enable STOP interrupt */
7062   if (hi2c->XferCount == 0U)
7063   {
7064     /* Enable STOP interrupt */
7065     I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT);
7066   }
7067   /* else prepare a new DMA transfer and enable TCReload interrupt */
7068   else
7069   {
7070     /* Update Buffer pointer */
7071     hi2c->pBuffPtr += hi2c->XferSize;
7072 
7073     /* Set the XferSize to transfer */
7074     if (hi2c->XferCount > MAX_NBYTE_SIZE)
7075     {
7076       hi2c->XferSize = MAX_NBYTE_SIZE;
7077     }
7078     else
7079     {
7080       hi2c->XferSize = hi2c->XferCount;
7081     }
7082 
7083     /* Enable the DMA channel */
7084     if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
7085     {
7086       if (hi2c->hdmatx->LinkedListQueue != NULL)
7087       {
7088         /* Set DMA data size */
7089         hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
7090 
7091         /* Set DMA source address */
7092         hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2c->pBuffPtr;
7093 
7094         /* Set DMA destination address */
7095         hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hi2c->Instance->TXDR;
7096 
7097         dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx);
7098       }
7099       else
7100       {
7101         /* Call the corresponding callback to inform upper layer of End of Transfer */
7102         I2C_ITError(hi2c, HAL_I2C_ERROR_DMA);
7103       }
7104     }
7105     else
7106     {
7107       dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR,
7108                                        hi2c->XferSize);
7109     }
7110 
7111     if (dmaxferstatus != HAL_OK)
7112     {
7113       /* Call the corresponding callback to inform upper layer of End of Transfer */
7114       I2C_ITError(hi2c, HAL_I2C_ERROR_DMA);
7115     }
7116     else
7117     {
7118       /* Enable TC interrupts */
7119       I2C_Enable_IRQ(hi2c, I2C_XFER_RELOAD_IT);
7120     }
7121   }
7122 }
7123 
7124 
7125 /**
7126   * @brief  DMA I2C slave transmit process complete callback.
7127   * @param  hdma DMA handle
7128   * @retval None
7129   */
I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef * hdma)7130 static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma)
7131 {
7132   /* Derogation MISRAC2012-Rule-11.5 */
7133   I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
7134   uint32_t tmpoptions = hi2c->XferOptions;
7135 
7136   if ((tmpoptions == I2C_NEXT_FRAME) || (tmpoptions == I2C_FIRST_FRAME))
7137   {
7138     /* Disable DMA Request */
7139     hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
7140 
7141     /* Last Byte is Transmitted */
7142     /* Call I2C Slave Sequential complete process */
7143     I2C_ITSlaveSeqCplt(hi2c);
7144   }
7145   else
7146   {
7147     /* No specific action, Master fully manage the generation of STOP condition */
7148     /* Mean that this generation can arrive at any time, at the end or during DMA process */
7149     /* So STOP condition should be manage through Interrupt treatment */
7150   }
7151 }
7152 
7153 
7154 /**
7155   * @brief DMA I2C master receive process complete callback.
7156   * @param  hdma DMA handle
7157   * @retval None
7158   */
I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef * hdma)7159 static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma)
7160 {
7161   HAL_StatusTypeDef dmaxferstatus = HAL_OK;
7162   /* Derogation MISRAC2012-Rule-11.5 */
7163   I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
7164 
7165   /* Disable DMA Request */
7166   hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
7167 
7168   /* If last transfer, enable STOP interrupt */
7169   if (hi2c->XferCount == 0U)
7170   {
7171     /* Enable STOP interrupt */
7172     I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT);
7173   }
7174   /* else prepare a new DMA transfer and enable TCReload interrupt */
7175   else
7176   {
7177     /* Update Buffer pointer */
7178     hi2c->pBuffPtr += hi2c->XferSize;
7179 
7180     /* Set the XferSize to transfer */
7181     if (hi2c->XferCount > MAX_NBYTE_SIZE)
7182     {
7183       hi2c->XferSize = MAX_NBYTE_SIZE;
7184     }
7185     else
7186     {
7187       hi2c->XferSize = hi2c->XferCount;
7188     }
7189 
7190     /* Enable the DMA channel */
7191     if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
7192     {
7193       if (hi2c->hdmarx->LinkedListQueue != NULL)
7194       {
7195         /* Set DMA data size */
7196         hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize;
7197 
7198         /* Set DMA source address */
7199         hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hi2c->Instance->RXDR;
7200 
7201         /* Set DMA destination address */
7202         hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hi2c->pBuffPtr;
7203 
7204         dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx);
7205       }
7206       else
7207       {
7208         /* Call the corresponding callback to inform upper layer of End of Transfer */
7209         I2C_ITError(hi2c, HAL_I2C_ERROR_DMA);
7210       }
7211     }
7212     else
7213     {
7214       dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)hi2c->pBuffPtr,
7215                                        hi2c->XferSize);
7216     }
7217 
7218     if (dmaxferstatus != HAL_OK)
7219     {
7220       /* Call the corresponding callback to inform upper layer of End of Transfer */
7221       I2C_ITError(hi2c, HAL_I2C_ERROR_DMA);
7222     }
7223     else
7224     {
7225       /* Enable TC interrupts */
7226       I2C_Enable_IRQ(hi2c, I2C_XFER_RELOAD_IT);
7227     }
7228   }
7229 }
7230 
7231 
7232 /**
7233   * @brief  DMA I2C slave receive process complete callback.
7234   * @param  hdma DMA handle
7235   * @retval None
7236   */
I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef * hdma)7237 static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma)
7238 {
7239   /* Derogation MISRAC2012-Rule-11.5 */
7240   I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
7241   uint32_t tmpoptions = hi2c->XferOptions;
7242 
7243   if ((I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx) == 0U) && \
7244       (tmpoptions != I2C_NO_OPTION_FRAME))
7245   {
7246     /* Disable DMA Request */
7247     hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
7248 
7249     /* Call I2C Slave Sequential complete process */
7250     I2C_ITSlaveSeqCplt(hi2c);
7251   }
7252   else
7253   {
7254     /* No specific action, Master fully manage the generation of STOP condition */
7255     /* Mean that this generation can arrive at any time, at the end or during DMA process */
7256     /* So STOP condition should be manage through Interrupt treatment */
7257   }
7258 }
7259 
7260 
7261 /**
7262   * @brief  DMA I2C communication error callback.
7263   * @param hdma DMA handle
7264   * @retval None
7265   */
I2C_DMAError(DMA_HandleTypeDef * hdma)7266 static void I2C_DMAError(DMA_HandleTypeDef *hdma)
7267 {
7268   /* Derogation MISRAC2012-Rule-11.5 */
7269   I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
7270 
7271   /* Disable Acknowledge */
7272   hi2c->Instance->CR2 |= I2C_CR2_NACK;
7273 
7274   /* Call the corresponding callback to inform upper layer of End of Transfer */
7275   I2C_ITError(hi2c, HAL_I2C_ERROR_DMA);
7276 }
7277 
7278 
7279 /**
7280   * @brief DMA I2C communication abort callback
7281   *        (To be called at end of DMA Abort procedure).
7282   * @param hdma DMA handle.
7283   * @retval None
7284   */
I2C_DMAAbort(DMA_HandleTypeDef * hdma)7285 static void I2C_DMAAbort(DMA_HandleTypeDef *hdma)
7286 {
7287   /* Derogation MISRAC2012-Rule-11.5 */
7288   I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
7289 
7290   /* Reset AbortCpltCallback */
7291   if (hi2c->hdmatx != NULL)
7292   {
7293     hi2c->hdmatx->XferAbortCallback = NULL;
7294   }
7295   if (hi2c->hdmarx != NULL)
7296   {
7297     hi2c->hdmarx->XferAbortCallback = NULL;
7298   }
7299 
7300   I2C_TreatErrorCallback(hi2c);
7301 }
7302 
7303 #endif /* HAL_DMA_MODULE_ENABLED */
7304 
7305 /**
7306   * @brief  This function handles I2C Communication Timeout. It waits
7307   *                until a flag is no longer in the specified status.
7308   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
7309   *                the configuration information for the specified I2C.
7310   * @param  Flag Specifies the I2C flag to check.
7311   * @param  Status The actual Flag status (SET or RESET).
7312   * @param  Timeout Timeout duration
7313   * @param  Tickstart Tick start value
7314   * @retval HAL status
7315   */
I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef * hi2c,uint32_t Flag,FlagStatus Status,uint32_t Timeout,uint32_t Tickstart)7316 static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status,
7317                                                     uint32_t Timeout, uint32_t Tickstart)
7318 {
7319   while (__HAL_I2C_GET_FLAG(hi2c, Flag) == Status)
7320   {
7321     /* Check if an error is detected */
7322     if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK)
7323     {
7324       return HAL_ERROR;
7325     }
7326 
7327     /* Check for the Timeout */
7328     if (Timeout != HAL_MAX_DELAY)
7329     {
7330       if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U))
7331       {
7332         if ((__HAL_I2C_GET_FLAG(hi2c, Flag) == Status))
7333         {
7334           hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
7335           hi2c->State = HAL_I2C_STATE_READY;
7336           hi2c->Mode = HAL_I2C_MODE_NONE;
7337 
7338           /* Process Unlocked */
7339           __HAL_UNLOCK(hi2c);
7340           return HAL_ERROR;
7341         }
7342       }
7343     }
7344   }
7345   return HAL_OK;
7346 }
7347 
7348 /**
7349   * @brief  This function handles I2C Communication Timeout for specific usage of TXIS flag.
7350   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
7351   *                the configuration information for the specified I2C.
7352   * @param  Timeout Timeout duration
7353   * @param  Tickstart Tick start value
7354   * @retval HAL status
7355   */
I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef * hi2c,uint32_t Timeout,uint32_t Tickstart)7356 static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
7357                                                         uint32_t Tickstart)
7358 {
7359   while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == RESET)
7360   {
7361     /* Check if an error is detected */
7362     if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK)
7363     {
7364       return HAL_ERROR;
7365     }
7366 
7367     /* Check for the Timeout */
7368     if (Timeout != HAL_MAX_DELAY)
7369     {
7370       if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U))
7371       {
7372         if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == RESET))
7373         {
7374           hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
7375           hi2c->State = HAL_I2C_STATE_READY;
7376           hi2c->Mode = HAL_I2C_MODE_NONE;
7377 
7378           /* Process Unlocked */
7379           __HAL_UNLOCK(hi2c);
7380 
7381           return HAL_ERROR;
7382         }
7383       }
7384     }
7385   }
7386   return HAL_OK;
7387 }
7388 
7389 /**
7390   * @brief  This function handles I2C Communication Timeout for specific usage of STOP flag.
7391   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
7392   *                the configuration information for the specified I2C.
7393   * @param  Timeout Timeout duration
7394   * @param  Tickstart Tick start value
7395   * @retval HAL status
7396   */
I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef * hi2c,uint32_t Timeout,uint32_t Tickstart)7397 static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
7398                                                         uint32_t Tickstart)
7399 {
7400   while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET)
7401   {
7402     /* Check if an error is detected */
7403     if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK)
7404     {
7405       return HAL_ERROR;
7406     }
7407 
7408     /* Check for the Timeout */
7409     if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U))
7410     {
7411       if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET))
7412       {
7413         hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
7414         hi2c->State = HAL_I2C_STATE_READY;
7415         hi2c->Mode = HAL_I2C_MODE_NONE;
7416 
7417         /* Process Unlocked */
7418         __HAL_UNLOCK(hi2c);
7419 
7420         return HAL_ERROR;
7421       }
7422     }
7423   }
7424   return HAL_OK;
7425 }
7426 
7427 /**
7428   * @brief  This function handles I2C Communication Timeout for specific usage of RXNE flag.
7429   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
7430   *                the configuration information for the specified I2C.
7431   * @param  Timeout Timeout duration
7432   * @param  Tickstart Tick start value
7433   * @retval HAL status
7434   */
I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef * hi2c,uint32_t Timeout,uint32_t Tickstart)7435 static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
7436                                                         uint32_t Tickstart)
7437 {
7438   HAL_StatusTypeDef status = HAL_OK;
7439 
7440   while ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET) && (status == HAL_OK))
7441   {
7442     /* Check if an error is detected */
7443     if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK)
7444     {
7445       status = HAL_ERROR;
7446     }
7447 
7448     /* Check if a STOPF is detected */
7449     if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) && (status == HAL_OK))
7450     {
7451       /* Check if an RXNE is pending */
7452       /* Store Last receive data if any */
7453       if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) && (hi2c->XferSize > 0U))
7454       {
7455         /* Return HAL_OK */
7456         /* The Reading of data from RXDR will be done in caller function */
7457         status = HAL_OK;
7458       }
7459 
7460       /* Check a no-acknowledge have been detected */
7461       if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET)
7462       {
7463         __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
7464         hi2c->ErrorCode = HAL_I2C_ERROR_AF;
7465 
7466         /* Clear STOP Flag */
7467         __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
7468 
7469         /* Clear Configuration Register 2 */
7470         I2C_RESET_CR2(hi2c);
7471 
7472         hi2c->State = HAL_I2C_STATE_READY;
7473         hi2c->Mode = HAL_I2C_MODE_NONE;
7474 
7475         /* Process Unlocked */
7476         __HAL_UNLOCK(hi2c);
7477 
7478         status = HAL_ERROR;
7479       }
7480       else
7481       {
7482         hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
7483       }
7484     }
7485 
7486     /* Check for the Timeout */
7487     if ((((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) && (status == HAL_OK))
7488     {
7489       if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET))
7490       {
7491         hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
7492         hi2c->State = HAL_I2C_STATE_READY;
7493 
7494         /* Process Unlocked */
7495         __HAL_UNLOCK(hi2c);
7496 
7497         status = HAL_ERROR;
7498       }
7499     }
7500   }
7501   return status;
7502 }
7503 
7504 /**
7505   * @brief  This function handles errors detection during an I2C Communication.
7506   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
7507   *                the configuration information for the specified I2C.
7508   * @param  Timeout Timeout duration
7509   * @param  Tickstart Tick start value
7510   * @retval HAL status
7511   */
I2C_IsErrorOccurred(I2C_HandleTypeDef * hi2c,uint32_t Timeout,uint32_t Tickstart)7512 static HAL_StatusTypeDef I2C_IsErrorOccurred(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart)
7513 {
7514   HAL_StatusTypeDef status = HAL_OK;
7515   uint32_t itflag   = hi2c->Instance->ISR;
7516   uint32_t error_code = 0;
7517   uint32_t tickstart = Tickstart;
7518   uint32_t tmp1;
7519   HAL_I2C_ModeTypeDef tmp2;
7520 
7521   if (HAL_IS_BIT_SET(itflag, I2C_FLAG_AF))
7522   {
7523     /* Clear NACKF Flag */
7524     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
7525 
7526     /* Wait until STOP Flag is set or timeout occurred */
7527     /* AutoEnd should be initiate after AF */
7528     while ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) && (status == HAL_OK))
7529     {
7530       /* Check for the Timeout */
7531       if (Timeout != HAL_MAX_DELAY)
7532       {
7533         if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
7534         {
7535           tmp1 = (uint32_t)(hi2c->Instance->CR2 & I2C_CR2_STOP);
7536           tmp2 = hi2c->Mode;
7537 
7538           /* In case of I2C still busy, try to regenerate a STOP manually */
7539           if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && \
7540               (tmp1 != I2C_CR2_STOP) && \
7541               (tmp2 != HAL_I2C_MODE_SLAVE))
7542           {
7543             /* Generate Stop */
7544             hi2c->Instance->CR2 |= I2C_CR2_STOP;
7545 
7546             /* Update Tick with new reference */
7547             tickstart = HAL_GetTick();
7548           }
7549 
7550           while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET)
7551           {
7552             /* Check for the Timeout */
7553             if ((HAL_GetTick() - tickstart) > I2C_TIMEOUT_STOPF)
7554             {
7555               error_code |= HAL_I2C_ERROR_TIMEOUT;
7556 
7557               status = HAL_ERROR;
7558 
7559               break;
7560             }
7561           }
7562         }
7563       }
7564     }
7565 
7566     /* In case STOP Flag is detected, clear it */
7567     if (status == HAL_OK)
7568     {
7569       /* Clear STOP Flag */
7570       __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
7571     }
7572 
7573     error_code |= HAL_I2C_ERROR_AF;
7574 
7575     status = HAL_ERROR;
7576   }
7577 
7578   /* Refresh Content of Status register */
7579   itflag = hi2c->Instance->ISR;
7580 
7581   /* Then verify if an additional errors occurs */
7582   /* Check if a Bus error occurred */
7583   if (HAL_IS_BIT_SET(itflag, I2C_FLAG_BERR))
7584   {
7585     error_code |= HAL_I2C_ERROR_BERR;
7586 
7587     /* Clear BERR flag */
7588     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR);
7589 
7590     status = HAL_ERROR;
7591   }
7592 
7593   /* Check if an Over-Run/Under-Run error occurred */
7594   if (HAL_IS_BIT_SET(itflag, I2C_FLAG_OVR))
7595   {
7596     error_code |= HAL_I2C_ERROR_OVR;
7597 
7598     /* Clear OVR flag */
7599     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR);
7600 
7601     status = HAL_ERROR;
7602   }
7603 
7604   /* Check if an Arbitration Loss error occurred */
7605   if (HAL_IS_BIT_SET(itflag, I2C_FLAG_ARLO))
7606   {
7607     error_code |= HAL_I2C_ERROR_ARLO;
7608 
7609     /* Clear ARLO flag */
7610     __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO);
7611 
7612     status = HAL_ERROR;
7613   }
7614 
7615   if (status != HAL_OK)
7616   {
7617     /* Flush TX register */
7618     I2C_Flush_TXDR(hi2c);
7619 
7620     /* Clear Configuration Register 2 */
7621     I2C_RESET_CR2(hi2c);
7622 
7623     hi2c->ErrorCode |= error_code;
7624     hi2c->State = HAL_I2C_STATE_READY;
7625     hi2c->Mode = HAL_I2C_MODE_NONE;
7626 
7627     /* Process Unlocked */
7628     __HAL_UNLOCK(hi2c);
7629   }
7630 
7631   return status;
7632 }
7633 
7634 /**
7635   * @brief  Handles I2Cx communication when starting transfer or during transfer (TC or TCR flag are set).
7636   * @param  hi2c I2C handle.
7637   * @param  DevAddress Specifies the slave address to be programmed.
7638   * @param  Size Specifies the number of bytes to be programmed.
7639   *   This parameter must be a value between 0 and 255.
7640   * @param  Mode New state of the I2C START condition generation.
7641   *   This parameter can be one of the following values:
7642   *     @arg @ref I2C_RELOAD_MODE Enable Reload mode .
7643   *     @arg @ref I2C_AUTOEND_MODE Enable Automatic end mode.
7644   *     @arg @ref I2C_SOFTEND_MODE Enable Software end mode.
7645   * @param  Request New state of the I2C START condition generation.
7646   *   This parameter can be one of the following values:
7647   *     @arg @ref I2C_NO_STARTSTOP Don't Generate stop and start condition.
7648   *     @arg @ref I2C_GENERATE_STOP Generate stop condition (Size should be set to 0).
7649   *     @arg @ref I2C_GENERATE_START_READ Generate Restart for read request.
7650   *     @arg @ref I2C_GENERATE_START_WRITE Generate Restart for write request.
7651   * @retval None
7652   */
I2C_TransferConfig(I2C_HandleTypeDef * hi2c,uint16_t DevAddress,uint8_t Size,uint32_t Mode,uint32_t Request)7653 static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode,
7654                                uint32_t Request)
7655 {
7656   uint32_t tmp;
7657 
7658   /* Check the parameters */
7659   assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
7660   assert_param(IS_TRANSFER_MODE(Mode));
7661   assert_param(IS_TRANSFER_REQUEST(Request));
7662 
7663   /* Declaration of tmp to prevent undefined behavior of volatile usage */
7664   tmp = ((uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | \
7665                     (((uint32_t)Size << I2C_CR2_NBYTES_Pos) & I2C_CR2_NBYTES) | \
7666                     (uint32_t)Mode | (uint32_t)Request) & (~0x80000000U));
7667 
7668   /* update CR2 register */
7669   MODIFY_REG(hi2c->Instance->CR2, \
7670              ((I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | \
7671                (I2C_CR2_RD_WRN & (uint32_t)(Request >> (31U - I2C_CR2_RD_WRN_Pos))) | \
7672                I2C_CR2_START | I2C_CR2_STOP)), tmp);
7673 }
7674 
7675 /**
7676   * @brief  Manage the enabling of Interrupts.
7677   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
7678   *                the configuration information for the specified I2C.
7679   * @param  InterruptRequest Value of @ref I2C_Interrupt_configuration_definition.
7680   * @retval None
7681   */
I2C_Enable_IRQ(I2C_HandleTypeDef * hi2c,uint16_t InterruptRequest)7682 static void I2C_Enable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest)
7683 {
7684   uint32_t tmpisr = 0U;
7685 
7686 #if defined(HAL_DMA_MODULE_ENABLED)
7687   if ((hi2c->XferISR != I2C_Master_ISR_DMA) && \
7688       (hi2c->XferISR != I2C_Slave_ISR_DMA) && \
7689       (hi2c->XferISR != I2C_Mem_ISR_DMA))
7690 #endif /* HAL_DMA_MODULE_ENABLED */
7691   {
7692     if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT)
7693     {
7694       /* Enable ERR, STOP, NACK and ADDR interrupts */
7695       tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
7696     }
7697 
7698     if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT)
7699     {
7700       /* Enable ERR, TC, STOP, NACK and TXI interrupts */
7701       tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_TXI;
7702     }
7703 
7704     if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT)
7705     {
7706       /* Enable ERR, TC, STOP, NACK and RXI interrupts */
7707       tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_RXI;
7708     }
7709 
7710     if (InterruptRequest == I2C_XFER_ERROR_IT)
7711     {
7712       /* Enable ERR and NACK interrupts */
7713       tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI;
7714     }
7715 
7716     if (InterruptRequest == I2C_XFER_CPLT_IT)
7717     {
7718       /* Enable STOP interrupts */
7719       tmpisr |= I2C_IT_STOPI;
7720     }
7721   }
7722 
7723 #if defined(HAL_DMA_MODULE_ENABLED)
7724   else
7725   {
7726     if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT)
7727     {
7728       /* Enable ERR, STOP, NACK and ADDR interrupts */
7729       tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
7730     }
7731 
7732     if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT)
7733     {
7734       /* Enable ERR, TC, STOP, NACK and TXI interrupts */
7735       tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_TXI;
7736     }
7737 
7738     if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT)
7739     {
7740       /* Enable ERR, TC, STOP, NACK and RXI interrupts */
7741       tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_RXI;
7742     }
7743 
7744     if (InterruptRequest == I2C_XFER_ERROR_IT)
7745     {
7746       /* Enable ERR and NACK interrupts */
7747       tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI;
7748     }
7749 
7750     if (InterruptRequest == I2C_XFER_CPLT_IT)
7751     {
7752       /* Enable STOP interrupts */
7753       tmpisr |= (I2C_IT_STOPI | I2C_IT_TCI);
7754     }
7755 
7756     if (InterruptRequest == I2C_XFER_RELOAD_IT)
7757     {
7758       /* Enable TC interrupts */
7759       tmpisr |= I2C_IT_TCI;
7760     }
7761   }
7762 #endif /* HAL_DMA_MODULE_ENABLED */
7763 
7764   /* Enable interrupts only at the end */
7765   /* to avoid the risk of I2C interrupt handle execution before */
7766   /* all interrupts requested done */
7767   __HAL_I2C_ENABLE_IT(hi2c, tmpisr);
7768 }
7769 
7770 /**
7771   * @brief  Manage the disabling of Interrupts.
7772   * @param  hi2c Pointer to a I2C_HandleTypeDef structure that contains
7773   *                the configuration information for the specified I2C.
7774   * @param  InterruptRequest Value of @ref I2C_Interrupt_configuration_definition.
7775   * @retval None
7776   */
I2C_Disable_IRQ(I2C_HandleTypeDef * hi2c,uint16_t InterruptRequest)7777 static void I2C_Disable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest)
7778 {
7779   uint32_t tmpisr = 0U;
7780 
7781   if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT)
7782   {
7783     /* Disable TC and TXI interrupts */
7784     tmpisr |= I2C_IT_TCI | I2C_IT_TXI;
7785 
7786     if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) != (uint32_t)HAL_I2C_STATE_LISTEN)
7787     {
7788       /* Disable NACK and STOP interrupts */
7789       tmpisr |= I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
7790     }
7791   }
7792 
7793   if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT)
7794   {
7795     /* Disable TC and RXI interrupts */
7796     tmpisr |= I2C_IT_TCI | I2C_IT_RXI;
7797 
7798     if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) != (uint32_t)HAL_I2C_STATE_LISTEN)
7799     {
7800       /* Disable NACK and STOP interrupts */
7801       tmpisr |= I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
7802     }
7803   }
7804 
7805   if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT)
7806   {
7807     /* Disable ADDR, NACK and STOP interrupts */
7808     tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
7809   }
7810 
7811   if (InterruptRequest == I2C_XFER_ERROR_IT)
7812   {
7813     /* Enable ERR and NACK interrupts */
7814     tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI;
7815   }
7816 
7817   if (InterruptRequest == I2C_XFER_CPLT_IT)
7818   {
7819     /* Enable STOP interrupts */
7820     tmpisr |= I2C_IT_STOPI;
7821   }
7822 
7823   if (InterruptRequest == I2C_XFER_RELOAD_IT)
7824   {
7825     /* Enable TC interrupts */
7826     tmpisr |= I2C_IT_TCI;
7827   }
7828 
7829   /* Disable interrupts only at the end */
7830   /* to avoid a breaking situation like at "t" time */
7831   /* all disable interrupts request are not done */
7832   __HAL_I2C_DISABLE_IT(hi2c, tmpisr);
7833 }
7834 
7835 /**
7836   * @brief  Convert I2Cx OTHER_xxx XferOptions to functional XferOptions.
7837   * @param  hi2c I2C handle.
7838   * @retval None
7839   */
I2C_ConvertOtherXferOptions(I2C_HandleTypeDef * hi2c)7840 static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c)
7841 {
7842   /* if user set XferOptions to I2C_OTHER_FRAME            */
7843   /* it request implicitly to generate a restart condition */
7844   /* set XferOptions to I2C_FIRST_FRAME                    */
7845   if (hi2c->XferOptions == I2C_OTHER_FRAME)
7846   {
7847     hi2c->XferOptions = I2C_FIRST_FRAME;
7848   }
7849   /* else if user set XferOptions to I2C_OTHER_AND_LAST_FRAME */
7850   /* it request implicitly to generate a restart condition    */
7851   /* then generate a stop condition at the end of transfer    */
7852   /* set XferOptions to I2C_FIRST_AND_LAST_FRAME              */
7853   else if (hi2c->XferOptions == I2C_OTHER_AND_LAST_FRAME)
7854   {
7855     hi2c->XferOptions = I2C_FIRST_AND_LAST_FRAME;
7856   }
7857   else
7858   {
7859     /* Nothing to do */
7860   }
7861 }
7862 
7863 /**
7864   * @}
7865   */
7866 
7867 #endif /* HAL_I2C_MODULE_ENABLED */
7868 /**
7869   * @}
7870   */
7871 
7872 /**
7873   * @}
7874   */
7875