1  /**
2    ******************************************************************************
3    * @file    stm32f4xx_i2c.c
4    * @author  MCD Application Team
5    * @version V1.5.1
6    * @date    22-May-2015
7    * @brief   This file provides firmware functions to manage the following
8    *          functionalities of the Inter-integrated circuit (I2C)
9    *           + Initialization and Configuration
10    *           + Data transfers
11    *           + PEC management
12    *           + DMA transfers management
13    *           + Interrupts, events and flags management
14    *
15      @verbatim
16   ===============================================================================
17                      ##### How to use this driver #####
18   ===============================================================================
19      [..]
20        (#) Enable peripheral clock using RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2Cx, ENABLE)
21            function for I2C1, I2C2 or I2C3.
22  
23        (#) Enable SDA, SCL  and SMBA (when used) GPIO clocks using
24            RCC_AHBPeriphClockCmd() function.
25  
26        (#) Peripherals alternate function:
27          (++) Connect the pin to the desired peripherals' Alternate
28               Function (AF) using GPIO_PinAFConfig() function
29          (++) Configure the desired pin in alternate function by:
30               GPIO_InitStruct->GPIO_Mode = GPIO_Mode_AF
31          (++) Select the type, pull-up/pull-down and output speed via
32               GPIO_PuPd, GPIO_OType and GPIO_Speed members
33          (++) Call GPIO_Init() function
34               Recommended configuration is Push-Pull, Pull-up, Open-Drain.
35               Add an external pull up if necessary (typically 4.7 KOhm).
36  
37        (#) Program the Mode, duty cycle , Own address, Ack, Speed and Acknowledged
38            Address using the I2C_Init() function.
39  
40        (#) Optionally you can enable/configure the following parameters without
41            re-initialization (i.e there is no need to call again I2C_Init() function):
42          (++) Enable the acknowledge feature using I2C_AcknowledgeConfig() function
43          (++) Enable the dual addressing mode using I2C_DualAddressCmd() function
44          (++) Enable the general call using the I2C_GeneralCallCmd() function
45          (++) Enable the clock stretching using I2C_StretchClockCmd() function
46          (++) Enable the fast mode duty cycle using the I2C_FastModeDutyCycleConfig()
47               function.
48          (++) Configure the NACK position for Master Receiver mode in case of
49               2 bytes reception using the function I2C_NACKPositionConfig().
50          (++) Enable the PEC Calculation using I2C_CalculatePEC() function
51          (++) For SMBus Mode:
52            (+++) Enable the Address Resolution Protocol (ARP) using I2C_ARPCmd() function
53            (+++) Configure the SMBusAlert pin using I2C_SMBusAlertConfig() function
54  
55        (#) Enable the NVIC and the corresponding interrupt using the function
56            I2C_ITConfig() if you need to use interrupt mode.
57  
58        (#) When using the DMA mode
59          (++) Configure the DMA using DMA_Init() function
60          (++) Active the needed channel Request using I2C_DMACmd() or
61               I2C_DMALastTransferCmd() function.
62          -@@- When using DMA mode, I2C interrupts may be used at the same time to
63               control the communication flow (Start/Stop/Ack... events and errors).
64  
65        (#) Enable the I2C using the I2C_Cmd() function.
66  
67        (#) Enable the DMA using the DMA_Cmd() function when using DMA mode in the
68            transfers.
69  
70      @endverbatim
71    ******************************************************************************
72    * @attention
73    *
74    * <h2><center>&copy; COPYRIGHT 2015 STMicroelectronics</center></h2>
75    *
76    * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
77    * You may not use this file except in compliance with the License.
78    * You may obtain a copy of the License at:
79    *
80    *        http://www.st.com/software_license_agreement_liberty_v2
81    *
82    * Unless required by applicable law or agreed to in writing, software
83    * distributed under the License is distributed on an "AS IS" BASIS,
84    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
85    * See the License for the specific language governing permissions and
86    * limitations under the License.
87    *
88    ******************************************************************************
89    */
90  
91  /* Includes ------------------------------------------------------------------*/
92  #include "stm32f4xx_i2c.h"
93  #include "stm32f4xx_rcc.h"
94  
95  /** @addtogroup STM32F4xx_StdPeriph_Driver
96    * @{
97    */
98  
99  /** @defgroup I2C
100    * @brief I2C driver modules
101    * @{
102    */
103  
104  /* Private typedef -----------------------------------------------------------*/
105  /* Private define ------------------------------------------------------------*/
106  
107  #define CR1_CLEAR_MASK    ((uint16_t)0xFBF5)      /*<! I2C registers Masks */
108  #define FLAG_MASK         ((uint32_t)0x00FFFFFF)  /*<! I2C FLAG mask */
109  #define ITEN_MASK         ((uint32_t)0x07000000)  /*<! I2C Interrupt Enable mask */
110  
111  /* Private macro -------------------------------------------------------------*/
112  /* Private variables ---------------------------------------------------------*/
113  /* Private function prototypes -----------------------------------------------*/
114  /* Private functions ---------------------------------------------------------*/
115  
116  /** @defgroup I2C_Private_Functions
117    * @{
118    */
119  
120  /** @defgroup I2C_Group1 Initialization and Configuration functions
121   *  @brief   Initialization and Configuration functions
122   *
123  @verbatim
124   ===============================================================================
125              ##### Initialization and Configuration functions #####
126   ===============================================================================
127  
128  @endverbatim
129    * @{
130    */
131  
132  /**
133    * @brief  Deinitialize the I2Cx peripheral registers to their default reset values.
134    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
135    * @retval None
136    */
I2C_DeInit(I2C_TypeDef * I2Cx)137  void I2C_DeInit(I2C_TypeDef* I2Cx)
138  {
139    /* Check the parameters */
140    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
141  
142    if (I2Cx == I2C1)
143    {
144      /* Enable I2C1 reset state */
145      RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C1, ENABLE);
146      /* Release I2C1 from reset state */
147      RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C1, DISABLE);
148    }
149    else if (I2Cx == I2C2)
150    {
151      /* Enable I2C2 reset state */
152      RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C2, ENABLE);
153      /* Release I2C2 from reset state */
154      RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C2, DISABLE);
155    }
156    else
157    {
158      if (I2Cx == I2C3)
159      {
160        /* Enable I2C3 reset state */
161        RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C3, ENABLE);
162        /* Release I2C3 from reset state */
163        RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C3, DISABLE);
164      }
165    }
166  }
167  
168  /**
169    * @brief  Initializes the I2Cx peripheral according to the specified
170    *         parameters in the I2C_InitStruct.
171    *
172    * @note   To use the I2C at 400 KHz (in fast mode), the PCLK1 frequency
173    *         (I2C peripheral input clock) must be a multiple of 10 MHz.
174    *
175    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
176    * @param  I2C_InitStruct: pointer to a I2C_InitTypeDef structure that contains
177    *         the configuration information for the specified I2C peripheral.
178    * @retval None
179    */
I2C_Init(I2C_TypeDef * I2Cx,I2C_InitTypeDef * I2C_InitStruct)180  void I2C_Init(I2C_TypeDef* I2Cx, I2C_InitTypeDef* I2C_InitStruct)
181  {
182    uint16_t tmpreg = 0, freqrange = 0;
183    uint16_t result = 0x04;
184    uint32_t pclk1 = 8000000;
185    RCC_ClocksTypeDef  rcc_clocks;
186    /* Check the parameters */
187    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
188    assert_param(IS_I2C_CLOCK_SPEED(I2C_InitStruct->I2C_ClockSpeed));
189    assert_param(IS_I2C_MODE(I2C_InitStruct->I2C_Mode));
190    assert_param(IS_I2C_DUTY_CYCLE(I2C_InitStruct->I2C_DutyCycle));
191    assert_param(IS_I2C_OWN_ADDRESS1(I2C_InitStruct->I2C_OwnAddress1));
192    assert_param(IS_I2C_ACK_STATE(I2C_InitStruct->I2C_Ack));
193    assert_param(IS_I2C_ACKNOWLEDGE_ADDRESS(I2C_InitStruct->I2C_AcknowledgedAddress));
194  
195  /*---------------------------- I2Cx CR2 Configuration ------------------------*/
196    /* Get the I2Cx CR2 value */
197    tmpreg = I2Cx->CR2;
198    /* Clear frequency FREQ[5:0] bits */
199    tmpreg &= (uint16_t)~((uint16_t)I2C_CR2_FREQ);
200    /* Get pclk1 frequency value */
201    RCC_GetClocksFreq(&rcc_clocks);
202    pclk1 = rcc_clocks.PCLK1_Frequency;
203    /* Set frequency bits depending on pclk1 value */
204    freqrange = (uint16_t)(pclk1 / 1000000);
205    tmpreg |= freqrange;
206    /* Write to I2Cx CR2 */
207    I2Cx->CR2 = tmpreg;
208  
209  /*---------------------------- I2Cx CCR Configuration ------------------------*/
210    /* Disable the selected I2C peripheral to configure TRISE */
211    I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_PE);
212    /* Reset tmpreg value */
213    /* Clear F/S, DUTY and CCR[11:0] bits */
214    tmpreg = 0;
215  
216    /* Configure speed in standard mode */
217    if (I2C_InitStruct->I2C_ClockSpeed <= 100000)
218    {
219      /* Standard mode speed calculate */
220      result = (uint16_t)(pclk1 / (I2C_InitStruct->I2C_ClockSpeed << 1));
221      /* Test if CCR value is under 0x4*/
222      if (result < 0x04)
223      {
224        /* Set minimum allowed value */
225        result = 0x04;
226      }
227      /* Set speed value for standard mode */
228      tmpreg |= result;
229      /* Set Maximum Rise Time for standard mode */
230      I2Cx->TRISE = freqrange + 1;
231    }
232    /* Configure speed in fast mode */
233    /* To use the I2C at 400 KHz (in fast mode), the PCLK1 frequency (I2C peripheral
234       input clock) must be a multiple of 10 MHz */
235    else /*(I2C_InitStruct->I2C_ClockSpeed <= 400000)*/
236    {
237      if (I2C_InitStruct->I2C_DutyCycle == I2C_DutyCycle_2)
238      {
239        /* Fast mode speed calculate: Tlow/Thigh = 2 */
240        result = (uint16_t)(pclk1 / (I2C_InitStruct->I2C_ClockSpeed * 3));
241      }
242      else /*I2C_InitStruct->I2C_DutyCycle == I2C_DutyCycle_16_9*/
243      {
244        /* Fast mode speed calculate: Tlow/Thigh = 16/9 */
245        result = (uint16_t)(pclk1 / (I2C_InitStruct->I2C_ClockSpeed * 25));
246        /* Set DUTY bit */
247        result |= I2C_DutyCycle_16_9;
248      }
249  
250      /* Test if CCR value is under 0x1*/
251      if ((result & I2C_CCR_CCR) == 0)
252      {
253        /* Set minimum allowed value */
254        result |= (uint16_t)0x0001;
255      }
256      /* Set speed value and set F/S bit for fast mode */
257      tmpreg |= (uint16_t)(result | I2C_CCR_FS);
258      /* Set Maximum Rise Time for fast mode */
259      I2Cx->TRISE = (uint16_t)(((freqrange * (uint16_t)300) / (uint16_t)1000) + (uint16_t)1);
260    }
261  
262    /* Write to I2Cx CCR */
263    I2Cx->CCR = tmpreg;
264    /* Enable the selected I2C peripheral */
265    I2Cx->CR1 |= I2C_CR1_PE;
266  
267  /*---------------------------- I2Cx CR1 Configuration ------------------------*/
268    /* Get the I2Cx CR1 value */
269    tmpreg = I2Cx->CR1;
270    /* Clear ACK, SMBTYPE and  SMBUS bits */
271    tmpreg &= CR1_CLEAR_MASK;
272    /* Configure I2Cx: mode and acknowledgement */
273    /* Set SMBTYPE and SMBUS bits according to I2C_Mode value */
274    /* Set ACK bit according to I2C_Ack value */
275    tmpreg |= (uint16_t)((uint32_t)I2C_InitStruct->I2C_Mode | I2C_InitStruct->I2C_Ack);
276    /* Write to I2Cx CR1 */
277    I2Cx->CR1 = tmpreg;
278  
279  /*---------------------------- I2Cx OAR1 Configuration -----------------------*/
280    /* Set I2Cx Own Address1 and acknowledged address */
281    I2Cx->OAR1 = (I2C_InitStruct->I2C_AcknowledgedAddress | I2C_InitStruct->I2C_OwnAddress1);
282  }
283  
284  /**
285    * @brief  Fills each I2C_InitStruct member with its default value.
286    * @param  I2C_InitStruct: pointer to an I2C_InitTypeDef structure which will be initialized.
287    * @retval None
288    */
I2C_StructInit(I2C_InitTypeDef * I2C_InitStruct)289  void I2C_StructInit(I2C_InitTypeDef* I2C_InitStruct)
290  {
291  /*---------------- Reset I2C init structure parameters values ----------------*/
292    /* initialize the I2C_ClockSpeed member */
293    I2C_InitStruct->I2C_ClockSpeed = 5000;
294    /* Initialize the I2C_Mode member */
295    I2C_InitStruct->I2C_Mode = I2C_Mode_I2C;
296    /* Initialize the I2C_DutyCycle member */
297    I2C_InitStruct->I2C_DutyCycle = I2C_DutyCycle_2;
298    /* Initialize the I2C_OwnAddress1 member */
299    I2C_InitStruct->I2C_OwnAddress1 = 0;
300    /* Initialize the I2C_Ack member */
301    I2C_InitStruct->I2C_Ack = I2C_Ack_Disable;
302    /* Initialize the I2C_AcknowledgedAddress member */
303    I2C_InitStruct->I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
304  }
305  
306  /**
307    * @brief  Enables or disables the specified I2C peripheral.
308    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
309    * @param  NewState: new state of the I2Cx peripheral.
310    *          This parameter can be: ENABLE or DISABLE.
311    * @retval None
312    */
I2C_Cmd(I2C_TypeDef * I2Cx,FunctionalState NewState)313  void I2C_Cmd(I2C_TypeDef* I2Cx, FunctionalState NewState)
314  {
315    /* Check the parameters */
316    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
317    assert_param(IS_FUNCTIONAL_STATE(NewState));
318    if (NewState != DISABLE)
319    {
320      /* Enable the selected I2C peripheral */
321      I2Cx->CR1 |= I2C_CR1_PE;
322    }
323    else
324    {
325      /* Disable the selected I2C peripheral */
326      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_PE);
327    }
328  }
329  
330  /**
331    * @brief  Enables or disables the Analog filter of I2C peripheral.
332    *
333    * @note   This function can be used only for STM32F42xxx/STM3243xxx, STM32F401xx and STM32F411xE devices.
334    *
335    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
336    * @param  NewState: new state of the Analog filter.
337    *          This parameter can be: ENABLE or DISABLE.
338    * @note   This function should be called before initializing and enabling
339              the I2C Peripheral.
340    * @retval None
341    */
I2C_AnalogFilterCmd(I2C_TypeDef * I2Cx,FunctionalState NewState)342  void I2C_AnalogFilterCmd(I2C_TypeDef* I2Cx, FunctionalState NewState)
343  {
344    /* Check the parameters */
345    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
346    assert_param(IS_FUNCTIONAL_STATE(NewState));
347    if (NewState != DISABLE)
348    {
349      /* Enable the analog filter */
350      I2Cx->FLTR &= (uint16_t)~((uint16_t)I2C_FLTR_ANOFF);
351    }
352    else
353    {
354      /* Disable the analog filter */
355      I2Cx->FLTR |= I2C_FLTR_ANOFF;
356    }
357  }
358  
359  /**
360    * @brief  Configures the Digital noise filter of I2C peripheral.
361    *
362    * @note   This function can be used only for STM32F42xxx/STM3243xxx, STM32F401xx and STM32F411xE devices.
363    *
364    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
365    * @param  I2C_DigitalFilter: Coefficient of digital noise filter.
366    *          This parameter can be a number between 0x00 and 0x0F.
367    * @note   This function should be called before initializing and enabling
368              the I2C Peripheral.
369    * @retval None
370    */
I2C_DigitalFilterConfig(I2C_TypeDef * I2Cx,uint16_t I2C_DigitalFilter)371  void I2C_DigitalFilterConfig(I2C_TypeDef* I2Cx, uint16_t I2C_DigitalFilter)
372  {
373    uint16_t tmpreg = 0;
374  
375    /* Check the parameters */
376    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
377    assert_param(IS_I2C_DIGITAL_FILTER(I2C_DigitalFilter));
378  
379    /* Get the old register value */
380    tmpreg = I2Cx->FLTR;
381  
382    /* Reset I2Cx DNF bit [3:0] */
383    tmpreg &= (uint16_t)~((uint16_t)I2C_FLTR_DNF);
384  
385    /* Set I2Cx DNF coefficient */
386    tmpreg |= (uint16_t)((uint16_t)I2C_DigitalFilter & I2C_FLTR_DNF);
387  
388    /* Store the new register value */
389    I2Cx->FLTR = tmpreg;
390  }
391  
392  /**
393    * @brief  Generates I2Cx communication START condition.
394    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
395    * @param  NewState: new state of the I2C START condition generation.
396    *          This parameter can be: ENABLE or DISABLE.
397    * @retval None.
398    */
I2C_GenerateSTART(I2C_TypeDef * I2Cx,FunctionalState NewState)399  void I2C_GenerateSTART(I2C_TypeDef* I2Cx, FunctionalState NewState)
400  {
401    /* Check the parameters */
402    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
403    assert_param(IS_FUNCTIONAL_STATE(NewState));
404    if (NewState != DISABLE)
405    {
406      /* Generate a START condition */
407      I2Cx->CR1 |= I2C_CR1_START;
408    }
409    else
410    {
411      /* Disable the START condition generation */
412      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_START);
413    }
414  }
415  
416  /**
417    * @brief  Generates I2Cx communication STOP condition.
418    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
419    * @param  NewState: new state of the I2C STOP condition generation.
420    *          This parameter can be: ENABLE or DISABLE.
421    * @retval None.
422    */
I2C_GenerateSTOP(I2C_TypeDef * I2Cx,FunctionalState NewState)423  void I2C_GenerateSTOP(I2C_TypeDef* I2Cx, FunctionalState NewState)
424  {
425    /* Check the parameters */
426    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
427    assert_param(IS_FUNCTIONAL_STATE(NewState));
428    if (NewState != DISABLE)
429    {
430      /* Generate a STOP condition */
431      I2Cx->CR1 |= I2C_CR1_STOP;
432    }
433    else
434    {
435      /* Disable the STOP condition generation */
436      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_STOP);
437    }
438  }
439  
440  /**
441    * @brief  Transmits the address byte to select the slave device.
442    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
443    * @param  Address: specifies the slave address which will be transmitted
444    * @param  I2C_Direction: specifies whether the I2C device will be a Transmitter
445    *         or a Receiver.
446    *          This parameter can be one of the following values
447    *            @arg I2C_Direction_Transmitter: Transmitter mode
448    *            @arg I2C_Direction_Receiver: Receiver mode
449    * @retval None.
450    */
I2C_Send7bitAddress(I2C_TypeDef * I2Cx,uint8_t Address,uint8_t I2C_Direction)451  void I2C_Send7bitAddress(I2C_TypeDef* I2Cx, uint8_t Address, uint8_t I2C_Direction)
452  {
453    /* Check the parameters */
454    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
455    assert_param(IS_I2C_DIRECTION(I2C_Direction));
456    /* Test on the direction to set/reset the read/write bit */
457    if (I2C_Direction != I2C_Direction_Transmitter)
458    {
459      /* Set the address bit0 for read */
460      Address |= I2C_OAR1_ADD0;
461    }
462    else
463    {
464      /* Reset the address bit0 for write */
465      Address &= (uint8_t)~((uint8_t)I2C_OAR1_ADD0);
466    }
467    /* Send the address */
468    I2Cx->DR = Address;
469  }
470  
471  /**
472    * @brief  Enables or disables the specified I2C acknowledge feature.
473    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
474    * @param  NewState: new state of the I2C Acknowledgement.
475    *          This parameter can be: ENABLE or DISABLE.
476    * @retval None.
477    */
I2C_AcknowledgeConfig(I2C_TypeDef * I2Cx,FunctionalState NewState)478  void I2C_AcknowledgeConfig(I2C_TypeDef* I2Cx, FunctionalState NewState)
479  {
480    /* Check the parameters */
481    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
482    assert_param(IS_FUNCTIONAL_STATE(NewState));
483    if (NewState != DISABLE)
484    {
485      /* Enable the acknowledgement */
486      I2Cx->CR1 |= I2C_CR1_ACK;
487    }
488    else
489    {
490      /* Disable the acknowledgement */
491      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_ACK);
492    }
493  }
494  
495  /**
496    * @brief  Configures the specified I2C own address2.
497    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
498    * @param  Address: specifies the 7bit I2C own address2.
499    * @retval None.
500    */
I2C_OwnAddress2Config(I2C_TypeDef * I2Cx,uint8_t Address)501  void I2C_OwnAddress2Config(I2C_TypeDef* I2Cx, uint8_t Address)
502  {
503    uint16_t tmpreg = 0;
504  
505    /* Check the parameters */
506    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
507  
508    /* Get the old register value */
509    tmpreg = I2Cx->OAR2;
510  
511    /* Reset I2Cx Own address2 bit [7:1] */
512    tmpreg &= (uint16_t)~((uint16_t)I2C_OAR2_ADD2);
513  
514    /* Set I2Cx Own address2 */
515    tmpreg |= (uint16_t)((uint16_t)Address & (uint16_t)0x00FE);
516  
517    /* Store the new register value */
518    I2Cx->OAR2 = tmpreg;
519  }
520  
521  /**
522    * @brief  Enables or disables the specified I2C dual addressing mode.
523    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
524    * @param  NewState: new state of the I2C dual addressing mode.
525    *          This parameter can be: ENABLE or DISABLE.
526    * @retval None
527    */
I2C_DualAddressCmd(I2C_TypeDef * I2Cx,FunctionalState NewState)528  void I2C_DualAddressCmd(I2C_TypeDef* I2Cx, FunctionalState NewState)
529  {
530    /* Check the parameters */
531    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
532    assert_param(IS_FUNCTIONAL_STATE(NewState));
533    if (NewState != DISABLE)
534    {
535      /* Enable dual addressing mode */
536      I2Cx->OAR2 |= I2C_OAR2_ENDUAL;
537    }
538    else
539    {
540      /* Disable dual addressing mode */
541      I2Cx->OAR2 &= (uint16_t)~((uint16_t)I2C_OAR2_ENDUAL);
542    }
543  }
544  
545  /**
546    * @brief  Enables or disables the specified I2C general call feature.
547    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
548    * @param  NewState: new state of the I2C General call.
549    *          This parameter can be: ENABLE or DISABLE.
550    * @retval None
551    */
I2C_GeneralCallCmd(I2C_TypeDef * I2Cx,FunctionalState NewState)552  void I2C_GeneralCallCmd(I2C_TypeDef* I2Cx, FunctionalState NewState)
553  {
554    /* Check the parameters */
555    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
556    assert_param(IS_FUNCTIONAL_STATE(NewState));
557    if (NewState != DISABLE)
558    {
559      /* Enable general call */
560      I2Cx->CR1 |= I2C_CR1_ENGC;
561    }
562    else
563    {
564      /* Disable general call */
565      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_ENGC);
566    }
567  }
568  
569  /**
570    * @brief  Enables or disables the specified I2C software reset.
571    * @note   When software reset is enabled, the I2C IOs are released (this can
572    *         be useful to recover from bus errors).
573    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
574    * @param  NewState: new state of the I2C software reset.
575    *          This parameter can be: ENABLE or DISABLE.
576    * @retval None
577    */
I2C_SoftwareResetCmd(I2C_TypeDef * I2Cx,FunctionalState NewState)578  void I2C_SoftwareResetCmd(I2C_TypeDef* I2Cx, FunctionalState NewState)
579  {
580    /* Check the parameters */
581    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
582    assert_param(IS_FUNCTIONAL_STATE(NewState));
583    if (NewState != DISABLE)
584    {
585      /* Peripheral under reset */
586      I2Cx->CR1 |= I2C_CR1_SWRST;
587    }
588    else
589    {
590      /* Peripheral not under reset */
591      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_SWRST);
592    }
593  }
594  
595  /**
596    * @brief  Enables or disables the specified I2C Clock stretching.
597    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
598    * @param  NewState: new state of the I2Cx Clock stretching.
599    *          This parameter can be: ENABLE or DISABLE.
600    * @retval None
601    */
I2C_StretchClockCmd(I2C_TypeDef * I2Cx,FunctionalState NewState)602  void I2C_StretchClockCmd(I2C_TypeDef* I2Cx, FunctionalState NewState)
603  {
604    /* Check the parameters */
605    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
606    assert_param(IS_FUNCTIONAL_STATE(NewState));
607    if (NewState == DISABLE)
608    {
609      /* Enable the selected I2C Clock stretching */
610      I2Cx->CR1 |= I2C_CR1_NOSTRETCH;
611    }
612    else
613    {
614      /* Disable the selected I2C Clock stretching */
615      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_NOSTRETCH);
616    }
617  }
618  
619  /**
620    * @brief  Selects the specified I2C fast mode duty cycle.
621    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
622    * @param  I2C_DutyCycle: specifies the fast mode duty cycle.
623    *          This parameter can be one of the following values:
624    *            @arg I2C_DutyCycle_2: I2C fast mode Tlow/Thigh = 2
625    *            @arg I2C_DutyCycle_16_9: I2C fast mode Tlow/Thigh = 16/9
626    * @retval None
627    */
I2C_FastModeDutyCycleConfig(I2C_TypeDef * I2Cx,uint16_t I2C_DutyCycle)628  void I2C_FastModeDutyCycleConfig(I2C_TypeDef* I2Cx, uint16_t I2C_DutyCycle)
629  {
630    /* Check the parameters */
631    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
632    assert_param(IS_I2C_DUTY_CYCLE(I2C_DutyCycle));
633    if (I2C_DutyCycle != I2C_DutyCycle_16_9)
634    {
635      /* I2C fast mode Tlow/Thigh=2 */
636      I2Cx->CCR &= I2C_DutyCycle_2;
637    }
638    else
639    {
640      /* I2C fast mode Tlow/Thigh=16/9 */
641      I2Cx->CCR |= I2C_DutyCycle_16_9;
642    }
643  }
644  
645  /**
646    * @brief  Selects the specified I2C NACK position in master receiver mode.
647    * @note   This function is useful in I2C Master Receiver mode when the number
648    *         of data to be received is equal to 2. In this case, this function
649    *         should be called (with parameter I2C_NACKPosition_Next) before data
650    *         reception starts,as described in the 2-byte reception procedure
651    *         recommended in Reference Manual in Section: Master receiver.
652    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
653    * @param  I2C_NACKPosition: specifies the NACK position.
654    *          This parameter can be one of the following values:
655    *            @arg I2C_NACKPosition_Next: indicates that the next byte will be the last
656    *                                        received byte.
657    *            @arg I2C_NACKPosition_Current: indicates that current byte is the last
658    *                                           received byte.
659    *
660    * @note    This function configures the same bit (POS) as I2C_PECPositionConfig()
661    *          but is intended to be used in I2C mode while I2C_PECPositionConfig()
662    *          is intended to used in SMBUS mode.
663    *
664    * @retval None
665    */
I2C_NACKPositionConfig(I2C_TypeDef * I2Cx,uint16_t I2C_NACKPosition)666  void I2C_NACKPositionConfig(I2C_TypeDef* I2Cx, uint16_t I2C_NACKPosition)
667  {
668    /* Check the parameters */
669    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
670    assert_param(IS_I2C_NACK_POSITION(I2C_NACKPosition));
671  
672    /* Check the input parameter */
673    if (I2C_NACKPosition == I2C_NACKPosition_Next)
674    {
675      /* Next byte in shift register is the last received byte */
676      I2Cx->CR1 |= I2C_NACKPosition_Next;
677    }
678    else
679    {
680      /* Current byte in shift register is the last received byte */
681      I2Cx->CR1 &= I2C_NACKPosition_Current;
682    }
683  }
684  
685  /**
686    * @brief  Drives the SMBusAlert pin high or low for the specified I2C.
687    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
688    * @param  I2C_SMBusAlert: specifies SMBAlert pin level.
689    *          This parameter can be one of the following values:
690    *            @arg I2C_SMBusAlert_Low: SMBAlert pin driven low
691    *            @arg I2C_SMBusAlert_High: SMBAlert pin driven high
692    * @retval None
693    */
I2C_SMBusAlertConfig(I2C_TypeDef * I2Cx,uint16_t I2C_SMBusAlert)694  void I2C_SMBusAlertConfig(I2C_TypeDef* I2Cx, uint16_t I2C_SMBusAlert)
695  {
696    /* Check the parameters */
697    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
698    assert_param(IS_I2C_SMBUS_ALERT(I2C_SMBusAlert));
699    if (I2C_SMBusAlert == I2C_SMBusAlert_Low)
700    {
701      /* Drive the SMBusAlert pin Low */
702      I2Cx->CR1 |= I2C_SMBusAlert_Low;
703    }
704    else
705    {
706      /* Drive the SMBusAlert pin High  */
707      I2Cx->CR1 &= I2C_SMBusAlert_High;
708    }
709  }
710  
711  /**
712    * @brief  Enables or disables the specified I2C ARP.
713    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
714    * @param  NewState: new state of the I2Cx ARP.
715    *          This parameter can be: ENABLE or DISABLE.
716    * @retval None
717    */
I2C_ARPCmd(I2C_TypeDef * I2Cx,FunctionalState NewState)718  void I2C_ARPCmd(I2C_TypeDef* I2Cx, FunctionalState NewState)
719  {
720    /* Check the parameters */
721    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
722    assert_param(IS_FUNCTIONAL_STATE(NewState));
723    if (NewState != DISABLE)
724    {
725      /* Enable the selected I2C ARP */
726      I2Cx->CR1 |= I2C_CR1_ENARP;
727    }
728    else
729    {
730      /* Disable the selected I2C ARP */
731      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_ENARP);
732    }
733  }
734  /**
735    * @}
736    */
737  
738  /** @defgroup I2C_Group2 Data transfers functions
739   *  @brief   Data transfers functions
740   *
741  @verbatim
742   ===============================================================================
743                    ##### Data transfers functions #####
744   ===============================================================================
745  
746  @endverbatim
747    * @{
748    */
749  
750  /**
751    * @brief  Sends a data byte through the I2Cx peripheral.
752    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
753    * @param  Data: Byte to be transmitted..
754    * @retval None
755    */
I2C_SendData(I2C_TypeDef * I2Cx,uint8_t Data)756  void I2C_SendData(I2C_TypeDef* I2Cx, uint8_t Data)
757  {
758    /* Check the parameters */
759    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
760    /* Write in the DR register the data to be sent */
761    I2Cx->DR = Data;
762  }
763  
764  /**
765    * @brief  Returns the most recent received data by the I2Cx peripheral.
766    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
767    * @retval The value of the received data.
768    */
I2C_ReceiveData(I2C_TypeDef * I2Cx)769  uint8_t I2C_ReceiveData(I2C_TypeDef* I2Cx)
770  {
771    /* Check the parameters */
772    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
773    /* Return the data in the DR register */
774    return (uint8_t)I2Cx->DR;
775  }
776  
777  /**
778    * @}
779    */
780  
781  /** @defgroup I2C_Group3 PEC management functions
782   *  @brief   PEC management functions
783   *
784  @verbatim
785   ===============================================================================
786                    ##### PEC management functions #####
787   ===============================================================================
788  
789  @endverbatim
790    * @{
791    */
792  
793  /**
794    * @brief  Enables or disables the specified I2C PEC transfer.
795    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
796    * @param  NewState: new state of the I2C PEC transmission.
797    *          This parameter can be: ENABLE or DISABLE.
798    * @retval None
799    */
I2C_TransmitPEC(I2C_TypeDef * I2Cx,FunctionalState NewState)800  void I2C_TransmitPEC(I2C_TypeDef* I2Cx, FunctionalState NewState)
801  {
802    /* Check the parameters */
803    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
804    assert_param(IS_FUNCTIONAL_STATE(NewState));
805    if (NewState != DISABLE)
806    {
807      /* Enable the selected I2C PEC transmission */
808      I2Cx->CR1 |= I2C_CR1_PEC;
809    }
810    else
811    {
812      /* Disable the selected I2C PEC transmission */
813      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_PEC);
814    }
815  }
816  
817  /**
818    * @brief  Selects the specified I2C PEC position.
819    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
820    * @param  I2C_PECPosition: specifies the PEC position.
821    *          This parameter can be one of the following values:
822    *            @arg I2C_PECPosition_Next: indicates that the next byte is PEC
823    *            @arg I2C_PECPosition_Current: indicates that current byte is PEC
824    *
825    * @note    This function configures the same bit (POS) as I2C_NACKPositionConfig()
826    *          but is intended to be used in SMBUS mode while I2C_NACKPositionConfig()
827    *          is intended to used in I2C mode.
828    *
829    * @retval None
830    */
I2C_PECPositionConfig(I2C_TypeDef * I2Cx,uint16_t I2C_PECPosition)831  void I2C_PECPositionConfig(I2C_TypeDef* I2Cx, uint16_t I2C_PECPosition)
832  {
833    /* Check the parameters */
834    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
835    assert_param(IS_I2C_PEC_POSITION(I2C_PECPosition));
836    if (I2C_PECPosition == I2C_PECPosition_Next)
837    {
838      /* Next byte in shift register is PEC */
839      I2Cx->CR1 |= I2C_PECPosition_Next;
840    }
841    else
842    {
843      /* Current byte in shift register is PEC */
844      I2Cx->CR1 &= I2C_PECPosition_Current;
845    }
846  }
847  
848  /**
849    * @brief  Enables or disables the PEC value calculation of the transferred bytes.
850    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
851    * @param  NewState: new state of the I2Cx PEC value calculation.
852    *          This parameter can be: ENABLE or DISABLE.
853    * @retval None
854    */
I2C_CalculatePEC(I2C_TypeDef * I2Cx,FunctionalState NewState)855  void I2C_CalculatePEC(I2C_TypeDef* I2Cx, FunctionalState NewState)
856  {
857    /* Check the parameters */
858    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
859    assert_param(IS_FUNCTIONAL_STATE(NewState));
860    if (NewState != DISABLE)
861    {
862      /* Enable the selected I2C PEC calculation */
863      I2Cx->CR1 |= I2C_CR1_ENPEC;
864    }
865    else
866    {
867      /* Disable the selected I2C PEC calculation */
868      I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_ENPEC);
869    }
870  }
871  
872  /**
873    * @brief  Returns the PEC value for the specified I2C.
874    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
875    * @retval The PEC value.
876    */
I2C_GetPEC(I2C_TypeDef * I2Cx)877  uint8_t I2C_GetPEC(I2C_TypeDef* I2Cx)
878  {
879    /* Check the parameters */
880    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
881    /* Return the selected I2C PEC value */
882    return ((I2Cx->SR2) >> 8);
883  }
884  
885  /**
886    * @}
887    */
888  
889  /** @defgroup I2C_Group4 DMA transfers management functions
890   *  @brief   DMA transfers management functions
891   *
892  @verbatim
893   ===============================================================================
894                  ##### DMA transfers management functions #####
895   ===============================================================================
896    This section provides functions allowing to configure the I2C DMA channels
897    requests.
898  
899  @endverbatim
900    * @{
901    */
902  
903  /**
904    * @brief  Enables or disables the specified I2C DMA requests.
905    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
906    * @param  NewState: new state of the I2C DMA transfer.
907    *          This parameter can be: ENABLE or DISABLE.
908    * @retval None
909    */
I2C_DMACmd(I2C_TypeDef * I2Cx,FunctionalState NewState)910  void I2C_DMACmd(I2C_TypeDef* I2Cx, FunctionalState NewState)
911  {
912    /* Check the parameters */
913    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
914    assert_param(IS_FUNCTIONAL_STATE(NewState));
915    if (NewState != DISABLE)
916    {
917      /* Enable the selected I2C DMA requests */
918      I2Cx->CR2 |= I2C_CR2_DMAEN;
919    }
920    else
921    {
922      /* Disable the selected I2C DMA requests */
923      I2Cx->CR2 &= (uint16_t)~((uint16_t)I2C_CR2_DMAEN);
924    }
925  }
926  
927  /**
928    * @brief  Specifies that the next DMA transfer is the last one.
929    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
930    * @param  NewState: new state of the I2C DMA last transfer.
931    *          This parameter can be: ENABLE or DISABLE.
932    * @retval None
933    */
I2C_DMALastTransferCmd(I2C_TypeDef * I2Cx,FunctionalState NewState)934  void I2C_DMALastTransferCmd(I2C_TypeDef* I2Cx, FunctionalState NewState)
935  {
936    /* Check the parameters */
937    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
938    assert_param(IS_FUNCTIONAL_STATE(NewState));
939    if (NewState != DISABLE)
940    {
941      /* Next DMA transfer is the last transfer */
942      I2Cx->CR2 |= I2C_CR2_LAST;
943    }
944    else
945    {
946      /* Next DMA transfer is not the last transfer */
947      I2Cx->CR2 &= (uint16_t)~((uint16_t)I2C_CR2_LAST);
948    }
949  }
950  
951  /**
952    * @}
953    */
954  
955  /** @defgroup I2C_Group5 Interrupts events and flags management functions
956   *  @brief   Interrupts, events and flags management functions
957   *
958  @verbatim
959   ===============================================================================
960            ##### Interrupts, events and flags management functions #####
961   ===============================================================================
962      [..]
963      This section provides functions allowing to configure the I2C Interrupts
964      sources and check or clear the flags or pending bits status.
965      The user should identify which mode will be used in his application to manage
966      the communication: Polling mode, Interrupt mode or DMA mode.
967  
968  
969                  ##### I2C State Monitoring Functions #####
970   ===============================================================================
971      [..]
972      This I2C driver provides three different ways for I2C state monitoring
973      depending on the application requirements and constraints:
974  
975  
976       (#) Basic state monitoring (Using I2C_CheckEvent() function)
977  
978          It compares the status registers (SR1 and SR2) content to a given event
979          (can be the combination of one or more flags).
980          It returns SUCCESS if the current status includes the given flags
981          and returns ERROR if one or more flags are missing in the current status.
982  
983            (++) When to use
984               (+++) This function is suitable for most applications as well as for startup
985                 activity since the events are fully described in the product reference
986                 manual (RM0090).
987               (+++) It is also suitable for users who need to define their own events.
988  
989            (++) Limitations
990                 If an error occurs (ie. error flags are set besides to the monitored
991                 flags), the I2C_CheckEvent() function may return SUCCESS despite
992                 the communication hold or corrupted real state.
993                 In this case, it is advised to use error interrupts to monitor
994                 the error events and handle them in the interrupt IRQ handler.
995  
996       -@@- For error management, it is advised to use the following functions:
997          (+@@) I2C_ITConfig() to configure and enable the error interrupts (I2C_IT_ERR).
998          (+@@) I2Cx_ER_IRQHandler() which is called when the error interrupt occurs.
999                Where x is the peripheral instance (I2C1, I2C2 ...)
1000          (+@@) I2C_GetFlagStatus() or I2C_GetITStatus()  to be called into the
1001                I2Cx_ER_IRQHandler() function in order to determine which error occurred.
1002          (+@@) I2C_ClearFlag() or I2C_ClearITPendingBit() and/or I2C_SoftwareResetCmd()
1003                and/or I2C_GenerateStop() in order to clear the error flag and source
1004                and return to correct  communication status.
1005  
1006  
1007       (#) Advanced state monitoring (Using the function I2C_GetLastEvent())
1008  
1009          Using the function I2C_GetLastEvent() which returns the image of both status
1010          registers in a single word (uint32_t) (Status Register 2 value is shifted left
1011          by 16 bits and concatenated to Status Register 1).
1012  
1013            (++) When to use
1014               (+++) This function is suitable for the same applications above but it
1015                 allows to overcome the mentioned limitation of I2C_GetFlagStatus()
1016                 function.
1017               (+++) The returned value could be compared to events already defined in
1018                 the library (stm32f4xx_i2c.h) or to custom values defined by user.
1019                 This function is suitable when multiple flags are monitored at the
1020                 same time.
1021               (+++) At the opposite of I2C_CheckEvent() function, this function allows
1022                 user to choose when an event is accepted (when all events flags are
1023                 set and no other flags are set or just when the needed flags are set
1024                 like I2C_CheckEvent() function.
1025  
1026            (++) Limitations
1027               (+++) User may need to define his own events.
1028               (+++) Same remark concerning the error management is applicable for this
1029                 function if user decides to check only regular communication flags
1030                 (and ignores error flags).
1031  
1032  
1033       (#) Flag-based state monitoring (Using the function I2C_GetFlagStatus())
1034  
1035        Using the function I2C_GetFlagStatus() which simply returns the status of
1036        one single flag (ie. I2C_FLAG_RXNE ...).
1037  
1038            (++) When to use
1039               (+++) This function could be used for specific applications or in debug
1040                 phase.
1041               (+++) It is suitable when only one flag checking is needed (most I2C
1042                 events are monitored through multiple flags).
1043            (++) Limitations:
1044               (+++) When calling this function, the Status register is accessed.
1045                 Some flags are cleared when the status register is accessed.
1046                 So checking the status of one Flag, may clear other ones.
1047               (+++) Function may need to be called twice or more in order to monitor
1048                 one single event.
1049  
1050     For detailed description of Events, please refer to section I2C_Events in
1051     stm32f4xx_i2c.h file.
1052  
1053  @endverbatim
1054    * @{
1055    */
1056  
1057  /**
1058    * @brief  Reads the specified I2C register and returns its value.
1059    * @param  I2C_Register: specifies the register to read.
1060    *          This parameter can be one of the following values:
1061    *            @arg I2C_Register_CR1:  CR1 register.
1062    *            @arg I2C_Register_CR2:   CR2 register.
1063    *            @arg I2C_Register_OAR1:  OAR1 register.
1064    *            @arg I2C_Register_OAR2:  OAR2 register.
1065    *            @arg I2C_Register_DR:    DR register.
1066    *            @arg I2C_Register_SR1:   SR1 register.
1067    *            @arg I2C_Register_SR2:   SR2 register.
1068    *            @arg I2C_Register_CCR:   CCR register.
1069    *            @arg I2C_Register_TRISE: TRISE register.
1070    * @retval The value of the read register.
1071    */
I2C_ReadRegister(I2C_TypeDef * I2Cx,uint8_t I2C_Register)1072  uint16_t I2C_ReadRegister(I2C_TypeDef* I2Cx, uint8_t I2C_Register)
1073  {
1074    __IO uint32_t tmp = 0;
1075  
1076    /* Check the parameters */
1077    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
1078    assert_param(IS_I2C_REGISTER(I2C_Register));
1079  
1080    tmp = (uint32_t) I2Cx;
1081    tmp += I2C_Register;
1082  
1083    /* Return the selected register value */
1084    return (*(__IO uint16_t *) tmp);
1085  }
1086  
1087  /**
1088    * @brief  Enables or disables the specified I2C interrupts.
1089    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
1090    * @param  I2C_IT: specifies the I2C interrupts sources to be enabled or disabled.
1091    *          This parameter can be any combination of the following values:
1092    *            @arg I2C_IT_BUF: Buffer interrupt mask
1093    *            @arg I2C_IT_EVT: Event interrupt mask
1094    *            @arg I2C_IT_ERR: Error interrupt mask
1095    * @param  NewState: new state of the specified I2C interrupts.
1096    *          This parameter can be: ENABLE or DISABLE.
1097    * @retval None
1098    */
I2C_ITConfig(I2C_TypeDef * I2Cx,uint16_t I2C_IT,FunctionalState NewState)1099  void I2C_ITConfig(I2C_TypeDef* I2Cx, uint16_t I2C_IT, FunctionalState NewState)
1100  {
1101    /* Check the parameters */
1102    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
1103    assert_param(IS_FUNCTIONAL_STATE(NewState));
1104    assert_param(IS_I2C_CONFIG_IT(I2C_IT));
1105  
1106    if (NewState != DISABLE)
1107    {
1108      /* Enable the selected I2C interrupts */
1109      I2Cx->CR2 |= I2C_IT;
1110    }
1111    else
1112    {
1113      /* Disable the selected I2C interrupts */
1114      I2Cx->CR2 &= (uint16_t)~I2C_IT;
1115    }
1116  }
1117  
1118  /*
1119   ===============================================================================
1120                            1. Basic state monitoring
1121   ===============================================================================
1122   */
1123  
1124  /**
1125    * @brief  Checks whether the last I2Cx Event is equal to the one passed
1126    *         as parameter.
1127    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
1128    * @param  I2C_EVENT: specifies the event to be checked.
1129    *          This parameter can be one of the following values:
1130    *            @arg I2C_EVENT_SLAVE_TRANSMITTER_ADDRESS_MATCHED: EV1
1131    *            @arg I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED: EV1
1132    *            @arg I2C_EVENT_SLAVE_TRANSMITTER_SECONDADDRESS_MATCHED: EV1
1133    *            @arg I2C_EVENT_SLAVE_RECEIVER_SECONDADDRESS_MATCHED: EV1
1134    *            @arg I2C_EVENT_SLAVE_GENERALCALLADDRESS_MATCHED: EV1
1135    *            @arg I2C_EVENT_SLAVE_BYTE_RECEIVED: EV2
1136    *            @arg (I2C_EVENT_SLAVE_BYTE_RECEIVED | I2C_FLAG_DUALF): EV2
1137    *            @arg (I2C_EVENT_SLAVE_BYTE_RECEIVED | I2C_FLAG_GENCALL): EV2
1138    *            @arg I2C_EVENT_SLAVE_BYTE_TRANSMITTED: EV3
1139    *            @arg (I2C_EVENT_SLAVE_BYTE_TRANSMITTED | I2C_FLAG_DUALF): EV3
1140    *            @arg (I2C_EVENT_SLAVE_BYTE_TRANSMITTED | I2C_FLAG_GENCALL): EV3
1141    *            @arg I2C_EVENT_SLAVE_ACK_FAILURE: EV3_2
1142    *            @arg I2C_EVENT_SLAVE_STOP_DETECTED: EV4
1143    *            @arg I2C_EVENT_MASTER_MODE_SELECT: EV5
1144    *            @arg I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED: EV6
1145    *            @arg I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED: EV6
1146    *            @arg I2C_EVENT_MASTER_BYTE_RECEIVED: EV7
1147    *            @arg I2C_EVENT_MASTER_BYTE_TRANSMITTING: EV8
1148    *            @arg I2C_EVENT_MASTER_BYTE_TRANSMITTED: EV8_2
1149    *            @arg I2C_EVENT_MASTER_MODE_ADDRESS10: EV9
1150    *
1151    * @note   For detailed description of Events, please refer to section I2C_Events
1152    *         in stm32f4xx_i2c.h file.
1153    *
1154    * @retval An ErrorStatus enumeration value:
1155    *           - SUCCESS: Last event is equal to the I2C_EVENT
1156    *           - ERROR: Last event is different from the I2C_EVENT
1157    */
I2C_CheckEvent(I2C_TypeDef * I2Cx,uint32_t I2C_EVENT)1158  ErrorStatus I2C_CheckEvent(I2C_TypeDef* I2Cx, uint32_t I2C_EVENT)
1159  {
1160    uint32_t lastevent = 0;
1161    uint32_t flag1 = 0, flag2 = 0;
1162    ErrorStatus status = ERROR;
1163  
1164    /* Check the parameters */
1165    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
1166    assert_param(IS_I2C_EVENT(I2C_EVENT));
1167  
1168    /* Read the I2Cx status register */
1169    flag1 = I2Cx->SR1;
1170    flag2 = I2Cx->SR2;
1171    flag2 = flag2 << 16;
1172  
1173    /* Get the last event value from I2C status register */
1174    lastevent = (flag1 | flag2) & FLAG_MASK;
1175  
1176    /* Check whether the last event contains the I2C_EVENT */
1177    if ((lastevent & I2C_EVENT) == I2C_EVENT)
1178    {
1179      /* SUCCESS: last event is equal to I2C_EVENT */
1180      status = SUCCESS;
1181    }
1182    else
1183    {
1184      /* ERROR: last event is different from I2C_EVENT */
1185      status = ERROR;
1186    }
1187    /* Return status */
1188    return status;
1189  }
1190  
1191  /*
1192   ===============================================================================
1193                            2. Advanced state monitoring
1194   ===============================================================================
1195   */
1196  
1197  /**
1198    * @brief  Returns the last I2Cx Event.
1199    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
1200    *
1201    * @note   For detailed description of Events, please refer to section I2C_Events
1202    *         in stm32f4xx_i2c.h file.
1203    *
1204    * @retval The last event
1205    */
I2C_GetLastEvent(I2C_TypeDef * I2Cx)1206  uint32_t I2C_GetLastEvent(I2C_TypeDef* I2Cx)
1207  {
1208    uint32_t lastevent = 0;
1209    uint32_t flag1 = 0, flag2 = 0;
1210  
1211    /* Check the parameters */
1212    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
1213  
1214    /* Read the I2Cx status register */
1215    flag1 = I2Cx->SR1;
1216    flag2 = I2Cx->SR2;
1217    flag2 = flag2 << 16;
1218  
1219    /* Get the last event value from I2C status register */
1220    lastevent = (flag1 | flag2) & FLAG_MASK;
1221  
1222    /* Return status */
1223    return lastevent;
1224  }
1225  
1226  /*
1227   ===============================================================================
1228                            3. Flag-based state monitoring
1229   ===============================================================================
1230   */
1231  
1232  /**
1233    * @brief  Checks whether the specified I2C flag is set or not.
1234    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
1235    * @param  I2C_FLAG: specifies the flag to check.
1236    *          This parameter can be one of the following values:
1237    *            @arg I2C_FLAG_DUALF: Dual flag (Slave mode)
1238    *            @arg I2C_FLAG_SMBHOST: SMBus host header (Slave mode)
1239    *            @arg I2C_FLAG_SMBDEFAULT: SMBus default header (Slave mode)
1240    *            @arg I2C_FLAG_GENCALL: General call header flag (Slave mode)
1241    *            @arg I2C_FLAG_TRA: Transmitter/Receiver flag
1242    *            @arg I2C_FLAG_BUSY: Bus busy flag
1243    *            @arg I2C_FLAG_MSL: Master/Slave flag
1244    *            @arg I2C_FLAG_SMBALERT: SMBus Alert flag
1245    *            @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag
1246    *            @arg I2C_FLAG_PECERR: PEC error in reception flag
1247    *            @arg I2C_FLAG_OVR: Overrun/Underrun flag (Slave mode)
1248    *            @arg I2C_FLAG_AF: Acknowledge failure flag
1249    *            @arg I2C_FLAG_ARLO: Arbitration lost flag (Master mode)
1250    *            @arg I2C_FLAG_BERR: Bus error flag
1251    *            @arg I2C_FLAG_TXE: Data register empty flag (Transmitter)
1252    *            @arg I2C_FLAG_RXNE: Data register not empty (Receiver) flag
1253    *            @arg I2C_FLAG_STOPF: Stop detection flag (Slave mode)
1254    *            @arg I2C_FLAG_ADD10: 10-bit header sent flag (Master mode)
1255    *            @arg I2C_FLAG_BTF: Byte transfer finished flag
1256    *            @arg I2C_FLAG_ADDR: Address sent flag (Master mode) "ADSL"
1257    *                                Address matched flag (Slave mode)"ENDAD"
1258    *            @arg I2C_FLAG_SB: Start bit flag (Master mode)
1259    * @retval The new state of I2C_FLAG (SET or RESET).
1260    */
I2C_GetFlagStatus(I2C_TypeDef * I2Cx,uint32_t I2C_FLAG)1261  FlagStatus I2C_GetFlagStatus(I2C_TypeDef* I2Cx, uint32_t I2C_FLAG)
1262  {
1263    FlagStatus bitstatus = RESET;
1264    __IO uint32_t i2creg = 0, i2cxbase = 0;
1265  
1266    /* Check the parameters */
1267    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
1268    assert_param(IS_I2C_GET_FLAG(I2C_FLAG));
1269  
1270    /* Get the I2Cx peripheral base address */
1271    i2cxbase = (uint32_t)I2Cx;
1272  
1273    /* Read flag register index */
1274    i2creg = I2C_FLAG >> 28;
1275  
1276    /* Get bit[23:0] of the flag */
1277    I2C_FLAG &= FLAG_MASK;
1278  
1279    if(i2creg != 0)
1280    {
1281      /* Get the I2Cx SR1 register address */
1282      i2cxbase += 0x14;
1283    }
1284    else
1285    {
1286      /* Flag in I2Cx SR2 Register */
1287      I2C_FLAG = (uint32_t)(I2C_FLAG >> 16);
1288      /* Get the I2Cx SR2 register address */
1289      i2cxbase += 0x18;
1290    }
1291  
1292    if(((*(__IO uint32_t *)i2cxbase) & I2C_FLAG) != (uint32_t)RESET)
1293    {
1294      /* I2C_FLAG is set */
1295      bitstatus = SET;
1296    }
1297    else
1298    {
1299      /* I2C_FLAG is reset */
1300      bitstatus = RESET;
1301    }
1302  
1303    /* Return the I2C_FLAG status */
1304    return  bitstatus;
1305  }
1306  
1307  /**
1308    * @brief  Clears the I2Cx's pending flags.
1309    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
1310    * @param  I2C_FLAG: specifies the flag to clear.
1311    *          This parameter can be any combination of the following values:
1312    *            @arg I2C_FLAG_SMBALERT: SMBus Alert flag
1313    *            @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag
1314    *            @arg I2C_FLAG_PECERR: PEC error in reception flag
1315    *            @arg I2C_FLAG_OVR: Overrun/Underrun flag (Slave mode)
1316    *            @arg I2C_FLAG_AF: Acknowledge failure flag
1317    *            @arg I2C_FLAG_ARLO: Arbitration lost flag (Master mode)
1318    *            @arg I2C_FLAG_BERR: Bus error flag
1319    *
1320    * @note   STOPF (STOP detection) is cleared by software sequence: a read operation
1321    *          to I2C_SR1 register (I2C_GetFlagStatus()) followed by a write operation
1322    *          to I2C_CR1 register (I2C_Cmd() to re-enable the I2C peripheral).
1323    * @note   ADD10 (10-bit header sent) is cleared by software sequence: a read
1324    *          operation to I2C_SR1 (I2C_GetFlagStatus()) followed by writing the
1325    *          second byte of the address in DR register.
1326    * @note   BTF (Byte Transfer Finished) is cleared by software sequence: a read
1327    *          operation to I2C_SR1 register (I2C_GetFlagStatus()) followed by a
1328    *          read/write to I2C_DR register (I2C_SendData()).
1329    * @note   ADDR (Address sent) is cleared by software sequence: a read operation to
1330    *          I2C_SR1 register (I2C_GetFlagStatus()) followed by a read operation to
1331    *          I2C_SR2 register ((void)(I2Cx->SR2)).
1332    * @note   SB (Start Bit) is cleared software sequence: a read operation to I2C_SR1
1333    *          register (I2C_GetFlagStatus()) followed by a write operation to I2C_DR
1334    *          register (I2C_SendData()).
1335    *
1336    * @retval None
1337    */
I2C_ClearFlag(I2C_TypeDef * I2Cx,uint32_t I2C_FLAG)1338  void I2C_ClearFlag(I2C_TypeDef* I2Cx, uint32_t I2C_FLAG)
1339  {
1340    uint32_t flagpos = 0;
1341    /* Check the parameters */
1342    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
1343    assert_param(IS_I2C_CLEAR_FLAG(I2C_FLAG));
1344    /* Get the I2C flag position */
1345    flagpos = I2C_FLAG & FLAG_MASK;
1346    /* Clear the selected I2C flag */
1347    I2Cx->SR1 = (uint16_t)~flagpos;
1348  }
1349  
1350  /**
1351    * @brief  Checks whether the specified I2C interrupt has occurred or not.
1352    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
1353    * @param  I2C_IT: specifies the interrupt source to check.
1354    *          This parameter can be one of the following values:
1355    *            @arg I2C_IT_SMBALERT: SMBus Alert flag
1356    *            @arg I2C_IT_TIMEOUT: Timeout or Tlow error flag
1357    *            @arg I2C_IT_PECERR: PEC error in reception flag
1358    *            @arg I2C_IT_OVR: Overrun/Underrun flag (Slave mode)
1359    *            @arg I2C_IT_AF: Acknowledge failure flag
1360    *            @arg I2C_IT_ARLO: Arbitration lost flag (Master mode)
1361    *            @arg I2C_IT_BERR: Bus error flag
1362    *            @arg I2C_IT_TXE: Data register empty flag (Transmitter)
1363    *            @arg I2C_IT_RXNE: Data register not empty (Receiver) flag
1364    *            @arg I2C_IT_STOPF: Stop detection flag (Slave mode)
1365    *            @arg I2C_IT_ADD10: 10-bit header sent flag (Master mode)
1366    *            @arg I2C_IT_BTF: Byte transfer finished flag
1367    *            @arg I2C_IT_ADDR: Address sent flag (Master mode) "ADSL"
1368    *                              Address matched flag (Slave mode)"ENDAD"
1369    *            @arg I2C_IT_SB: Start bit flag (Master mode)
1370    * @retval The new state of I2C_IT (SET or RESET).
1371    */
I2C_GetITStatus(I2C_TypeDef * I2Cx,uint32_t I2C_IT)1372  ITStatus I2C_GetITStatus(I2C_TypeDef* I2Cx, uint32_t I2C_IT)
1373  {
1374    ITStatus bitstatus = RESET;
1375    uint32_t enablestatus = 0;
1376  
1377    /* Check the parameters */
1378    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
1379    assert_param(IS_I2C_GET_IT(I2C_IT));
1380  
1381    /* Check if the interrupt source is enabled or not */
1382    enablestatus = (uint32_t)(((I2C_IT & ITEN_MASK) >> 16) & (I2Cx->CR2)) ;
1383  
1384    /* Get bit[23:0] of the flag */
1385    I2C_IT &= FLAG_MASK;
1386  
1387    /* Check the status of the specified I2C flag */
1388    if (((I2Cx->SR1 & I2C_IT) != (uint32_t)RESET) && enablestatus)
1389    {
1390      /* I2C_IT is set */
1391      bitstatus = SET;
1392    }
1393    else
1394    {
1395      /* I2C_IT is reset */
1396      bitstatus = RESET;
1397    }
1398    /* Return the I2C_IT status */
1399    return  bitstatus;
1400  }
1401  
1402  /**
1403    * @brief  Clears the I2Cx's interrupt pending bits.
1404    * @param  I2Cx: where x can be 1, 2 or 3 to select the I2C peripheral.
1405    * @param  I2C_IT: specifies the interrupt pending bit to clear.
1406    *          This parameter can be any combination of the following values:
1407    *            @arg I2C_IT_SMBALERT: SMBus Alert interrupt
1408    *            @arg I2C_IT_TIMEOUT: Timeout or Tlow error interrupt
1409    *            @arg I2C_IT_PECERR: PEC error in reception  interrupt
1410    *            @arg I2C_IT_OVR: Overrun/Underrun interrupt (Slave mode)
1411    *            @arg I2C_IT_AF: Acknowledge failure interrupt
1412    *            @arg I2C_IT_ARLO: Arbitration lost interrupt (Master mode)
1413    *            @arg I2C_IT_BERR: Bus error interrupt
1414    *
1415    * @note   STOPF (STOP detection) is cleared by software sequence: a read operation
1416    *          to I2C_SR1 register (I2C_GetITStatus()) followed by a write operation to
1417    *          I2C_CR1 register (I2C_Cmd() to re-enable the I2C peripheral).
1418    * @note   ADD10 (10-bit header sent) is cleared by software sequence: a read
1419    *          operation to I2C_SR1 (I2C_GetITStatus()) followed by writing the second
1420    *          byte of the address in I2C_DR register.
1421    * @note   BTF (Byte Transfer Finished) is cleared by software sequence: a read
1422    *          operation to I2C_SR1 register (I2C_GetITStatus()) followed by a
1423    *          read/write to I2C_DR register (I2C_SendData()).
1424    * @note   ADDR (Address sent) is cleared by software sequence: a read operation to
1425    *          I2C_SR1 register (I2C_GetITStatus()) followed by a read operation to
1426    *          I2C_SR2 register ((void)(I2Cx->SR2)).
1427    * @note   SB (Start Bit) is cleared by software sequence: a read operation to
1428    *          I2C_SR1 register (I2C_GetITStatus()) followed by a write operation to
1429    *          I2C_DR register (I2C_SendData()).
1430    * @retval None
1431    */
I2C_ClearITPendingBit(I2C_TypeDef * I2Cx,uint32_t I2C_IT)1432  void I2C_ClearITPendingBit(I2C_TypeDef* I2Cx, uint32_t I2C_IT)
1433  {
1434    uint32_t flagpos = 0;
1435    /* Check the parameters */
1436    assert_param(IS_I2C_ALL_PERIPH(I2Cx));
1437    assert_param(IS_I2C_CLEAR_IT(I2C_IT));
1438  
1439    /* Get the I2C flag position */
1440    flagpos = I2C_IT & FLAG_MASK;
1441  
1442    /* Clear the selected I2C flag */
1443    I2Cx->SR1 = (uint16_t)~flagpos;
1444  }
1445  
1446  /**
1447    * @}
1448    */
1449  
1450  /**
1451    * @}
1452    */
1453  
1454  /**
1455    * @}
1456    */
1457  
1458  /**
1459    * @}
1460    */
1461  
1462  /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
1463