aboutsummaryrefslogtreecommitdiff
path: root/Drivers/STM32F4xx_HAL_Driver/Src
diff options
context:
space:
mode:
Diffstat (limited to 'Drivers/STM32F4xx_HAL_Driver/Src')
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal.c453
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc.c1286
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc_ex.c838
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_can.c1415
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cortex.c444
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_crc.c332
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cryp.c3726
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cryp_ex.c2998
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac.c916
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac_ex.c377
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dcmi.c815
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma.c888
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma2d.c1239
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma_ex.c294
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_eth.c1933
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash.c748
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash_ex.c1299
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_gpio.c479
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hash.c1812
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hash_ex.c1598
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hcd.c1194
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c.c3744
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c_ex.c204
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s.c1638
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s_ex.c748
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_irda.c1302
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_iwdg.c342
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_ltdc.c1182
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_msp_template.c133
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_nand.c1050
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_nor.c782
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pccard.c711
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pcd.c1212
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr.c520
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr_ex.c329
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc.c1248
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc_ex.c512
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rng.c414
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc.c1497
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc_ex.c1671
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sai.c1338
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sd.c3359
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sdram.c824
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_smartcard.c1266
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_spi.c2034
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sram.c664
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim.c5036
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim_ex.c1810
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_uart.c1885
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_usart.c1821
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_wwdg.c451
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_fmc.c1273
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_fsmc.c856
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_sdmmc.c555
-rw-r--r--Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_usb.c1684
55 files changed, 69179 insertions, 0 deletions
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal.c
new file mode 100644
index 0000000..858397f
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal.c
@@ -0,0 +1,453 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief HAL module driver.
+ * This is the common part of the HAL initialization
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The common HAL driver contains a set of generic and common APIs that can be
+ used by the PPP peripheral drivers and the user to start using the HAL.
+ [..]
+ The HAL contains two APIs categories:
+ (+) Common HAL APIs
+ (+) Services HAL APIs
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup HAL
+ * @brief HAL module driver.
+ * @{
+ */
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/**
+ * @brief STM32F4xx HAL Driver version number V1.0.0
+ */
+#define __STM32F4xx_HAL_VERSION_MAIN (0x01) /*!< [31:24] main version */
+#define __STM32F4xx_HAL_VERSION_SUB1 (0x00) /*!< [23:16] sub1 version */
+#define __STM32F4xx_HAL_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */
+#define __STM32F4xx_HAL_VERSION_RC (0x00) /*!< [7:0] release candidate */
+#define __STM32F4xx_HAL_VERSION ((__STM32F4xx_HAL_VERSION_MAIN << 24)\
+ |(__STM32F4xx_HAL_VERSION_SUB1 << 16)\
+ |(__STM32F4xx_HAL_VERSION_SUB2 << 8 )\
+ |(__STM32F4xx_HAL_VERSION_RC))
+
+#define IDCODE_DEVID_MASK ((uint32_t)0x00000FFF)
+
+/* ------------ RCC registers bit address in the alias region ----------- */
+#define SYSCFG_OFFSET (SYSCFG_BASE - PERIPH_BASE)
+/* --- MEMRMP Register ---*/
+/* Alias word address of UFB_MODE bit */
+#define MEMRMP_OFFSET SYSCFG_OFFSET
+#define UFB_MODE_BitNumber ((uint8_t)0x8)
+#define UFB_MODE_BB (PERIPH_BB_BASE + (MEMRMP_OFFSET * 32) + (UFB_MODE_BitNumber * 4))
+
+/* --- CMPCR Register ---*/
+/* Alias word address of CMP_PD bit */
+#define CMPCR_OFFSET (SYSCFG_OFFSET + 0x20)
+#define CMP_PD_BitNumber ((uint8_t)0x00)
+#define CMPCR_CMP_PD_BB (PERIPH_BB_BASE + (CMPCR_OFFSET * 32) + (CMP_PD_BitNumber * 4))
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+static __IO uint32_t uwTick;
+
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup HAL_Private_Functions
+ * @{
+ */
+
+/** @defgroup HAL_Group1 Initialization and de-initialization Functions
+ * @brief Initialization and de-initialization functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initializes the Flash interface the NVIC allocation and initial clock
+ configuration. It initializes the systick also when timeout is needed
+ and the backup domain when enabled.
+ (+) de-Initializes common part of the HAL
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief This function is used to initialize the HAL Library; it must be the first
+ * instruction to be executed in the main program (before to call any other
+ * HAL function), it performs the following:
+ * - Configure the Flash prefetch, instruction and Data caches
+ * - Configures the SysTick to generate an interrupt each 1 millisecond,
+ * which is clocked by the HSI (at this stage, the clock is not yet
+ * configured and thus the system is running from the internal HSI at 16 MHz)
+ * - Set NVIC Group Priority to 4
+ * - Calls the HAL_MspInit() callback function defined in user file
+ * stm32f4xx_hal_msp.c to do the global low level hardware initialization
+ *
+ * @note SysTick is used as time base for the HAL_Delay() function, the application
+ * need to ensure that the SysTick time base is always set to 1 millisecond
+ * to have correct HAL operation.
+ * @note
+ * @param None
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_Init(void)
+{
+ /* Configure Flash prefetch, Instruction cache, Data cache */
+#if (INSTRUCTION_CACHE_ENABLE != 0)
+ __HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
+#endif /* INSTRUCTION_CACHE_ENABLE */
+
+#if (DATA_CACHE_ENABLE != 0)
+ __HAL_FLASH_DATA_CACHE_ENABLE();
+#endif /* DATA_CACHE_ENABLE */
+
+#if (PREFETCH_ENABLE != 0)
+ __HAL_FLASH_PREFETCH_BUFFER_ENABLE();
+#endif /* PREFETCH_ENABLE */
+
+ /* Enable systick and configure 1ms tick (default clock after Reset is HSI) */
+ HAL_SYSTICK_Config(HSI_VALUE/ 1000);
+
+ /* Set Interrupt Group Priority */
+ HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
+
+ /* Init the low level hardware */
+ HAL_MspInit();
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief This function de-Initializes common part of the HAL and stops the systick.
+ * This function is optional.
+ * @param None
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DeInit(void)
+{
+ /* Reset of all peripherals */
+ __APB1_FORCE_RESET();
+ __APB1_RELEASE_RESET();
+
+ __APB2_FORCE_RESET();
+ __APB2_RELEASE_RESET();
+
+ __AHB1_FORCE_RESET();
+ __AHB1_RELEASE_RESET();
+
+ __AHB2_FORCE_RESET();
+ __AHB2_RELEASE_RESET();
+
+ __AHB3_FORCE_RESET();
+ __AHB3_RELEASE_RESET();
+
+ /* De-Init the low level hardware */
+ HAL_MspDeInit();
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the MSP.
+ * @param None
+ * @retval None
+ */
+__weak void HAL_MspInit(void)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the MSP.
+ * @param None
+ * @retval None
+ */
+__weak void HAL_MspDeInit(void)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HAL_Group2 HAL Control functions
+ * @brief HAL Control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### HAL Control functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) provide a tick value in millisecond
+ (+) provide a blocking delay in millisecond
+ (+) Get the HAL API driver version
+ (+) Get the device identifier
+ (+) Get the device revision identifier
+ (+) Enable/Disable Debug module during Sleep mode
+ (+) Enable/Disable Debug module during STOP mode
+ (+) Enable/Disable Debug module during STANDBY mode
+
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief This function is called from SysTick ISR each 1 millisecond, to increment
+ * a global variable "uwTick" used as time base.
+ * @param None
+ * @retval None
+ */
+void HAL_IncTick(void)
+{
+ uwTick++;
+}
+
+/**
+ * @brief Povides a tick value in millisecond.
+ * @param Non
+ * @retval tick value
+ */
+uint32_t HAL_GetTick(void)
+{
+ return uwTick;
+}
+
+/**
+ * @brief Provides a blocking delay in millisecond.
+ * @note Care must be taken when using HAL_Delay(), this function provides accurate delay
+ * (in milliseconds) based on variable incremented in SysTick ISR. This implies that
+ * if HAL_Delay() is called from a peripheral ISR process, then the SysTick interrupt
+ * must have higher priority (numerically lower) than the peripheral interrupt.
+ * Otherwise the caller ISR process will be blocked. To change the SysTick interrupt
+ * priority you have to use HAL_NVIC_SetPriority() function.
+ * @param Delay : specifies the delay time length, in milliseconds.
+ * @retval None
+ */
+void HAL_Delay(__IO uint32_t Delay)
+{
+ uint32_t timingdelay;
+
+ timingdelay = HAL_GetTick() + Delay;
+ while(HAL_GetTick() < timingdelay)
+ {
+ }
+}
+
+/**
+ * @brief Returns the HAL revision
+ * @param None
+ * @retval version : 0xXYZR (8bits for each decimal, R for RC)
+ */
+uint32_t HAL_GetHalVersion(void)
+{
+ return __STM32F4xx_HAL_VERSION;
+}
+
+/**
+ * @brief Returns the device revision identifier.
+ * @param None
+ * @retval Device revision identifier
+ */
+uint32_t HAL_GetREVID(void)
+{
+ return((DBGMCU->IDCODE) >> 16);
+}
+
+/**
+ * @brief Returns the device identifier.
+ * @param None
+ * @retval Device identifier
+ */
+uint32_t HAL_GetDEVID(void)
+{
+ return((DBGMCU->IDCODE) & IDCODE_DEVID_MASK);
+}
+
+/**
+ * @brief Enable the Debug Module during SLEEP mode
+ * @param None
+ * @retval None
+ */
+void HAL_EnableDBGSleepMode(void)
+{
+ SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP);
+}
+
+/**
+ * @brief Disable the Debug Module during SLEEP mode
+ * @param None
+ * @retval None
+ */
+void HAL_DisableDBGSleepMode(void)
+{
+ CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP);
+}
+
+/**
+ * @brief Enable the Debug Module during STOP mode
+ * @param None
+ * @retval None
+ */
+void HAL_EnableDBGStopMode(void)
+{
+ SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP);
+}
+
+/**
+ * @brief Disable the Debug Module during STOP mode
+ * @param None
+ * @retval None
+ */
+void HAL_DisableDBGStopMode(void)
+{
+ CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP);
+}
+
+/**
+ * @brief Enable the Debug Module during STANDBY mode
+ * @param None
+ * @retval None
+ */
+void HAL_EnableDBGStandbyMode(void)
+{
+ SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY);
+}
+
+/**
+ * @brief Disable the Debug Module during STANDBY mode
+ * @param None
+ * @retval None
+ */
+void HAL_DisableDBGStandbyMode(void)
+{
+ CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY);
+}
+
+/**
+ * @brief Enables the I/O Compensation Cell.
+ * @note The I/O compensation cell can be used only when the device supply
+ * voltage ranges from 2.4 to 3.6 V.
+ * @retval None
+ */
+void HAL_EnableCompensationCell(void)
+{
+ *(__IO uint32_t *)CMPCR_CMP_PD_BB = (uint32_t)ENABLE;
+}
+
+/**
+ * @brief Power-down the I/O Compensation Cell.
+ * @note The I/O compensation cell can be used only when the device supply
+ * voltage ranges from 2.4 to 3.6 V.
+ * @retval None
+ */
+void HAL_DisableCompensationCell(void)
+{
+ *(__IO uint32_t *)CMPCR_CMP_PD_BB = (uint32_t)DISABLE;
+}
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx)
+/**
+ * @brief Enables the Internal FLASH Bank Swapping.
+ *
+ * @note This function can be used only for STM32F42xxx/43xxx devices.
+ *
+ * @note Flash Bank2 mapped at 0x08000000 (and aliased @0x00000000)
+ * and Flash Bank1 mapped at 0x08100000 (and aliased at 0x00100000)
+ *
+ * @retval None
+ */
+void HAL_EnableMemorySwappingBank(void)
+{
+ *(__IO uint32_t *)UFB_MODE_BB = (uint32_t)ENABLE;
+}
+
+/**
+ * @brief Disables the Internal FLASH Bank Swapping.
+ *
+ * @note This function can be used only for STM32F42xxx/43xxx devices.
+ *
+ * @note The default state : Flash Bank1 mapped at 0x08000000 (and aliased @0x0000 0000)
+ * and Flash Bank2 mapped at 0x08100000 (and aliased at 0x00100000)
+ *
+ * @retval None
+ */
+void HAL_DisableMemorySwappingBank(void)
+{
+
+ *(__IO uint32_t *)UFB_MODE_BB = (uint32_t)DISABLE;
+}
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc.c
new file mode 100644
index 0000000..bd48131
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc.c
@@ -0,0 +1,1286 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_adc.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief This file provides firmware functions to manage the following
+ * functionalities of the Analog to Digital Convertor (ADC) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + State and errors functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### ADC Peripheral features #####
+ ==============================================================================
+ [..]
+ (#) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution.
+ (#) Interrupt generation at the end of conversion, end of injected conversion,
+ and in case of analog watchdog or overrun events
+ (#) Single and continuous conversion modes.
+ (#) Scan mode for automatic conversion of channel 0 to channel x.
+ (#) Data alignment with in-built data coherency.
+ (#) Channel-wise programmable sampling time.
+ (#) External trigger option with configurable polarity for both regular and
+ injected conversion.
+ (#) Dual/Triple mode (on devices with 2 ADCs or more).
+ (#) Configurable DMA data storage in Dual/Triple ADC mode.
+ (#) Configurable delay between conversions in Dual/Triple interleaved mode.
+ (#) ADC conversion type (refer to the datasheets).
+ (#) ADC supply requirements: 2.4 V to 3.6 V at full speed and down to 1.8 V at
+ slower speed.
+ (#) ADC input range: VREF(minus) = VIN = VREF(plus).
+ (#) DMA request generation during regular channel conversion.
+
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#)Initialize the ADC low level resources by implementing the HAL_ADC_MspInit():
+ (##) Enable the ADC interface clock using __ADC_CLK_ENABLE()
+ (##) ADC pins configuration
+ (+++) Enable the clock for the ADC GPIOs using the following function:
+ __GPIOx_CLK_ENABLE()
+ (+++) Configure these ADC pins in analog mode using HAL_GPIO_Init()
+ (##) In case of using interrupts (e.g. HAL_ADC_Start_IT())
+ (+++) Configure the ADC interrupt priority using HAL_NVIC_SetPriority()
+ (+++) Enable the ADC IRQ handler using HAL_NVIC_EnableIRQ()
+ (+++) In ADC IRQ handler, call HAL_ADC_IRQHandler()
+ (##) In case of using DMA to control data transfer (e.g. HAL_ADC_Start_DMA())
+ (+++) Enable the DMAx interface clock using __DMAx_CLK_ENABLE()
+ (+++) Configure and enable two DMA streams stream for managing data
+ transfer from peripheral to memory (output stream)
+ (+++) Associate the initilalized DMA handle to the CRYP DMA handle
+ using __HAL_LINKDMA()
+ (+++) Configure the priority and enable the NVIC for the transfer complete
+ interrupt on the two DMA Streams. The output stream should have higher
+ priority than the input stream.
+
+ (#) Configure the ADC Prescaler, conversion resolution and data alignment
+ using the HAL_ADC_Init() function.
+
+ (#) Configure the ADC regular channels group features, use HAL_ADC_Init()
+ and HAL_ADC_ConfigChannel() functions.
+
+ (#) Three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Start the ADC peripheral using HAL_ADC_Start()
+ (+) Wait for end of conversion using HAL_ADC_PollForConversion(), at this stage
+ user can specify the value of timeout according to his end application
+ (+) To read the ADC converted values, use the HAL_ADC_GetValue() function.
+ (+) Stop the ADC peripheral using HAL_ADC_Stop()
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Start the ADC peripheral using HAL_ADC_Start_IT()
+ (+) Use HAL_ADC_IRQHandler() called under ADC_IRQHandler() Interrupt subroutine
+ (+) At ADC end of conversion HAL_ADC_ConvCpltCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_ADC_ConvCpltCallback
+ (+) In case of ADC Error, HAL_ADC_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_ADC_ErrorCallback
+ (+) Stop the ADC peripheral using HAL_ADC_Stop_IT()
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Start the ADC peripheral using HAL_ADC_Start_DMA(), at this stage the user specify the length
+ of data to be transfered at each end of conversion
+ (+) At The end of data transfer by HAL_ADC_ConvCpltCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_ADC_ConvCpltCallback
+ (+) In case of transfer Error, HAL_ADC_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_ADC_ErrorCallback
+ (+) Stop the ADC peripheral using HAL_ADC_Stop_DMA()
+
+ *** ADC HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in ADC HAL driver.
+
+ (+) __HAL_ADC_ENABLE : Enable the ADC peripheral
+ (+) __HAL_ADC_DISABLE : Disable the ADC peripheral
+ (+) __HAL_ADC_ENABLE_IT: Enable the ADC end of conversion interrupt
+ (+) __HAL_ADC_DISABLE_IT: Disable the ADC end of conversion interrupt
+ (+) __HAL_ADC_GET_IT_SOURCE: Check if the specified ADC interrupt source is enabled or disabled
+ (+) __HAL_ADC_CLEAR_FLAG: Clear the ADC's pending flags
+ (+) __HAL_ADC_GET_FLAG: Get the selected ADC's flag status
+ (+) __HAL_ADC_GET_RESOLUTION: Return resolution bits in CR1 register
+
+ [..]
+ (@) You can refer to the ADC HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup ADC
+ * @brief ADC driver modules
+ * @{
+ */
+
+#ifdef HAL_ADC_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void ADC_Init(ADC_HandleTypeDef* hadc);
+static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma);
+static void ADC_DMAError(DMA_HandleTypeDef *hdma);
+static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup ADC_Private_Functions
+ * @{
+ */
+
+/** @defgroup ADC_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize and configure the ADC.
+ (+) De-initialize the ADC.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the ADCx peripheral according to the specified parameters
+ * in the ADC_InitStruct and initializes the ADC MSP.
+ *
+ * @note This function is used to configure the global features of the ADC (
+ * ClockPrescaler, Resolution, Data Alignment and number of conversion), however,
+ * the rest of the configuration parameters are specific to the regular
+ * channels group (scan mode activation, continuous mode activation,
+ * External trigger source and edge, DMA continuous request after the
+ * last transfer and End of conversion selection).
+ *
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc)
+{
+ /* Check ADC handle */
+ if(hadc == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
+ assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler));
+ assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution));
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ScanConvMode));
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
+ assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
+ assert_param(IS_ADC_EXT_TRIG(hadc->Init.ExternalTrigConv));
+ assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign));
+ assert_param(IS_ADC_REGULAR_LENGTH(hadc->Init.NbrOfConversion));
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
+ assert_param(IS_ADC_EOCSelection(hadc->Init.EOCSelection));
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
+
+ if(hadc->State == HAL_ADC_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_ADC_MspInit(hadc);
+ }
+
+ /* Initialize the ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY;
+
+ /* Set ADC parameters */
+ ADC_Init(hadc);
+
+ /* Set ADC error code to none */
+ hadc->ErrorCode = HAL_ADC_ERROR_NONE;
+
+ /* Initialize the ADC state */
+ hadc->State = HAL_ADC_STATE_READY;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Deinitializes the ADCx peripheral registers to their default reset values.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc)
+{
+ /* Check ADC handle */
+ if(hadc == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_ADC_MspDeInit(hadc);
+
+ /* Set ADC error code to none */
+ hadc->ErrorCode = HAL_ADC_ERROR_NONE;
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_RESET;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the ADC MSP.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+__weak void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ADC_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the ADC MSP.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+__weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ADC_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup ADC_Group2 IO operation functions
+ * @brief IO operation functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Start conversion of regular channel.
+ (+) Stop conversion of regular channel.
+ (+) Start conversion of regular channel and enable interrupt.
+ (+) Stop conversion of regular channel and disable interrupt.
+ (+) Start conversion of regular channel and enable DMA transfer.
+ (+) Stop conversion of regular channel and disable DMA transfer.
+ (+) Handle ADC interrupt request.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables ADC and starts conversion of the regular channels.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc)
+{
+ uint16_t i = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
+ assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* Check if an injected conversion is ongoing */
+ if(hadc->State == HAL_ADC_STATE_BUSY_INJ)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_REG;
+ }
+
+ /* Check if ADC peripheral is disabled in order to enable it and wait during
+ Tstab time the ADC's stabilization */
+ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
+ {
+ /* Enable the Peripheral */
+ __HAL_ADC_ENABLE(hadc);
+
+ /* Delay inserted to wait during Tstab time the ADC's stabilazation */
+ for(; i <= 540; i++)
+ {
+ __NOP();
+ }
+ }
+
+ /* Check if Multimode enabled */
+ if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI))
+ {
+ /* if no external trigger present enable software conversion of regular channels */
+ if(hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIGCONVEDGE_NONE)
+ {
+ /* Enable the selected ADC software conversion for regular group */
+ hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
+ }
+ }
+ else
+ {
+ /* if instance of handle correspond to ADC1 and no external trigger present enable software conversion of regular channels */
+ if((hadc->Instance == ADC1) && (hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIGCONVEDGE_NONE))
+ {
+ /* Enable the selected ADC software conversion for regular group */
+ hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
+ }
+ }
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables ADC and stop conversion of regular channels.
+ *
+ * @note Caution: This function will stop also injected channels.
+ *
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * last transfer and End of conversion selection).
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc)
+{
+ /* Disable the Peripheral */
+ __HAL_ADC_DISABLE(hadc);
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Poll for regular conversion complete
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param Timeout: Timeout value in millisecond.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout)
+{
+ uint32_t timeout;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Check End of conversion flag */
+ while(!(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC)))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hadc->State= HAL_ADC_STATE_TIMEOUT;
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Check if an injected conversion is ready */
+ if(hadc->State == HAL_ADC_STATE_EOC_INJ)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_REG;
+ }
+
+ /* Return ADC state */
+ return HAL_OK;
+}
+
+/**
+ * @brief Poll for conversion event
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param EventType: the ADC event type.
+ * This parameter can be one of the following values:
+ * @arg AWD_EVENT: ADC Analog watch Dog event.
+ * @arg OVR_EVENT: ADC Overrun event.
+ * @param Timeout: Timeout value in millisecond.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout)
+{
+ /* Check the parameters */
+ assert_param(IS_ADC_EVENT_TYPE(EventType));
+
+ uint32_t timeout;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Check selected event flag */
+ while(!(__HAL_ADC_GET_FLAG(hadc,EventType)))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hadc->State= HAL_ADC_STATE_TIMEOUT;
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Check analog watchdog flag */
+ if(EventType == AWD_EVENT)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_AWD;
+
+ /* Clear the ADCx's analog watchdog flag */
+ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD);
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_ERROR;
+
+ /* Clear the ADCx's Overrun flag */
+ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
+ }
+
+ /* Return ADC state */
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Enables the interrupt and starts ADC conversion of regular channels.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc)
+{
+ uint16_t i = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
+ assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* Check if an injected conversion is ongoing */
+ if(hadc->State == HAL_ADC_STATE_BUSY_INJ)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_REG;
+ }
+
+ /* Set ADC error code to none */
+ hadc->ErrorCode = HAL_ADC_ERROR_NONE;
+
+ /* Check if ADC peripheral is disabled in order to enable it and wait during
+ Tstab time the ADC's stabilization */
+ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
+ {
+ /* Enable the Peripheral */
+ __HAL_ADC_ENABLE(hadc);
+
+ /* Delay inserted to wait during Tstab time the ADC's stabilazation */
+ for(; i <= 540; i++)
+ {
+ __NOP();
+ }
+ }
+
+ /* Enable the ADC overrun interrupt */
+ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
+
+ /* Enable the ADC end of conversion interrupt for regular group */
+ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOC);
+
+ /* Check if Multimode enabled */
+ if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI))
+ {
+ /* if no externel trigger present enable software conversion of regular channels */
+ if (hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIGCONVEDGE_NONE)
+ {
+ /* Enable the selected ADC software conversion for regular group */
+ hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
+ }
+ }
+ else
+ {
+ /* if instance of handle correspond to ADC1 and no external trigger present enable software conversion of regular channels */
+ if ((hadc->Instance == (ADC_TypeDef*)0x40012000) && (hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIGCONVEDGE_NONE))
+ {
+ /* Enable the selected ADC software conversion for regular group */
+ hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
+ }
+ }
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables the interrupt and stop ADC conversion of regular channels.
+ *
+ * @note Caution: This function will stop also injected channels.
+ *
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc)
+{
+ /* Disable the ADC end of conversion interrupt for regular group */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
+
+ /* Disable the ADC end of conversion interrupt for injected group */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_CR1_JEOCIE);
+
+ /* Enable the Periphral */
+ __HAL_ADC_DISABLE(hadc);
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Handles ADC interrupt request
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
+ assert_param(IS_ADC_REGULAR_LENGTH(hadc->Init.NbrOfConversion));
+ assert_param(IS_ADC_EOCSelection(hadc->Init.EOCSelection));
+
+ tmp1 = __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC);
+ tmp2 = __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOC);
+ /* Check End of conversion flag for regular channels */
+ if(tmp1 && tmp2)
+ {
+ /* Check if an injected conversion is ready */
+ if(hadc->State == HAL_ADC_STATE_EOC_INJ)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_REG;
+ }
+
+ if((hadc->Init.ContinuousConvMode == DISABLE) && (hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIGCONVEDGE_NONE))
+ {
+ if(hadc->Init.EOCSelection == EOC_SEQ_CONV)
+ {
+ /* DISABLE the ADC end of conversion interrupt for regular group */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
+
+ /* DISABLE the ADC overrun interrupt */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
+ }
+ else
+ {
+ if (hadc->NbrOfCurrentConversionRank == 0)
+ {
+ hadc->NbrOfCurrentConversionRank = hadc->Init.NbrOfConversion;
+ }
+
+ /* Decrement the number of conversion when an interrupt occurs */
+ hadc->NbrOfCurrentConversionRank--;
+
+ /* Check if all conversions are finished */
+ if(hadc->NbrOfCurrentConversionRank == 0)
+ {
+ /* DISABLE the ADC end of conversion interrupt for regular group */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
+
+ /* DISABLE the ADC overrun interrupt */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
+ }
+ }
+ }
+
+ /* Conversion complete callback */
+ HAL_ADC_ConvCpltCallback(hadc);
+
+ /* Clear the ADCx flag for regular end of conversion */
+ __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_EOC);
+ }
+
+ tmp1 = __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOC);
+ tmp2 = __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_JEOC);
+ /* Check End of conversion flag for injected channels */
+ if(tmp1 && tmp2)
+ {
+ /* Check if a regular conversion is ready */
+ if(hadc->State == HAL_ADC_STATE_EOC_REG)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_INJ;
+ }
+
+ tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO);
+ tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN);
+ if(((hadc->Init.ContinuousConvMode == DISABLE) || tmp1) && tmp2)
+ {
+ /* DISABLE the ADC end of conversion interrupt for injected group */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
+ }
+
+ /* Conversion complete callback */
+ HAL_ADCEx_InjectedConvCpltCallback(hadc);
+
+ /* Clear the ADCx flag for injected end of conversion */
+ __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_JEOC);
+ }
+
+ tmp1 = __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_AWD);
+ tmp2 = __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_AWD);
+ /* Check Analog watchdog flag */
+ if(tmp1 && tmp2)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_AWD;
+
+ /* Clear the ADCx's Analog watchdog flag */
+ __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_AWD);
+
+ /* Level out of window callback */
+ HAL_ADC_LevelOutOfWindowCallback(hadc);
+ }
+
+ tmp1 = __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_OVR);
+ tmp2 = __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_OVR);
+ /* Check Overrun flag */
+ if(tmp1 && tmp2)
+ {
+ /* Change ADC state to overrun state */
+ hadc->State = HAL_ADC_STATE_ERROR;
+
+ /* Set ADC error code to overrun */
+ hadc->ErrorCode |= HAL_ADC_ERROR_OVR;
+
+ /* Clear the Overrun flag */
+ __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_OVR);
+
+ /* Error callback */
+ HAL_ADC_ErrorCallback(hadc);
+ }
+}
+
+/**
+ * @brief Enables ADC DMA request after last transfer (Single-ADC mode) and enables ADC peripheral
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param pData: The destination Buffer address.
+ * @param Length: The length of data to be transferred from ADC peripheral to memory.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length)
+{
+ uint16_t i = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
+ assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* Enable ADC overrun interrupt */
+ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
+
+ /* Enable ADC DMA mode */
+ hadc->Instance->CR2 |= ADC_CR2_DMA;
+
+ /* Set the DMA transfer complete callback */
+ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
+
+ /* Set the DMA half transfer complete callback */
+ hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
+
+ /* Set the DMA error callback */
+ hadc->DMA_Handle->XferErrorCallback = ADC_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_REG;
+
+ /* Check if ADC peripheral is disabled in order to enable it and wait during
+ Tstab time the ADC's stabilization */
+ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
+ {
+ /* Enable the Peripheral */
+ __HAL_ADC_ENABLE(hadc);
+
+ /* Delay inserted to wait during Tstab time the ADC's stabilazation */
+ for(; i <= 540; i++)
+ {
+ __NOP();
+ }
+ }
+
+ /* if no external trigger present enable software conversion of regular channels */
+ if (hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIGCONVEDGE_NONE)
+ {
+ /* Enable the selected ADC software conversion for regular group */
+ hadc->Instance->CR2 |= ADC_CR2_SWSTART;
+ }
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables ADC DMA (Single-ADC mode) and disables ADC peripheral
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc)
+{
+ /* Disable the Periphral */
+ __HAL_ADC_DISABLE(hadc);
+
+ /* Disable ADC overrun interrupt */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
+
+ /* Disable the selected ADC DMA mode */
+ hadc->Instance->CR2 &= ~ADC_CR2_DMA;
+
+ /* Disable the ADC DMA Stream */
+ HAL_DMA_Abort(hadc->DMA_Handle);
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Gets the converted value from data register of regular channel.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval Converted value
+ */
+uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc)
+{
+ /* Return the selected ADC converted value */
+ return hadc->Instance->DR;
+}
+
+/**
+ * @brief Regular conversion complete callback in non blocking mode
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+__weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ADC_ConvCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Regular conversion half DMA transfer callback in non blocking mode
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+__weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ADC_ConvHalfCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Analog watchdog callback in non blocking mode
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+__weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ADC_LevelOoutOfWindowCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Error ADC callback.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+__weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ADC_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup ADC_Group3 Peripheral Control functions
+ * @brief Peripheral Control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Configure regular channels.
+ (+) Configure injected channels.
+ (+) Configure multimode.
+ (+) Configure the analog watch dog.
+
+@endverbatim
+ * @{
+ */
+
+ /**
+ * @brief Configures for the selected ADC regular channel its corresponding
+ * rank in the sequencer and its sample time.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param sConfig: ADC configuration structure.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig)
+{
+ /* Check the parameters */
+ assert_param(IS_ADC_CHANNEL(sConfig->Channel));
+ assert_param(IS_ADC_REGULAR_RANK(sConfig->Rank));
+ assert_param(IS_ADC_SAMPLE_TIME(sConfig->SamplingTime));
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* if ADC_Channel_10 ... ADC_Channel_18 is selected */
+ if (sConfig->Channel > ADC_CHANNEL_9)
+ {
+ /* Clear the old sample time */
+ hadc->Instance->SMPR1 &= ~__HAL_ADC_SMPR1(ADC_SMPR1_SMP10, sConfig->Channel);
+
+ /* Set the new sample time */
+ hadc->Instance->SMPR1 |= __HAL_ADC_SMPR1(sConfig->SamplingTime, sConfig->Channel);
+ }
+ else /* ADC_Channel include in ADC_Channel_[0..9] */
+ {
+ /* Clear the old sample time */
+ hadc->Instance->SMPR2 &= ~__HAL_ADC_SMPR2(ADC_SMPR2_SMP0, sConfig->Channel);
+
+ /* Set the new sample time */
+ hadc->Instance->SMPR2 |= __HAL_ADC_SMPR2(sConfig->SamplingTime, sConfig->Channel);
+ }
+
+ /* For Rank 1 to 6 */
+ if (sConfig->Rank < 7)
+ {
+ /* Clear the old SQx bits for the selected rank */
+ hadc->Instance->SQR3 &= ~__HAL_ADC_SQR3_RK(ADC_SQR3_SQ1, sConfig->Rank);
+
+ /* Set the SQx bits for the selected rank */
+ hadc->Instance->SQR3 |= __HAL_ADC_SQR3_RK(sConfig->Channel, sConfig->Rank);
+ }
+ /* For Rank 7 to 12 */
+ else if (sConfig->Rank < 13)
+ {
+ /* Clear the old SQx bits for the selected rank */
+ hadc->Instance->SQR2 &= ~__HAL_ADC_SQR2_RK(ADC_SQR2_SQ7, sConfig->Rank);
+
+ /* Set the SQx bits for the selected rank */
+ hadc->Instance->SQR2 |= __HAL_ADC_SQR2_RK(sConfig->Channel, sConfig->Rank);
+ }
+ /* For Rank 13 to 16 */
+ else
+ {
+ /* Clear the old SQx bits for the selected rank */
+ hadc->Instance->SQR1 &= ~__HAL_ADC_SQR1_RK(ADC_SQR1_SQ13, sConfig->Rank);
+
+ /* Set the SQx bits for the selected rank */
+ hadc->Instance->SQR1 |= __HAL_ADC_SQR1_RK(sConfig->Channel, sConfig->Rank);
+ }
+
+ /* if ADC1 Channel_18 is selected enable VBAT Channel */
+ if ((hadc->Instance == ADC1) && (sConfig->Channel == ADC_CHANNEL_VBAT))
+ {
+ /* Enable the VBAT channel*/
+ ADC->CCR |= ADC_CCR_VBATE;
+ }
+
+ /* if ADC1 Channel_16 or Channel_17 is selected enable TSVREFE Channel(Temperature sensor and VREFINT) */
+ if ((hadc->Instance == ADC1) && ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) || (sConfig->Channel == ADC_CHANNEL_VREFINT)))
+ {
+ /* Enable the TSVREFE channel*/
+ ADC->CCR |= ADC_CCR_TSVREFE;
+ }
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the analog watchdog.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param AnalogWDGConfig : pointer to an ADC_AnalogWDGConfTypeDef structure
+ * that contains the configuration information of ADC analog watchdog.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig)
+{
+#ifdef USE_FULL_ASSERT
+ uint32_t tmp = 0;
+#endif /* USE_FULL_ASSERT */
+
+ /* Check the parameters */
+ assert_param(IS_ADC_ANALOG_WATCHDOG(AnalogWDGConfig->WatchdogMode));
+ assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel));
+ assert_param(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode));
+
+#ifdef USE_FULL_ASSERT
+ tmp = __HAL_ADC_GET_RESOLUTION(hadc);
+ assert_param(IS_ADC_RANGE(tmp, AnalogWDGConfig->HighThreshold));
+ assert_param(IS_ADC_RANGE(tmp, AnalogWDGConfig->LowThreshold));
+#endif /* USE_FULL_ASSERT */
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ if(AnalogWDGConfig->ITMode == ENABLE)
+ {
+ /* Enable the ADC Analog watchdog interrupt */
+ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_AWD);
+ }
+ else
+ {
+ /* Disable the ADC Analog watchdog interrupt */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_AWD);
+ }
+
+ /* Clear AWDEN, JAWDEN and AWDSGL bits */
+ hadc->Instance->CR1 &= ~(ADC_CR1_AWDSGL | ADC_CR1_JAWDEN | ADC_CR1_AWDEN);
+
+ /* Set the analog watchdog enable mode */
+ hadc->Instance->CR1 |= AnalogWDGConfig->WatchdogMode;
+
+ /* Set the high threshold */
+ hadc->Instance->HTR = AnalogWDGConfig->HighThreshold;
+
+ /* Set the low threshold */
+ hadc->Instance->LTR = AnalogWDGConfig->LowThreshold;
+
+ /* Clear the Analog watchdog channel select bits */
+ hadc->Instance->CR1 &= ~ADC_CR1_AWDCH;
+
+ /* Set the Analog watchdog channel */
+ hadc->Instance->CR1 |= AnalogWDGConfig->Channel;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup ADC_Group4 ADC Peripheral State functions
+ * @brief ADC Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State and errors functions #####
+ ===============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Check the ADC state
+ (+) Check the ADC Error
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief return the ADC state
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval HAL state
+ */
+HAL_ADC_StateTypeDef HAL_ADC_GetState(ADC_HandleTypeDef* hadc)
+{
+ /* Return ADC state */
+ return hadc->State;
+}
+
+/**
+ * @brief Return the ADC error code
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval ADC Error Code
+ */
+uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc)
+{
+ return hadc->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Initializes the ADCx peripheral according to the specified parameters
+ * in the ADC_InitStruct without initializing the ADC MSP.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+static void ADC_Init(ADC_HandleTypeDef* hadc)
+{
+
+ /* Set ADC parameters */
+ /* Set the ADC clock prescaler */
+ ADC->CCR &= ~(ADC_CCR_ADCPRE);
+ ADC->CCR |= hadc->Init.ClockPrescaler;
+
+ /* Set ADC scan mode */
+ hadc->Instance->CR1 &= ~(ADC_CR1_SCAN);
+ hadc->Instance->CR1 |= __HAL_ADC_CR1_SCANCONV(hadc->Init.ScanConvMode);
+
+ /* Set ADC resolution */
+ hadc->Instance->CR1 &= ~(ADC_CR1_RES);
+ hadc->Instance->CR1 |= hadc->Init.Resolution;
+
+ /* Set ADC data alignment */
+ hadc->Instance->CR2 &= ~(ADC_CR2_ALIGN);
+ hadc->Instance->CR2 |= hadc->Init.DataAlign;
+
+ /* Select external trigger to start conversion */
+ hadc->Instance->CR2 &= ~(ADC_CR2_EXTSEL);
+ hadc->Instance->CR2 |= hadc->Init.ExternalTrigConv;
+
+ /* Select external trigger polarity */
+ hadc->Instance->CR2 &= ~(ADC_CR2_EXTEN);
+ hadc->Instance->CR2 |= hadc->Init.ExternalTrigConvEdge;
+
+ /* Enable or disable ADC continuous conversion mode */
+ hadc->Instance->CR2 &= ~(ADC_CR2_CONT);
+ hadc->Instance->CR2 |= __HAL_ADC_CR2_CONTINUOUS(hadc->Init.ContinuousConvMode);
+
+ if (hadc->Init.DiscontinuousConvMode != DISABLE)
+ {
+ assert_param(IS_ADC_REGULAR_DISC_NUMBER(hadc->Init.NbrOfDiscConversion));
+
+ /* Enable the selected ADC regular discontinuous mode */
+ hadc->Instance->CR1 |= (uint32_t)ADC_CR1_DISCEN;
+
+ /* Set the number of channels to be converted in discontinuous mode */
+ hadc->Instance->CR1 &= ~(ADC_CR1_DISCNUM);
+ hadc->Instance->CR1 |= __HAL_ADC_CR1_DISCONTINUOUS(hadc->Init.NbrOfDiscConversion);
+ }
+ else
+ {
+ /* Disable the selected ADC regular discontinuous mode */
+ hadc->Instance->CR1 &= ~(ADC_CR1_DISCEN);
+ }
+
+ /* Set ADC number of conversion */
+ hadc->Instance->SQR1 &= ~(ADC_SQR1_L);
+ hadc->Instance->SQR1 |= __HAL_ADC_SQR1(hadc->Init.NbrOfConversion);
+
+ /* Enable or disable ADC DMA continuous request */
+ hadc->Instance->CR2 &= ~(ADC_CR2_DDS);
+ hadc->Instance->CR2 |= __HAL_ADC_CR2_DMAContReq(hadc->Init.DMAContinuousRequests);
+
+ /* Enable or disable ADC end of conversion selection */
+ hadc->Instance->CR2 &= ~(ADC_CR2_EOCS);
+ hadc->Instance->CR2 |= __HAL_ADC_CR2_EOCSelection(hadc->Init.EOCSelection);
+}
+
+/**
+ * @brief DMA transfer complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
+{
+ ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ /* Check if an injected conversion is ready */
+ if(hadc->State == HAL_ADC_STATE_EOC_INJ)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_REG;
+ }
+
+ HAL_ADC_ConvCpltCallback(hadc);
+}
+
+/**
+ * @brief DMA half transfer complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
+{
+ ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ /* Conversion complete callback */
+ HAL_ADC_ConvHalfCpltCallback(hadc);
+}
+
+/**
+ * @brief DMA error callback
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void ADC_DMAError(DMA_HandleTypeDef *hdma)
+{
+ ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ hadc->State= HAL_ADC_STATE_ERROR;
+ /* Set ADC error code to DMA error */
+ hadc->ErrorCode |= HAL_ADC_ERROR_DMA;
+ HAL_ADC_ErrorCallback(hadc);
+}
+
+
+/**
+ * @}
+ */
+
+#endif /* HAL_ADC_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc_ex.c
new file mode 100644
index 0000000..d00e35a
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc_ex.c
@@ -0,0 +1,838 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_adc_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief This file provides firmware functions to manage the following
+ * functionalities of the ADC extension peripheral:
+ * + Extended features functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#)Initialize the ADC low level resources by implementing the HAL_ADC_MspInit():
+ (##) Enable the ADC interface clock using __ADC_CLK_ENABLE()
+ (##) ADC pins configuration
+ (+++) Enable the clock for the ADC GPIOs using the following function:
+ __GPIOx_CLK_ENABLE()
+ (+++) Configure these ADC pins in analog mode using HAL_GPIO_Init()
+ (##) In case of using interrupts (e.g. HAL_ADC_Start_IT())
+ (+++) Configure the ADC interrupt priority using HAL_NVIC_SetPriority()
+ (+++) Enable the ADC IRQ handler using HAL_NVIC_EnableIRQ()
+ (+++) In ADC IRQ handler, call HAL_ADC_IRQHandler()
+ (##) In case of using DMA to control data transfer (e.g. HAL_ADC_Start_DMA())
+ (++) Enable the DMAx interface clock using __DMAx_CLK_ENABLE()
+ (++) Configure and enable two DMA streams stream for managing data
+ transfer from peripheral to memory (output stream)
+ (++) Associate the initilalized DMA handle to the CRYP DMA handle
+ using __HAL_LINKDMA()
+ (++) Configure the priority and enable the NVIC for the transfer complete
+ interrupt on the two DMA Streams. The output stream should have higher
+ priority than the input stream.
+
+ (#) Configure the ADC Prescaler, conversion resolution and data alignment
+ using the HAL_ADC_Init() function.
+
+ (#) Configure the ADC Injected channels group features, use HAL_ADC_Init()
+ and HAL_ADC_ConfigChannel() functions.
+
+ (#) Three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Start the ADC peripheral using HAL_ADCEx_InjectedStart()
+ (+) Wait for end of conversion using HAL_ADC_PollForConversion(), at this stage
+ user can specify the value of timeout according to his end application
+ (+) To read the ADC converted values, use the HAL_ADCEx_InjectedGetValue() function.
+ (+) Stop the ADC peripheral using HAL_ADCEx_InjectedStop()
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Start the ADC peripheral using HAL_ADCEx_InjectedStart_IT()
+ (+) Use HAL_ADC_IRQHandler() called under ADC_IRQHandler() Interrupt subroutine
+ (+) At ADC end of conversion HAL_ADCEx_InjectedConvCpltCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_ADCEx_InjectedConvCpltCallback
+ (+) In case of ADC Error, HAL_ADCEx_InjectedErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_ADCEx_InjectedErrorCallback
+ (+) Stop the ADC peripheral using HAL_ADCEx_InjectedStop_IT()
+
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Start the ADC peripheral using HAL_ADCEx_InjectedStart_DMA(), at this stage the user specify the length
+ of data to be transfered at each end of conversion
+ (+) At The end of data transfer ba HAL_ADCEx_InjectedConvCpltCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_ADCEx_InjectedConvCpltCallback
+ (+) In case of transfer Error, HAL_ADCEx_InjectedErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_ADCEx_InjectedErrorCallback
+ (+) Stop the ADC peripheral using HAL_ADCEx_InjectedStop_DMA()
+
+ *** Multi mode ADCs Regular channels configuration ***
+ ======================================================
+ [..]
+ (+) Select the Multi mode ADC regular channels features (dual or triple mode)
+ and configure the DMA mode using HAL_ADCEx_MultiModeConfigChannel() functions.
+ (+) Start the ADC peripheral using HAL_ADCEx_MultiModeStart_DMA(), at this stage the user specify the length
+ of data to be transfered at each end of conversion
+ (+) Read the ADCs converted values using the HAL_ADCEx_MultiModeGetValue() function.
+
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup ADCEx
+ * @brief ADC Extended driver modules
+ * @{
+ */
+
+#ifdef HAL_ADC_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void ADC_MultiModeDMAConvCplt(DMA_HandleTypeDef *hdma);
+static void ADC_MultiModeDMAError(DMA_HandleTypeDef *hdma);
+static void ADC_MultiModeDMAHalfConvCplt(DMA_HandleTypeDef *hdma);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup ADCEx_Private_Functions
+ * @{
+ */
+
+/** @defgroup ADCEx_Group1 Extended features functions
+ * @brief Extended features functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Extended features functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Start conversion of injected channel.
+ (+) Stop conversion of injected channel.
+ (+) Start multimode and enable DMA transfer.
+ (+) Stop multimode and disable DMA transfer.
+ (+) Get result of injected channel conversion.
+ (+) Get result of multimode conversion.
+ (+) Configure injected channels.
+ (+) Configure multimode.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables the selected ADC software start conversion of the injected channels.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc)
+{
+ uint32_t i = 0, tmp1 = 0, tmp2 = 0;
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* Check if a regular conversion is ongoing */
+ if(hadc->State == HAL_ADC_STATE_BUSY_REG)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_INJ;
+ }
+
+ /* Check if ADC peripheral is disabled in order to enable it and wait during
+ Tstab time the ADC's stabilization */
+ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
+ {
+ /* Enable the Peripheral */
+ __HAL_ADC_ENABLE(hadc);
+
+ /* Delay inserted to wait during Tstab time the ADC's stabilazation */
+ for(; i <= 540; i++)
+ {
+ __NOP();
+ }
+ }
+
+ /* Check if Multimode enabled */
+ if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI))
+ {
+ tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN);
+ tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO);
+ if(tmp1 && tmp2)
+ {
+ /* Enable the selected ADC software conversion for injected group */
+ hadc->Instance->CR2 |= ADC_CR2_JSWSTART;
+ }
+ }
+ else
+ {
+ tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN);
+ tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO);
+ if((hadc->Instance == ADC1) && tmp1 && tmp2)
+ {
+ /* Enable the selected ADC software conversion for injected group */
+ hadc->Instance->CR2 |= ADC_CR2_JSWSTART;
+ }
+ }
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Enables the interrupt and starts ADC conversion of injected channels.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ *
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc)
+{
+ uint32_t i = 0, tmp1 = 0, tmp2 =0;
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* Check if a regular conversion is ongoing */
+ if(hadc->State == HAL_ADC_STATE_BUSY_REG)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_INJ;
+ }
+
+ /* Set ADC error code to none */
+ hadc->ErrorCode = HAL_ADC_ERROR_NONE;
+
+ /* Check if ADC peripheral is disabled in order to enable it and wait during
+ Tstab time the ADC's stabilization */
+ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
+ {
+ /* Enable the Peripheral */
+ __HAL_ADC_ENABLE(hadc);
+
+ /* Delay inserted to wait during Tstab time the ADC's stabilazation */
+ for(; i <= 540; i++)
+ {
+ __NOP();
+ }
+ }
+
+ /* Enable the ADC end of conversion interrupt for injected group */
+ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
+
+ /* Enable the ADC overrun interrupt */
+ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
+
+ /* Check if Multimode enabled */
+ if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI))
+ {
+ tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN);
+ tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO);
+ if(tmp1 && tmp2)
+ {
+ /* Enable the selected ADC software conversion for injected group */
+ hadc->Instance->CR2 |= ADC_CR2_JSWSTART;
+ }
+ }
+ else
+ {
+ tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN);
+ tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO);
+ if((hadc->Instance == ADC1) && tmp1 && tmp2)
+ {
+ /* Enable the selected ADC software conversion for injected group */
+ hadc->Instance->CR2 |= ADC_CR2_JSWSTART;
+ }
+ }
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables ADC and stop conversion of injected channels.
+ *
+ * @note Caution: This function will stop also regular channels.
+ *
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef* hadc)
+{
+ /* Disable the Peripheral */
+ __HAL_ADC_DISABLE(hadc);
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Poll for injected conversion complete
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param Timeout: Timeout value in millisecond.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout)
+{
+ uint32_t timeout;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Check End of conversion flag */
+ while(!(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOC)))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hadc->State= HAL_ADC_STATE_TIMEOUT;
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Check if a regular conversion is ready */
+ if(hadc->State == HAL_ADC_STATE_EOC_REG)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_INJ;
+ }
+
+ /* Return ADC state */
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables the interrupt and stop ADC conversion of injected channels.
+ *
+ * @note Caution: This function will stop also regular channels.
+ *
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc)
+{
+ /* Disable the ADC end of conversion interrupt for regular group */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
+
+ /* Disable the ADC end of conversion interrupt for injected group */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_CR1_JEOCIE);
+
+ /* Enable the Periphral */
+ __HAL_ADC_DISABLE(hadc);
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Gets the converted value from data register of injected channel.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param InjectedRank: the ADC injected rank.
+ * This parameter can be one of the following values:
+ * @arg ADC_InjectedChannel_1: Injected Channel1 selected
+ * @arg ADC_InjectedChannel_2: Injected Channel2 selected
+ * @arg ADC_InjectedChannel_3: Injected Channel3 selected
+ * @arg ADC_InjectedChannel_4: Injected Channel4 selected
+ * @retval None
+ */
+uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank)
+{
+ __IO uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_ADC_INJECTED_RANK(InjectedRank));
+
+ /* Clear the ADCx's flag for injected end of conversion */
+ __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_JEOC);
+
+ /* Return the selected ADC converted value */
+ switch(InjectedRank)
+ {
+ case ADC_INJECTED_RANK_4:
+ {
+ tmp = hadc->Instance->JDR4;
+ }
+ break;
+ case ADC_INJECTED_RANK_3:
+ {
+ tmp = hadc->Instance->JDR3;
+ }
+ break;
+ case ADC_INJECTED_RANK_2:
+ {
+ tmp = hadc->Instance->JDR2;
+ }
+ break;
+ case ADC_INJECTED_RANK_1:
+ {
+ tmp = hadc->Instance->JDR1;
+ }
+ break;
+ default:
+ break;
+ }
+ return tmp;
+}
+
+/**
+ * @brief Enables ADC DMA request after last transfer (Multi-ADC mode) and enables ADC peripheral
+ *
+ * @note Caution: This function must be used only with the ADC master.
+ *
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param pData: Pointer to buffer in which transferred from ADC peripheral to memory will be stored.
+ * @param Length: The length of data to be transferred from ADC peripheral to memory.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length)
+{
+ uint16_t counter = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
+ assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
+ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* Enable ADC overrun interrupt */
+ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
+
+ if (hadc->Init.DMAContinuousRequests != DISABLE)
+ {
+ /* Enable the selected ADC DMA request after last transfer */
+ ADC->CCR |= ADC_CCR_DDS;
+ }
+ else
+ {
+ /* Disable the selected ADC EOC rising on each regular channel conversion */
+ ADC->CCR &= ~ADC_CCR_DDS;
+ }
+
+ /* Set the DMA transfer complete callback */
+ hadc->DMA_Handle->XferCpltCallback = ADC_MultiModeDMAConvCplt;
+
+ /* Set the DMA half transfer complete callback */
+ hadc->DMA_Handle->XferHalfCpltCallback = ADC_MultiModeDMAHalfConvCplt;
+
+ /* Set the DMA error callback */
+ hadc->DMA_Handle->XferErrorCallback = ADC_MultiModeDMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&ADC->CDR, (uint32_t)pData, Length);
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_BUSY_REG;
+
+ /* Check if ADC peripheral is disabled in order to enable it and wait during
+ Tstab time the ADC's stabilization */
+ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
+ {
+ /* Enable the Peripheral */
+ __HAL_ADC_ENABLE(hadc);
+
+ /* Delay inserted to wait during Tstab time the ADC's stabilazation */
+ for(; counter <= 540; counter++)
+ {
+ __NOP();
+ }
+ }
+
+ /* if no external trigger present enable software conversion of regular channels */
+ if (hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIGCONVEDGE_NONE)
+ {
+ /* Enable the selected ADC software conversion for regular group */
+ hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
+ }
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables ADC DMA (multi-ADC mode) and disables ADC peripheral
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc)
+{
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* Enable the Peripheral */
+ __HAL_ADC_DISABLE(hadc);
+
+ /* Disable ADC overrun interrupt */
+ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
+
+ /* Disable the selected ADC DMA request after last transfer */
+ ADC->CCR &= ~ADC_CCR_DDS;
+
+ /* Disable the ADC DMA Stream */
+ HAL_DMA_Abort(hadc->DMA_Handle);
+
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Returns the last ADC1, ADC2 and ADC3 regular conversions results
+ * data in the selected multi mode.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval The converted data value.
+ */
+uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc)
+{
+ /* Return the multi mode conversion value */
+ return ADC->CDR;
+}
+
+/**
+ * @brief Injected conversion complete callback in non blocking mode
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @retval None
+ */
+__weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ADC_InjectedConvCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Configures for the selected ADC injected channel its corresponding
+ * rank in the sequencer and its sample time.
+ * @param hadc: pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param sConfigInjected: ADC configuration structure for injected channel.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_InjectionConfTypeDef* sConfigInjected)
+{
+
+#ifdef USE_FULL_ASSERT
+ uint32_t tmp = 0;
+#endif /* USE_FULL_ASSERT */
+
+ /* Check the parameters */
+ assert_param(IS_ADC_CHANNEL(sConfigInjected->InjectedChannel));
+ assert_param(IS_ADC_INJECTED_RANK(sConfigInjected->InjectedRank));
+ assert_param(IS_ADC_SAMPLE_TIME(sConfigInjected->InjectedSamplingTime));
+ assert_param(IS_ADC_EXT_INJEC_TRIG(sConfigInjected->ExternalTrigInjecConv));
+ assert_param(IS_ADC_EXT_INJEC_TRIG_EDGE(sConfigInjected->ExternalTrigInjecConvEdge));
+ assert_param(IS_ADC_INJECTED_LENGTH(sConfigInjected->InjectedNbrOfConversion));
+ assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->AutoInjectedConv));
+ assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->InjectedDiscontinuousConvMode));
+
+#ifdef USE_FULL_ASSERT
+ tmp = __HAL_ADC_GET_RESOLUTION(hadc);
+ assert_param(IS_ADC_RANGE(tmp, sConfigInjected->InjectedOffset));
+#endif /* USE_FULL_ASSERT */
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* if ADC_Channel_10 ... ADC_Channel_18 is selected */
+ if (sConfigInjected->InjectedChannel > ADC_CHANNEL_9)
+ {
+ /* Clear the old sample time */
+ hadc->Instance->SMPR1 &= ~__HAL_ADC_SMPR1(ADC_SMPR1_SMP10, sConfigInjected->InjectedChannel);
+
+ /* Set the new sample time */
+ hadc->Instance->SMPR1 |= __HAL_ADC_SMPR1(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel);
+ }
+ else /* ADC_Channel include in ADC_Channel_[0..9] */
+ {
+ /* Clear the old sample time */
+ hadc->Instance->SMPR2 &= ~__HAL_ADC_SMPR2(ADC_SMPR2_SMP0, sConfigInjected->InjectedChannel);
+
+ /* Set the new sample time */
+ hadc->Instance->SMPR2 |= __HAL_ADC_SMPR2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel);
+ }
+
+ /*---------------------------- ADCx JSQR Configuration -----------------*/
+ hadc->Instance->JSQR &= ~(ADC_JSQR_JL);
+ hadc->Instance->JSQR |= __HAL_ADC_SQR1(sConfigInjected->InjectedNbrOfConversion);
+
+ /* Rank configuration */
+
+ /* Clear the old SQx bits for the selected rank */
+ hadc->Instance->JSQR &= ~__HAL_ADC_JSQR(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank,sConfigInjected->InjectedNbrOfConversion);
+
+ /* Set the SQx bits for the selected rank */
+ hadc->Instance->JSQR |= __HAL_ADC_JSQR(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank,sConfigInjected->InjectedNbrOfConversion);
+
+ /* Select external trigger to start conversion */
+ hadc->Instance->CR2 &= ~(ADC_CR2_JEXTSEL);
+ hadc->Instance->CR2 |= sConfigInjected->ExternalTrigInjecConv;
+
+ /* Select external trigger polarity */
+ hadc->Instance->CR2 &= ~(ADC_CR2_JEXTEN);
+ hadc->Instance->CR2 |= sConfigInjected->ExternalTrigInjecConvEdge;
+
+ if (sConfigInjected->AutoInjectedConv != DISABLE)
+ {
+ /* Enable the selected ADC automatic injected group conversion */
+ hadc->Instance->CR1 |= ADC_CR1_JAUTO;
+ }
+ else
+ {
+ /* Disable the selected ADC automatic injected group conversion */
+ hadc->Instance->CR1 &= ~(ADC_CR1_JAUTO);
+ }
+
+ if (sConfigInjected->InjectedDiscontinuousConvMode != DISABLE)
+ {
+ /* Enable the selected ADC injected discontinuous mode */
+ hadc->Instance->CR1 |= ADC_CR1_JDISCEN;
+ }
+ else
+ {
+ /* Disable the selected ADC injected discontinuous mode */
+ hadc->Instance->CR1 &= ~(ADC_CR1_JDISCEN);
+ }
+
+ switch(sConfigInjected->InjectedRank)
+ {
+ case 1:
+ /* Set injected channel 1 offset */
+ hadc->Instance->JOFR1 &= ~(ADC_JOFR1_JOFFSET1);
+ hadc->Instance->JOFR1 |= sConfigInjected->InjectedOffset;
+ break;
+ case 2:
+ /* Set injected channel 2 offset */
+ hadc->Instance->JOFR2 &= ~(ADC_JOFR2_JOFFSET2);
+ hadc->Instance->JOFR2 |= sConfigInjected->InjectedOffset;
+ break;
+ case 3:
+ /* Set injected channel 3 offset */
+ hadc->Instance->JOFR3 &= ~(ADC_JOFR3_JOFFSET3);
+ hadc->Instance->JOFR3 |= sConfigInjected->InjectedOffset;
+ break;
+ default:
+ /* Set injected channel 4 offset */
+ hadc->Instance->JOFR4 &= ~(ADC_JOFR4_JOFFSET4);
+ hadc->Instance->JOFR4 |= sConfigInjected->InjectedOffset;
+ break;
+ }
+
+ /* if ADC1 Channel_18 is selected enable VBAT Channel */
+ if ((hadc->Instance == ADC1) && (sConfigInjected->InjectedChannel == ADC_CHANNEL_VBAT))
+ {
+ /* Enable the VBAT channel*/
+ ADC->CCR |= ADC_CCR_VBATE;
+ }
+
+ /* if ADC1 Channel_16 or Channel_17 is selected enable TSVREFE Channel(Temperature sensor and VREFINT) */
+ if ((hadc->Instance == ADC1) && ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR) || (sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT)))
+ {
+ /* Enable the TSVREFE channel*/
+ ADC->CCR |= ADC_CCR_TSVREFE;
+ }
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the ADC multi-mode
+ * @param hadc : pointer to a ADC_HandleTypeDef structure that contains
+ * the configuration information for the specified ADC.
+ * @param multimode : pointer to an ADC_MultiModeTypeDef structure that contains
+ * the configuration information for multimode.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_MultiModeTypeDef* multimode)
+{
+ /* Check the parameters */
+ assert_param(IS_ADC_MODE(multimode->Mode));
+ assert_param(IS_ADC_DMA_ACCESS_MODE(multimode->DMAAccessMode));
+ assert_param(IS_ADC_SAMPLING_DELAY(multimode->TwoSamplingDelay));
+
+ /* Process locked */
+ __HAL_LOCK(hadc);
+
+ /* Set ADC mode */
+ ADC->CCR &= ~(ADC_CCR_MULTI);
+ ADC->CCR |= multimode->Mode;
+
+ /* Set the ADC DMA access mode */
+ ADC->CCR &= ~(ADC_CCR_DMA);
+ ADC->CCR |= multimode->DMAAccessMode;
+
+ /* Set delay between two sampling phases */
+ ADC->CCR &= ~(ADC_CCR_DELAY);
+ ADC->CCR |= multimode->TwoSamplingDelay;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hadc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+ /**
+ * @brief DMA transfer complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void ADC_MultiModeDMAConvCplt(DMA_HandleTypeDef *hdma)
+{
+ ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ /* Check if an injected conversion is ready */
+ if(hadc->State == HAL_ADC_STATE_EOC_INJ)
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
+ }
+ else
+ {
+ /* Change ADC state */
+ hadc->State = HAL_ADC_STATE_EOC_REG;
+ }
+
+ HAL_ADC_ConvCpltCallback(hadc);
+}
+
+/**
+ * @brief DMA half transfer complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void ADC_MultiModeDMAHalfConvCplt(DMA_HandleTypeDef *hdma)
+{
+ ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ /* Conversion complete callback */
+ HAL_ADC_ConvHalfCpltCallback(hadc);
+}
+
+/**
+ * @brief DMA error callback
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void ADC_MultiModeDMAError(DMA_HandleTypeDef *hdma)
+{
+ ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ hadc->State= HAL_ADC_STATE_ERROR;
+ /* Set ADC error code to DMA error */
+ hadc->ErrorCode |= HAL_ADC_ERROR_DMA;
+ HAL_ADC_ErrorCallback(hadc);
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_ADC_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_can.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_can.c
new file mode 100644
index 0000000..dd123b6
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_can.c
@@ -0,0 +1,1415 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_can.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief This file provides firmware functions to manage the following
+ * functionalities of the Controller Area Network (CAN) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State and Error functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#) Enable the CAN controller interface clock using
+ __CAN1_CLK_ENABLE() for CAN1 and __CAN1_CLK_ENABLE() for CAN2
+ -@- In case you are using CAN2 only, you have to enable the CAN1 clock.
+
+ (#) CAN pins configuration
+ (++) Enable the clock for the CAN GPIOs using the following function:
+ __GPIOx_CLK_ENABLE()
+ (++) Connect and configure the involved CAN pins to AF9 using the
+ following function HAL_GPIO_Init()
+
+ (#) Initialise and configure the CAN using CAN_Init() function.
+
+ (#) Transmit the desired CAN frame using HAL_CAN_Transmit() function.
+
+ (#) Receive a CAN frame using HAL_CAN_Recieve() function.
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Start the CAN peripheral transmission and wait the end of this operation
+ using HAL_CAN_Transmit(), at this stage user can specify the value of timeout
+ according to his end application
+ (+) Start the CAN peripheral reception and wait the end of this operation
+ using HAL_CAN_Receive(), at this stage user can specify the value of timeout
+ according to his end application
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Start the CAN peripheral transmission using HAL_CAN_Transmit_IT()
+ (+) Start the CAN peripheral reception using HAL_CAN_Receive_IT()
+ (+) Use HAL_CAN_IRQHandler() called under the used CAN Interrupt subroutine
+ (+) At CAN end of transmission HAL_CAN_TxCpltCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_CAN_TxCpltCallback
+ (+) In case of CAN Error, HAL_CAN_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_CAN_ErrorCallback
+
+ *** CAN HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in CAN HAL driver.
+
+ (+) __HAL_CAN_ENABLE_IT: Enable the specified CAN interrupts
+ (+) __HAL_CAN_DISABLE_IT: Disable the specified CAN interrupts
+ (+) __HAL_CAN_GET_IT_SOURCE: Check if the specified CAN interrupt source is enabled or disabled
+ (+) __HAL_CAN_CLEAR_FLAG: Clear the CAN's pending flags
+ (+) __HAL_CAN_GET_FLAG: Get the selected CAN's flag status
+
+ [..]
+ (@) You can refer to the CAN HAL driver header file for more useful macros
+
+ @endverbatim
+
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup CAN
+ * @brief CAN driver modules
+ * @{
+ */
+
+#ifdef HAL_CAN_MODULE_ENABLED
+
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber);
+static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup CAN_Private_Functions
+ * @{
+ */
+
+/** @defgroup CAN_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de-initialization functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize and configure the CAN.
+ (+) De-initialize the CAN.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the CAN peripheral according to the specified
+ * parameters in the CAN_InitStruct.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan)
+{
+ uint32_t InitStatus = 3;
+ uint32_t timeout = 0;
+
+ /* Check CAN handle */
+ if(hcan == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_CAN_ALL_INSTANCE(hcan->Instance));
+ assert_param(IS_FUNCTIONAL_STATE(hcan->Init.TTCM));
+ assert_param(IS_FUNCTIONAL_STATE(hcan->Init.ABOM));
+ assert_param(IS_FUNCTIONAL_STATE(hcan->Init.AWUM));
+ assert_param(IS_FUNCTIONAL_STATE(hcan->Init.NART));
+ assert_param(IS_FUNCTIONAL_STATE(hcan->Init.RFLM));
+ assert_param(IS_FUNCTIONAL_STATE(hcan->Init.TXFP));
+ assert_param(IS_CAN_MODE(hcan->Init.Mode));
+ assert_param(IS_CAN_SJW(hcan->Init.SJW));
+ assert_param(IS_CAN_BS1(hcan->Init.BS1));
+ assert_param(IS_CAN_BS2(hcan->Init.BS2));
+ assert_param(IS_CAN_PRESCALER(hcan->Init.Prescaler));
+
+
+ if(hcan->State == HAL_CAN_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_CAN_MspInit(hcan);
+ }
+
+ /* Initialize the CAN state*/
+ hcan->State = HAL_CAN_STATE_BUSY;
+
+ /* Exit from sleep mode */
+ hcan->Instance->MCR &= (~(uint32_t)CAN_MCR_SLEEP);
+
+ /* Request initialisation */
+ hcan->Instance->MCR |= CAN_MCR_INRQ ;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 10;
+
+ /* Wait the acknowledge */
+ while((hcan->Instance->MSR & CAN_MSR_INAK) != CAN_MSR_INAK)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hcan->State= HAL_CAN_STATE_TIMEOUT;
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Check acknowledge */
+ if ((hcan->Instance->MSR & CAN_MSR_INAK) != CAN_MSR_INAK)
+ {
+ InitStatus = CAN_INITSTATUS_FAILED;
+ }
+ else
+ {
+ /* Set the time triggered communication mode */
+ if (hcan->Init.TTCM == ENABLE)
+ {
+ hcan->Instance->MCR |= CAN_MCR_TTCM;
+ }
+ else
+ {
+ hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_TTCM;
+ }
+
+ /* Set the automatic bus-off management */
+ if (hcan->Init.ABOM == ENABLE)
+ {
+ hcan->Instance->MCR |= CAN_MCR_ABOM;
+ }
+ else
+ {
+ hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_ABOM;
+ }
+
+ /* Set the automatic wake-up mode */
+ if (hcan->Init.AWUM == ENABLE)
+ {
+ hcan->Instance->MCR |= CAN_MCR_AWUM;
+ }
+ else
+ {
+ hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_AWUM;
+ }
+
+ /* Set the no automatic retransmission */
+ if (hcan->Init.NART == ENABLE)
+ {
+ hcan->Instance->MCR |= CAN_MCR_NART;
+ }
+ else
+ {
+ hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_NART;
+ }
+
+ /* Set the receive FIFO locked mode */
+ if (hcan->Init.RFLM == ENABLE)
+ {
+ hcan->Instance->MCR |= CAN_MCR_RFLM;
+ }
+ else
+ {
+ hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_RFLM;
+ }
+
+ /* Set the transmit FIFO priority */
+ if (hcan->Init.TXFP == ENABLE)
+ {
+ hcan->Instance->MCR |= CAN_MCR_TXFP;
+ }
+ else
+ {
+ hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_TXFP;
+ }
+
+ /* Set the bit timing register */
+ hcan->Instance->BTR = (uint32_t)((uint32_t)hcan->Init.Mode) | \
+ ((uint32_t)hcan->Init.SJW) | \
+ ((uint32_t)hcan->Init.BS1) | \
+ ((uint32_t)hcan->Init.BS2) | \
+ ((uint32_t)hcan->Init.Prescaler - 1);
+
+ /* Request leave initialisation */
+ hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_INRQ;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 10;
+
+ /* Wait the acknowledge */
+ while((hcan->Instance->MSR & CAN_MSR_INAK) == CAN_MSR_INAK)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hcan->State= HAL_CAN_STATE_TIMEOUT;
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Check acknowledged */
+ if ((hcan->Instance->MSR & CAN_MSR_INAK) == CAN_MSR_INAK)
+ {
+ InitStatus = CAN_INITSTATUS_FAILED;
+ }
+ else
+ {
+ InitStatus = CAN_INITSTATUS_SUCCESS;
+ }
+ }
+
+ if(InitStatus == CAN_INITSTATUS_SUCCESS)
+ {
+ /* Set CAN error code to none */
+ hcan->ErrorCode = HAL_CAN_ERROR_NONE;
+
+ /* Initialize the CAN state */
+ hcan->State = HAL_CAN_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ /* Initialize the CAN state */
+ hcan->State = HAL_CAN_STATE_ERROR;
+
+ /* Return function status */
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Configures the CAN reception filter according to the specified
+ * parameters in the CAN_FilterInitStruct.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @param sFilterConfig: pointer to a CAN_FilterConfTypeDef structure that
+ * contains the filter configuration information.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig)
+{
+ uint32_t filternbrbitpos = 0;
+
+ /* Check the parameters */
+ assert_param(IS_CAN_FILTER_NUMBER(sFilterConfig->FilterNumber));
+ assert_param(IS_CAN_FILTER_MODE(sFilterConfig->FilterMode));
+ assert_param(IS_CAN_FILTER_SCALE(sFilterConfig->FilterScale));
+ assert_param(IS_CAN_FILTER_FIFO(sFilterConfig->FilterFIFOAssignment));
+ assert_param(IS_FUNCTIONAL_STATE(sFilterConfig->FilterActivation));
+ assert_param(IS_CAN_BANKNUMBER(sFilterConfig->BankNumber));
+
+ filternbrbitpos = ((uint32_t)1) << sFilterConfig->FilterNumber;
+
+ /* Initialisation mode for the filter */
+ CAN1->FMR |= (uint32_t)CAN_FMR_FINIT;
+
+ /* Select the start slave bank */
+ CAN1->FMR &= ~((uint32_t)CAN_FMR_CAN2SB);
+ CAN1->FMR |= (uint32_t)(sFilterConfig->BankNumber << 8);
+
+ /* Filter Deactivation */
+ CAN1->FA1R &= ~(uint32_t)filternbrbitpos;
+
+ /* Filter Scale */
+ if (sFilterConfig->FilterScale == CAN_FILTERSCALE_16BIT)
+ {
+ /* 16-bit scale for the filter */
+ CAN1->FS1R &= ~(uint32_t)filternbrbitpos;
+
+ /* First 16-bit identifier and First 16-bit mask */
+ /* Or First 16-bit identifier and Second 16-bit identifier */
+ CAN1->sFilterRegister[sFilterConfig->FilterNumber].FR1 =
+ ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdLow) << 16) |
+ (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdLow);
+
+ /* Second 16-bit identifier and Second 16-bit mask */
+ /* Or Third 16-bit identifier and Fourth 16-bit identifier */
+ CAN1->sFilterRegister[sFilterConfig->FilterNumber].FR2 =
+ ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16) |
+ (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdHigh);
+ }
+
+ if (sFilterConfig->FilterScale == CAN_FILTERSCALE_32BIT)
+ {
+ /* 32-bit scale for the filter */
+ CAN1->FS1R |= filternbrbitpos;
+ /* 32-bit identifier or First 32-bit identifier */
+ CAN1->sFilterRegister[sFilterConfig->FilterNumber].FR1 =
+ ((0x0000FFFF & (uint32_t)sFilterConfig->FilterIdHigh) << 16) |
+ (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdLow);
+ /* 32-bit mask or Second 32-bit identifier */
+ CAN1->sFilterRegister[sFilterConfig->FilterNumber].FR2 =
+ ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16) |
+ (0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdLow);
+ }
+
+ /* Filter Mode */
+ if (sFilterConfig->FilterMode == CAN_FILTERMODE_IDMASK)
+ {
+ /*Id/Mask mode for the filter*/
+ CAN1->FM1R &= ~(uint32_t)filternbrbitpos;
+ }
+ else /* CAN_FilterInitStruct->CAN_FilterMode == CAN_FilterMode_IdList */
+ {
+ /*Identifier list mode for the filter*/
+ CAN1->FM1R |= (uint32_t)filternbrbitpos;
+ }
+
+ /* Filter FIFO assignment */
+ if (sFilterConfig->FilterFIFOAssignment == CAN_FILTER_FIFO0)
+ {
+ /* FIFO 0 assignation for the filter */
+ CAN1->FFA1R &= ~(uint32_t)filternbrbitpos;
+ }
+
+ if (sFilterConfig->FilterFIFOAssignment == CAN_FILTER_FIFO1)
+ {
+ /* FIFO 1 assignation for the filter */
+ CAN1->FFA1R |= (uint32_t)filternbrbitpos;
+ }
+
+ /* Filter activation */
+ if (sFilterConfig->FilterActivation == ENABLE)
+ {
+ CAN1->FA1R |= filternbrbitpos;
+ }
+
+ /* Leave the initialisation mode for the filter */
+ CAN1->FMR &= ~((uint32_t)CAN_FMR_FINIT);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Deinitializes the CANx peripheral registers to their default reset values.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef* hcan)
+{
+ /* Check CAN handle */
+ if(hcan == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_CAN_ALL_INSTANCE(hcan->Instance));
+
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_CAN_MspDeInit(hcan);
+
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hcan);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CAN MSP.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval None
+ */
+__weak void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CAN_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the CAN MSP.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval None
+ */
+__weak void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CAN_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup CAN_Group2 IO operation functions
+ * @brief IO operation functions
+ *
+@verbatim
+ ==============================================================================
+ ##### IO operation functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Transmit a CAN frame message.
+ (+) Receive a CAN frame message.
+ (+) Enter CAN peripheral in sleep mode.
+ (+) Wake up the CAN peripheral from sleep mode.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initiates and transmits a CAN frame message.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef* hcan, uint32_t Timeout)
+{
+ uint32_t transmitmailbox = 5;
+
+ uint32_t timeout;
+
+ /* Check the parameters */
+ assert_param(IS_CAN_IDTYPE(hcan->pTxMsg->IDE));
+ assert_param(IS_CAN_RTR(hcan->pTxMsg->RTR));
+ assert_param(IS_CAN_DLC(hcan->pTxMsg->DLC));
+
+ /* Process locked */
+ __HAL_LOCK(hcan);
+
+ if(hcan->State == HAL_CAN_STATE_BUSY_RX)
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_TX;
+ }
+
+ /* Select one empty transmit mailbox */
+ if ((hcan->Instance->TSR&CAN_TSR_TME0) == CAN_TSR_TME0)
+ {
+ transmitmailbox = 0;
+ }
+ else if ((hcan->Instance->TSR&CAN_TSR_TME1) == CAN_TSR_TME1)
+ {
+ transmitmailbox = 1;
+ }
+ else if ((hcan->Instance->TSR&CAN_TSR_TME2) == CAN_TSR_TME2)
+ {
+ transmitmailbox = 2;
+ }
+ else
+ {
+ transmitmailbox = CAN_TXSTATUS_NOMAILBOX;
+ }
+
+ if (transmitmailbox != CAN_TXSTATUS_NOMAILBOX)
+ {
+ /* Set up the Id */
+ hcan->Instance->sTxMailBox[transmitmailbox].TIR &= CAN_TI0R_TXRQ;
+ if (hcan->pTxMsg->IDE == CAN_ID_STD)
+ {
+ assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId));
+ hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << 21) | \
+ hcan->pTxMsg->RTR);
+ }
+ else
+ {
+ assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId));
+ hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << 3) | \
+ hcan->pTxMsg->IDE | \
+ hcan->pTxMsg->RTR);
+ }
+
+ /* Set up the DLC */
+ hcan->pTxMsg->DLC &= (uint8_t)0x0000000F;
+ hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= (uint32_t)0xFFFFFFF0;
+ hcan->Instance->sTxMailBox[transmitmailbox].TDTR |= hcan->pTxMsg->DLC;
+
+ /* Set up the data field */
+ hcan->Instance->sTxMailBox[transmitmailbox].TDLR = (((uint32_t)hcan->pTxMsg->Data[3] << 24) |
+ ((uint32_t)hcan->pTxMsg->Data[2] << 16) |
+ ((uint32_t)hcan->pTxMsg->Data[1] << 8) |
+ ((uint32_t)hcan->pTxMsg->Data[0]));
+ hcan->Instance->sTxMailBox[transmitmailbox].TDHR = (((uint32_t)hcan->pTxMsg->Data[7] << 24) |
+ ((uint32_t)hcan->pTxMsg->Data[6] << 16) |
+ ((uint32_t)hcan->pTxMsg->Data[5] << 8) |
+ ((uint32_t)hcan->pTxMsg->Data[4]));
+ /* Request transmission */
+ hcan->Instance->sTxMailBox[transmitmailbox].TIR |= CAN_TI0R_TXRQ;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Check End of transmission flag */
+ while(!(__HAL_CAN_TRANSMIT_STATUS(hcan, transmitmailbox)))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hcan->State = HAL_CAN_STATE_TIMEOUT;
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX)
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_RX;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ }
+ else
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ }
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_ERROR;
+
+ /* Return function status */
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initiates and transmits a CAN frame message.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef* hcan)
+{
+ uint32_t transmitmailbox = 5;
+ uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_CAN_IDTYPE(hcan->pTxMsg->IDE));
+ assert_param(IS_CAN_RTR(hcan->pTxMsg->RTR));
+ assert_param(IS_CAN_DLC(hcan->pTxMsg->DLC));
+
+ tmp = hcan->State;
+ if((tmp == HAL_CAN_STATE_READY) || (tmp == HAL_CAN_STATE_BUSY_RX))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcan);
+
+ /* Select one empty transmit mailbox */
+ if((hcan->Instance->TSR&CAN_TSR_TME0) == CAN_TSR_TME0)
+ {
+ transmitmailbox = 0;
+ }
+ else if((hcan->Instance->TSR&CAN_TSR_TME1) == CAN_TSR_TME1)
+ {
+ transmitmailbox = 1;
+ }
+ else if((hcan->Instance->TSR&CAN_TSR_TME2) == CAN_TSR_TME2)
+ {
+ transmitmailbox = 2;
+ }
+ else
+ {
+ transmitmailbox = CAN_TXSTATUS_NOMAILBOX;
+ }
+
+ if(transmitmailbox != CAN_TXSTATUS_NOMAILBOX)
+ {
+ /* Set up the Id */
+ hcan->Instance->sTxMailBox[transmitmailbox].TIR &= CAN_TI0R_TXRQ;
+ if(hcan->pTxMsg->IDE == CAN_ID_STD)
+ {
+ assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId));
+ hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << 21) | \
+ hcan->pTxMsg->RTR);
+ }
+ else
+ {
+ assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId));
+ hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << 3) | \
+ hcan->pTxMsg->IDE | \
+ hcan->pTxMsg->RTR);
+ }
+
+ /* Set up the DLC */
+ hcan->pTxMsg->DLC &= (uint8_t)0x0000000F;
+ hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= (uint32_t)0xFFFFFFF0;
+ hcan->Instance->sTxMailBox[transmitmailbox].TDTR |= hcan->pTxMsg->DLC;
+
+ /* Set up the data field */
+ hcan->Instance->sTxMailBox[transmitmailbox].TDLR = (((uint32_t)hcan->pTxMsg->Data[3] << 24) |
+ ((uint32_t)hcan->pTxMsg->Data[2] << 16) |
+ ((uint32_t)hcan->pTxMsg->Data[1] << 8) |
+ ((uint32_t)hcan->pTxMsg->Data[0]));
+ hcan->Instance->sTxMailBox[transmitmailbox].TDHR = (((uint32_t)hcan->pTxMsg->Data[7] << 24) |
+ ((uint32_t)hcan->pTxMsg->Data[6] << 16) |
+ ((uint32_t)hcan->pTxMsg->Data[5] << 8) |
+ ((uint32_t)hcan->pTxMsg->Data[4]));
+
+ if(hcan->State == HAL_CAN_STATE_BUSY_RX)
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_TX;
+ }
+
+ /* Set CAN error code to none */
+ hcan->ErrorCode = HAL_CAN_ERROR_NONE;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcan);
+
+ /* Enable Error warning Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EWG);
+
+ /* Enable Error passive Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EPV);
+
+ /* Enable Bus-off Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_BOF);
+
+ /* Enable Last error code Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_LEC);
+
+ /* Enable Error Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_ERR);
+
+ /* Enable Transmit mailbox empty Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_TME);
+
+ /* Request transmission */
+ hcan->Instance->sTxMailBox[transmitmailbox].TIR |= CAN_TI0R_TXRQ;
+ }
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Receives a correct CAN frame.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @param FIFONumber: FIFO Number value
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef* hcan, uint8_t FIFONumber, uint32_t Timeout)
+{
+ uint32_t timeout;
+
+ /* Check the parameters */
+ assert_param(IS_CAN_FIFO(FIFONumber));
+
+ /* Process locked */
+ __HAL_LOCK(hcan);
+
+ if(hcan->State == HAL_CAN_STATE_BUSY_TX)
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_RX;
+ }
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Check pending message */
+ while(__HAL_CAN_MSG_PENDING(hcan, FIFONumber) == 0)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hcan->State = HAL_CAN_STATE_TIMEOUT;
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Get the Id */
+ hcan->pRxMsg->IDE = (uint8_t)0x04 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR;
+ if (hcan->pRxMsg->IDE == CAN_ID_STD)
+ {
+ hcan->pRxMsg->StdId = (uint32_t)0x000007FF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21);
+ }
+ else
+ {
+ hcan->pRxMsg->ExtId = (uint32_t)0x1FFFFFFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3);
+ }
+
+ hcan->pRxMsg->RTR = (uint8_t)0x02 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR;
+ /* Get the DLC */
+ hcan->pRxMsg->DLC = (uint8_t)0x0F & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR;
+ /* Get the FMI */
+ hcan->pRxMsg->FMI = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8);
+ /* Get the data field */
+ hcan->pRxMsg->Data[0] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR;
+ hcan->pRxMsg->Data[1] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8);
+ hcan->pRxMsg->Data[2] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16);
+ hcan->pRxMsg->Data[3] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24);
+ hcan->pRxMsg->Data[4] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR;
+ hcan->pRxMsg->Data[5] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8);
+ hcan->pRxMsg->Data[6] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16);
+ hcan->pRxMsg->Data[7] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24);
+
+ /* Release the FIFO */
+ if(FIFONumber == CAN_FIFO0)
+ {
+ /* Release FIFO0 */
+ __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO0);
+ }
+ else /* FIFONumber == CAN_FIFO1 */
+ {
+ /* Release FIFO1 */
+ __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO1);
+ }
+
+ if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX)
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_TX;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ }
+ else
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Receives a correct CAN frame.
+ * @param hcan: Pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @param FIFONumber: Specify the FIFO number
+ * @retval HAL status
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber)
+{
+ uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_CAN_FIFO(FIFONumber));
+
+ tmp = hcan->State;
+ if((tmp == HAL_CAN_STATE_READY) || (tmp == HAL_CAN_STATE_BUSY_TX))
+ {
+ /* Process locked */
+ __HAL_LOCK(hcan);
+
+ if(hcan->State == HAL_CAN_STATE_BUSY_TX)
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_RX;
+ }
+
+ /* Set CAN error code to none */
+ hcan->ErrorCode = HAL_CAN_ERROR_NONE;
+
+ /* Enable Error warning Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EWG);
+
+ /* Enable Error passive Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EPV);
+
+ /* Enable Bus-off Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_BOF);
+
+ /* Enable Last error code Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_LEC);
+
+ /* Enable Error Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_ERR);
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+
+ if(FIFONumber == CAN_FIFO0)
+ {
+ /* Enable FIFO 0 message pending Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FMP0);
+ }
+ else
+ {
+ /* Enable FIFO 1 message pending Interrupt */
+ __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FMP1);
+ }
+
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Enters the Sleep (low power) mode.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef* hcan)
+{
+ uint32_t timeout;
+
+ /* Process locked */
+ __HAL_LOCK(hcan);
+
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY;
+
+ /* Request Sleep mode */
+ hcan->Instance->MCR = (((hcan->Instance->MCR) & (uint32_t)(~(uint32_t)CAN_MCR_INRQ)) | CAN_MCR_SLEEP);
+
+ /* Sleep mode status */
+ if ((hcan->Instance->MSR & (CAN_MSR_SLAK|CAN_MSR_INAK)) != CAN_MSR_SLAK)
+ {
+ /* Return function status */
+ return HAL_ERROR;
+ }
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 10;
+
+ /* Wait the acknowledge */
+ while((hcan->Instance->MSR & (CAN_MSR_SLAK|CAN_MSR_INAK)) != CAN_MSR_SLAK)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hcan->State = HAL_CAN_STATE_TIMEOUT;
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Wakes up the CAN peripheral from sleep mode, after that the CAN peripheral
+ * is in the normal mode.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef* hcan)
+{
+ uint32_t timeout;
+
+ /* Process locked */
+ __HAL_LOCK(hcan);
+
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY;
+
+ /* Wake up request */
+ hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_SLEEP;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 10;
+
+ /* Sleep mode status */
+ while((hcan->Instance->MSR & CAN_MSR_SLAK) == CAN_MSR_SLAK)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hcan->State= HAL_CAN_STATE_TIMEOUT;
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+ return HAL_TIMEOUT;
+ }
+ }
+ if((hcan->Instance->MSR & CAN_MSR_SLAK) == CAN_MSR_SLAK)
+ {
+ /* Return function status */
+ return HAL_ERROR;
+ }
+
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hcan);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Handles CAN interrupt request
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval None
+ */
+void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan)
+{
+ uint32_t tmp1 = 0, tmp2 = 0, tmp3 = 0;
+
+ /* Check End of transmission flag */
+ if(__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_TME))
+ {
+ tmp1 = __HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_0);
+ tmp2 = __HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_1);
+ tmp3 = __HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_2);
+ if(tmp1 || tmp2 || tmp3)
+ {
+ /* Call transmit function */
+ CAN_Transmit_IT(hcan);
+ }
+ }
+
+ tmp1 = __HAL_CAN_MSG_PENDING(hcan, CAN_FIFO0);
+ tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP0);
+ /* Check End of reception flag for FIFO0 */
+ if((tmp1 != 0) && tmp2)
+ {
+ /* Call receive function */
+ CAN_Receive_IT(hcan, CAN_FIFO0);
+ }
+
+ tmp1 = __HAL_CAN_MSG_PENDING(hcan, CAN_FIFO1);
+ tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP1);
+ /* Check End of reception flag for FIFO1 */
+ if((tmp1 != 0) && tmp2)
+ {
+ /* Call receive function */
+ CAN_Receive_IT(hcan, CAN_FIFO1);
+ }
+
+ tmp1 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EWG);
+ tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EWG);
+ tmp3 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR);
+ /* Check Error Warning Flag */
+ if(tmp1 && tmp2 && tmp3)
+ {
+ /* Set CAN error code to EWG error */
+ hcan->ErrorCode |= HAL_CAN_ERROR_EWG;
+ /* Clear Error Warning Flag */
+ __HAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_EWG);
+ }
+
+ tmp1 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EPV);
+ tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EPV);
+ tmp3 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR);
+ /* Check Error Passive Flag */
+ if(tmp1 && tmp2 && tmp3)
+ {
+ /* Set CAN error code to EPV error */
+ hcan->ErrorCode |= HAL_CAN_ERROR_EPV;
+ /* Clear Error Passive Flag */
+ __HAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_EPV);
+ }
+
+ tmp1 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_BOF);
+ tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_BOF);
+ tmp3 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR);
+ /* Check Bus-Off Flag */
+ if(tmp1 && tmp2 && tmp3)
+ {
+ /* Set CAN error code to BOF error */
+ hcan->ErrorCode |= HAL_CAN_ERROR_BOF;
+ /* Clear Bus-Off Flag */
+ __HAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_BOF);
+ }
+
+ tmp1 = HAL_IS_BIT_CLR(hcan->Instance->ESR, CAN_ESR_LEC);
+ tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_LEC);
+ tmp3 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR);
+ /* Check Last error code Flag */
+ if((!tmp1) && tmp2 && tmp3)
+ {
+ tmp1 = (hcan->Instance->ESR) & CAN_ESR_LEC;
+ switch(tmp1)
+ {
+ case(CAN_ESR_LEC_0):
+ /* Set CAN error code to STF error */
+ hcan->ErrorCode |= HAL_CAN_ERROR_STF;
+ break;
+ case(CAN_ESR_LEC_1):
+ /* Set CAN error code to FOR error */
+ hcan->ErrorCode |= HAL_CAN_ERROR_FOR;
+ break;
+ case(CAN_ESR_LEC_1 | CAN_ESR_LEC_0):
+ /* Set CAN error code to ACK error */
+ hcan->ErrorCode |= HAL_CAN_ERROR_ACK;
+ break;
+ case(CAN_ESR_LEC_2):
+ /* Set CAN error code to BR error */
+ hcan->ErrorCode |= HAL_CAN_ERROR_BR;
+ break;
+ case(CAN_ESR_LEC_2 | CAN_ESR_LEC_0):
+ /* Set CAN error code to BD error */
+ hcan->ErrorCode |= HAL_CAN_ERROR_BD;
+ break;
+ case(CAN_ESR_LEC_2 | CAN_ESR_LEC_1):
+ /* Set CAN error code to CRC error */
+ hcan->ErrorCode |= HAL_CAN_ERROR_CRC;
+ break;
+ default:
+ break;
+ }
+
+ /* Clear Last error code Flag */
+ hcan->Instance->ESR &= ~(CAN_ESR_LEC);
+ }
+
+ /* Call the Error call Back in case of Errors */
+ if(hcan->ErrorCode != HAL_CAN_ERROR_NONE)
+ {
+ /* Set the CAN state ready to be able to start again the process */
+ hcan->State = HAL_CAN_STATE_READY;
+ /* Call Error callback function */
+ HAL_CAN_ErrorCallback(hcan);
+ }
+}
+
+/**
+ * @brief Transmission complete callback in non blocking mode
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval None
+ */
+__weak void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CAN_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Transmission complete callback in non blocking mode
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval None
+ */
+__weak void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CAN_RxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Error CAN callback.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval None
+ */
+__weak void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CAN_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup CAN_Group3 Peripheral State and Error functions
+ * @brief CAN Peripheral State functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State and Error functions #####
+ ==============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Check the CAN state.
+ (+) Check CAN Errors detected during interrupt process
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief return the CAN state
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval HAL state
+ */
+HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan)
+{
+ /* Return CAN state */
+ return hcan->State;
+}
+
+/**
+ * @brief Return the CAN error code
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval CAN Error Code
+ */
+uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan)
+{
+ return hcan->ErrorCode;
+}
+
+/**
+ * @}
+ */
+/**
+ * @brief Initiates and transmits a CAN frame message.
+ * @param hcan: pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan)
+{
+ /* Disable Transmit mailbox empty Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_TME);
+
+ if(hcan->State == HAL_CAN_STATE_BUSY_TX)
+ {
+ /* Disable Error warning Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EWG);
+
+ /* Disable Error passive Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EPV);
+
+ /* Disable Bus-off Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_BOF);
+
+ /* Disable Last error code Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_LEC);
+
+ /* Disable Error Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_ERR);
+ }
+
+ if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX)
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_RX;
+ }
+ else
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_READY;
+ }
+
+ /* Transmission complete callback */
+ HAL_CAN_TxCpltCallback(hcan);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Receives a correct CAN frame.
+ * @param hcan: Pointer to a CAN_HandleTypeDef structure that contains
+ * the configuration information for the specified CAN.
+ * @param FIFONumber: Specify the FIFO number
+ * @retval HAL status
+ * @retval None
+ */
+static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber)
+{
+ /* Get the Id */
+ hcan->pRxMsg->IDE = (uint8_t)0x04 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR;
+ if (hcan->pRxMsg->IDE == CAN_ID_STD)
+ {
+ hcan->pRxMsg->StdId = (uint32_t)0x000007FF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21);
+ }
+ else
+ {
+ hcan->pRxMsg->ExtId = (uint32_t)0x1FFFFFFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3);
+ }
+
+ hcan->pRxMsg->RTR = (uint8_t)0x02 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR;
+ /* Get the DLC */
+ hcan->pRxMsg->DLC = (uint8_t)0x0F & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR;
+ /* Get the FMI */
+ hcan->pRxMsg->FMI = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8);
+ /* Get the data field */
+ hcan->pRxMsg->Data[0] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR;
+ hcan->pRxMsg->Data[1] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8);
+ hcan->pRxMsg->Data[2] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16);
+ hcan->pRxMsg->Data[3] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24);
+ hcan->pRxMsg->Data[4] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR;
+ hcan->pRxMsg->Data[5] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8);
+ hcan->pRxMsg->Data[6] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16);
+ hcan->pRxMsg->Data[7] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24);
+ /* Release the FIFO */
+ /* Release FIFO0 */
+ if (FIFONumber == CAN_FIFO0)
+ {
+ __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO0);
+
+ /* Disable FIFO 0 message pending Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FMP0);
+ }
+ /* Release FIFO1 */
+ else /* FIFONumber == CAN_FIFO1 */
+ {
+ __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO1);
+
+ /* Disable FIFO 1 message pending Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FMP1);
+ }
+
+ if(hcan->State == HAL_CAN_STATE_BUSY_RX)
+ {
+ /* Disable Error warning Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EWG);
+
+ /* Disable Error passive Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EPV);
+
+ /* Disable Bus-off Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_BOF);
+
+ /* Disable Last error code Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_LEC);
+
+ /* Disable Error Interrupt */
+ __HAL_CAN_DISABLE_IT(hcan, CAN_IT_ERR);
+ }
+
+ if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX)
+ {
+ /* Disable CAN state */
+ hcan->State = HAL_CAN_STATE_BUSY_TX;
+ }
+ else
+ {
+ /* Change CAN state */
+ hcan->State = HAL_CAN_STATE_READY;
+ }
+
+ /* Receive complete callback */
+ HAL_CAN_RxCpltCallback(hcan);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+
+#endif /* HAL_CAN_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cortex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cortex.c
new file mode 100644
index 0000000..57e07b6
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cortex.c
@@ -0,0 +1,444 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_cortex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief CORTEX HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the CORTEX:
+ * + Initialization and de-initialization functions
+ * + Peripheral Control functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+
+ [..]
+ *** How to configure Interrupts using Cortex HAL driver ***
+ ===========================================================
+ [..]
+ This section provide functions allowing to configure the NVIC interrupts (IRQ).
+ The Cortex-M4 exceptions are managed by CMSIS functions.
+
+ (#) Configure the NVIC Priority Grouping using HAL_NVIC_SetPriorityGrouping()
+ function according to the following table.
+
+ The table below gives the allowed values of the pre-emption priority and subpriority according
+ to the Priority Grouping configuration performed by HAL_NVIC_SetPriorityGrouping() function.
+ ==========================================================================================================================
+ NVIC_PriorityGroup | NVIC_IRQChannelPreemptionPriority | NVIC_IRQChannelSubPriority | Description
+ ==========================================================================================================================
+ NVIC_PRIORITYGROUP_0 | 0 | 0-15 | 0 bits for pre-emption priority
+ | | | 4 bits for subpriority
+ --------------------------------------------------------------------------------------------------------------------------
+ NVIC_PRIORITYGROUP_1 | 0-1 | 0-7 | 1 bits for pre-emption priority
+ | | | 3 bits for subpriority
+ --------------------------------------------------------------------------------------------------------------------------
+ NVIC_PRIORITYGROUP_2 | 0-3 | 0-3 | 2 bits for pre-emption priority
+ | | | 2 bits for subpriority
+ --------------------------------------------------------------------------------------------------------------------------
+ NVIC_PRIORITYGROUP_3 | 0-7 | 0-1 | 3 bits for pre-emption priority
+ | | | 1 bits for subpriority
+ --------------------------------------------------------------------------------------------------------------------------
+ NVIC_PRIORITYGROUP_4 | 0-15 | 0 | 4 bits for pre-emption priority
+ | | | 0 bits for subpriority
+ ==========================================================================================================================
+ (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority()
+
+ (#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ()
+
+
+ -@- When the NVIC_PRIORITYGROUP_0 is selected, IRQ pre-emption is no more possible.
+ The pending IRQ priority will be managed only by the sub priority.
+
+ -@- IRQ priority order (sorted by highest to lowest priority):
+ (+@) Lowest pre-emption priority
+ (+@) Lowest sub priority
+ (+@) Lowest hardware priority (IRQ number)
+
+ [..]
+ *** How to configure Systick using Cortex HAL driver ***
+ ========================================================
+ [..]
+ Setup SysTick Timer for 1 msec interrupts.
+
+ (+) The HAL_SYSTICK_Config()function calls the SysTick_Config() function which
+ is a CMSIS function that:
+ (++) Configures the SysTick Reload register with value passed as function parameter.
+ (++) Configures the SysTick IRQ priority to the lowest value (0x0F).
+ (++) Resets the SysTick Counter register.
+ (++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK).
+ (++) Enables the SysTick Interrupt.
+ (++) Starts the SysTick Counter.
+
+ (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro
+ __HAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the
+ HAL_SYSTICK_Config() function call. The __HAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined
+ inside the stm32f4xx_hal_cortex.h file.
+
+ (+) You can change the SysTick IRQ priority by calling the
+ HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function
+ call. The HAL_NVIC_SetPriority() call the NVIC_SetPriority() function which is a CMSIS function.
+
+ (+) To adjust the SysTick time base, use the following formula:
+
+ Reload Value = SysTick Counter Clock (Hz) x Desired Time base (s)
+ (++) Reload Value is the parameter to be passed for HAL_SYSTICK_Config() function
+ (++) Reload Value should not exceed 0xFFFFFF
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup CORTEX
+ * @brief CORTEX HAL module driver
+ * @{
+ */
+
+#ifdef HAL_CORTEX_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup CORTEX_Private_Functions
+ * @{
+ */
+
+
+/** @defgroup CORTEX_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de-initialization functions #####
+ ==============================================================================
+ [..]
+ This section provide the Cortex HAL driver functions allowing to configure Interrupts
+ Systick functionalities
+
+@endverbatim
+ * @{
+ */
+
+
+/**
+ * @brief Sets the priority grouping field (pre-emption priority and subpriority)
+ * using the required unlock sequence.
+ * @param PriorityGroup: The priority grouping bits length.
+ * This parameter can be one of the following values:
+ * @arg NVIC_PRIORITYGROUP_0: 0 bits for pre-emption priority
+ * 4 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_1: 1 bits for pre-emption priority
+ * 3 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_2: 2 bits for pre-emption priority
+ * 2 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_3: 3 bits for pre-emption priority
+ * 1 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_4: 4 bits for pre-emption priority
+ * 0 bits for subpriority
+ * @note When the NVIC_PriorityGroup_0 is selected, IRQ pre-emption is no more possible.
+ * The pending IRQ priority will be managed only by the subpriority.
+ * @retval None
+ */
+void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
+{
+ /* Check the parameters */
+ assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup));
+
+ /* Set the PRIGROUP[10:8] bits according to the PriorityGroup parameter value */
+ NVIC_SetPriorityGrouping(PriorityGroup);
+}
+
+/**
+ * @brief Sets the priority of an interrupt.
+ * @param IRQn: External interrupt number
+ * This parameter can be an enumerator of @ref IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to stm32f4xx.h file)
+ * @param PreemptPriority: The pre-emption priority for the IRQn channel.
+ * This parameter can be a value between 0 and 15
+ * A lower priority value indicates a higher priority
+ * @param SubPriority: the subpriority level for the IRQ channel.
+ * This parameter can be a value between 0 and 15
+ * A lower priority value indicates a higher priority.
+ * @retval None
+ */
+void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority)
+{
+ uint32_t prioritygroup = 0x00;
+
+ /* Check the parameters */
+ assert_param(IS_NVIC_SUB_PRIORITY(SubPriority));
+ assert_param(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority));
+
+ prioritygroup = NVIC_GetPriorityGrouping();
+
+ NVIC_SetPriority(IRQn, NVIC_EncodePriority(prioritygroup, PreemptPriority, SubPriority));
+}
+
+/**
+ * @brief Enables a device specific interrupt in the NVIC interrupt controller.
+ * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig()
+ * function should be called before.
+ * @param IRQn External interrupt number
+ * This parameter can be an enumerator of @ref IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to stm32f4xx.h file)
+ * @retval None
+ */
+void HAL_NVIC_EnableIRQ(IRQn_Type IRQn)
+{
+ /* Enable interrupt */
+ NVIC_EnableIRQ(IRQn);
+}
+
+/**
+ * @brief Disables a device specific interrupt in the NVIC interrupt controller.
+ * @param IRQn External interrupt number
+ * This parameter can be an enumerator of @ref IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to stm32f4xx.h file)
+ * @retval None
+ */
+void HAL_NVIC_DisableIRQ(IRQn_Type IRQn)
+{
+ /* Disable interrupt */
+ NVIC_DisableIRQ(IRQn);
+}
+
+/**
+ * @brief Initiates a system reset request to reset the MCU.
+ * @param None
+ * @retval None
+ */
+void HAL_NVIC_SystemReset(void)
+{
+ /* System Reset */
+ NVIC_SystemReset();
+}
+
+/**
+ * @brief Initializes the System Timer and its interrupt, and starts the System Tick Timer.
+ * Counter is in free running mode to generate periodic interrupts.
+ * @param TicksNumb: Specifies the ticks Number of ticks between two interrupts.
+ * @retval status: - 0 Function succeeded.
+ * - 1 Function failed.
+ */
+uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb)
+{
+ return SysTick_Config(TicksNumb);
+}
+/**
+ * @}
+ */
+
+/** @defgroup CORTEX_Group2 Peripheral Control functions
+ * @brief Cortex control functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the CORTEX
+ (NVIC, SYSTICK) functionalities.
+
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Gets the priority grouping field from the NVIC Interrupt Controller.
+ * @param None
+ * @retval Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field)
+ */
+uint32_t HAL_NVIC_GetPriorityGrouping(void)
+{
+ /* Get the PRIGROUP[10:8] field value */
+ return NVIC_GetPriorityGrouping();
+}
+
+/**
+ * @brief Gets the priority of an interrupt.
+ * @param IRQn: External interrupt number
+ * This parameter can be an enumerator of @ref IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to stm32f4xx.h file)
+ * @param PriorityGroup: the priority grouping bits length.
+ * This parameter can be one of the following values:
+ * @arg NVIC_PRIORITYGROUP_0: 0 bits for pre-emption priority
+ * 4 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_1: 1 bits for pre-emption priority
+ * 3 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_2: 2 bits for pre-emption priority
+ * 2 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_3: 3 bits for pre-emption priority
+ * 1 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_4: 4 bits for pre-emption priority
+ * 0 bits for subpriority
+ * @param pPreemptPriority: Pointer on the Preemptive priority value (starting from 0).
+ * @param pSubPriority: Pointer on the Subpriority value (starting from 0).
+ * @retval None
+ */
+void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t *pPreemptPriority, uint32_t *pSubPriority)
+{
+ /* Check the parameters */
+ assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup));
+ /* Get priority for Cortex-M system or device specific interrupts */
+ NVIC_DecodePriority(NVIC_GetPriority(IRQn), PriorityGroup, pPreemptPriority, pSubPriority);
+}
+
+/**
+ * @brief Sets Pending bit of an external interrupt.
+ * @param IRQn External interrupt number
+ * This parameter can be an enumerator of @ref IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to stm32f4xx.h file)
+ * @retval None
+ */
+void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn)
+{
+ /* Set interrupt pending */
+ NVIC_SetPendingIRQ(IRQn);
+}
+
+/**
+ * @brief Gets Pending Interrupt (reads the pending register in the NVIC
+ * and returns the pending bit for the specified interrupt).
+ * @param IRQn External interrupt number
+ * This parameter can be an enumerator of @ref IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to stm32f4xx.h file)
+ * @retval status: - 0 Interrupt status is not pending.
+ * - 1 Interrupt status is pending.
+ */
+uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn)
+{
+ /* Return 1 if pending else 0 */
+ return NVIC_GetPendingIRQ(IRQn);
+}
+
+/**
+ * @brief Clears the pending bit of an external interrupt.
+ * @param IRQn External interrupt number
+ * This parameter can be an enumerator of @ref IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to stm32f4xx.h file)
+ * @retval None
+ */
+void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn)
+{
+ /* Clear pending interrupt */
+ NVIC_ClearPendingIRQ(IRQn);
+}
+
+/**
+ * @brief Gets active interrupt ( reads the active register in NVIC and returns the active bit).
+ * @param IRQn External interrupt number
+ * This parameter can be an enumerator of @ref IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to stm32f4xx.h file)
+ * @retval status: - 0 Interrupt status is not pending.
+ * - 1 Interrupt status is pending.
+ */
+uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn)
+{
+ /* Return 1 if active else 0 */
+ return NVIC_GetActive(IRQn);
+}
+
+/**
+ * @brief Configures the SysTick clock source.
+ * @param CLKSource: specifies the SysTick clock source.
+ * This parameter can be one of the following values:
+ * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source.
+ * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source.
+ * @retval None
+ */
+void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource)
+{
+ /* Check the parameters */
+ assert_param(IS_SYSTICK_CLK_SOURCE(CLKSource));
+ if (CLKSource == SYSTICK_CLKSOURCE_HCLK)
+ {
+ SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK;
+ }
+ else
+ {
+ SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK;
+ }
+}
+
+/**
+ * @brief This function handles SYSTICK interrupt request.
+ * @param None
+ * @retval None
+ */
+void HAL_SYSTICK_IRQHandler(void)
+{
+ HAL_SYSTICK_Callback();
+}
+
+/**
+ * @brief SYSTICK callback.
+ * @param None
+ * @retval None
+ */
+__weak void HAL_SYSTICK_Callback(void)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SYSTICK_Callback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_CORTEX_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_crc.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_crc.c
new file mode 100644
index 0000000..59ca9fe
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_crc.c
@@ -0,0 +1,332 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_crc.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief CRC HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Cyclic Redundancy Check (CRC) peripheral:
+ * + Initialization and de-initialization functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The CRC HAL driver can be used as follows:
+
+ (#) Enable CRC AHB clock using __CRC_CLK_ENABLE();
+
+ (#) Use HAL_CRC_Accumulate() function to compute the CRC value of
+ a 32-bit data buffer using combination of the previous CRC value
+ and the new one.
+
+ (#) Use HAL_CRC_Calculate() function to compute the CRC Value of
+ a new 32-bit data buffer. This function resets the CRC computation
+ unit before starting the computation to avoid getting wrong CRC values.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup CRC
+ * @brief CRC HAL module driver.
+ * @{
+ */
+
+#ifdef HAL_CRC_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup CRC_Private_Functions
+ * @{
+ */
+
+/** @defgroup CRC_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de-initialization functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize the CRC according to the specified parameters
+ in the CRC_InitTypeDef and create the associated handle
+ (+) DeInitialize the CRC peripheral
+ (+) Initialize the CRC MSP
+ (+) DeInitialize CRC MSP
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the CRC according to the specified
+ * parameters in the CRC_InitTypeDef and creates the associated handle.
+ * @param hcrc: CRC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc)
+{
+ /* Check the CRC handle allocation */
+ if(hcrc == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance));
+
+ if(hcrc->State == HAL_CRC_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_CRC_MspInit(hcrc);
+ }
+
+ /* Change CRC peripheral state */
+ hcrc->State = HAL_CRC_STATE_BUSY;
+
+ /* Change CRC peripheral state */
+ hcrc->State = HAL_CRC_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the CRC peripheral.
+ * @param hcrc: CRC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRC_DeInit(CRC_HandleTypeDef *hcrc)
+{
+ /* Check the CRC handle allocation */
+ if(hcrc == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance));
+
+ /* Change CRC peripheral state */
+ hcrc->State = HAL_CRC_STATE_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_CRC_MspDeInit(hcrc);
+
+ /* Change CRC peripheral state */
+ hcrc->State = HAL_CRC_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hcrc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRC MSP.
+ * @param hcrc: CRC handle
+ * @retval None
+ */
+__weak void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CRC_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the CRC MSP.
+ * @param hcrc: CRC handle
+ * @retval None
+ */
+__weak void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CRC_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup CRC_Group2 Peripheral Control functions
+ * @brief management functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral Control functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Compute the 32-bit CRC value of 32-bit data buffer,
+ using combination of the previous CRC value and the new one.
+ (+) Compute the 32-bit CRC value of 32-bit data buffer,
+ independently of the previous CRC value.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Computes the 32-bit CRC of 32-bit data buffer using combination
+ * of the previous CRC value and the new one.
+ * @param hcrc: CRC handle
+ * @param pBuffer: pointer to the buffer containing the data to be computed
+ * @param BufferLength: length of the buffer to be computed
+ * @retval 32-bit CRC
+ */
+uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength)
+{
+ uint32_t index = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hcrc);
+
+ /* Change CRC peripheral state */
+ hcrc->State = HAL_CRC_STATE_BUSY;
+
+ /* Enter Data to the CRC calculator */
+ for(index = 0; index < BufferLength; index++)
+ {
+ hcrc->Instance->DR = pBuffer[index];
+ }
+
+ /* Change CRC peripheral state */
+ hcrc->State = HAL_CRC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcrc);
+
+ /* Return the CRC computed value */
+ return hcrc->Instance->DR;
+}
+
+/**
+ * @brief Computes the 32-bit CRC of 32-bit data buffer independently
+ * of the previous CRC value.
+ * @param hcrc: CRC handle
+ * @param pBuffer: Pointer to the buffer containing the data to be computed
+ * @param BufferLength: Length of the buffer to be computed
+ * @retval 32-bit CRC
+ */
+uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength)
+{
+ uint32_t index = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hcrc);
+
+ /* Change CRC peripheral state */
+ hcrc->State = HAL_CRC_STATE_BUSY;
+
+ /* Reset CRC Calculation Unit */
+ __HAL_CRC_DR_RESET(hcrc);
+
+ /* Enter Data to the CRC calculator */
+ for(index = 0; index < BufferLength; index++)
+ {
+ hcrc->Instance->DR = pBuffer[index];
+ }
+
+ /* Change CRC peripheral state */
+ hcrc->State = HAL_CRC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcrc);
+
+ /* Return the CRC computed value */
+ return hcrc->Instance->DR;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup CRC_Group3 Peripheral State functions
+ * @brief Peripheral State functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State functions #####
+ ==============================================================================
+ [..]
+ This subsection permits to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the CRC state.
+ * @param hcrc: CRC handle
+ * @retval HAL state
+ */
+HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc)
+{
+ return hcrc->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_CRC_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cryp.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cryp.c
new file mode 100644
index 0000000..ab93244
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cryp.c
@@ -0,0 +1,3726 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_cryp.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief CRYP HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Cryptography (CRYP) peripheral:
+ * + Initialization and de-initialization functions
+ * + AES processing functions
+ * + DES processing functions
+ * + TDES processing functions
+ * + DMA callback functions
+ * + CRYP IRQ handler management
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The CRYP HAL driver can be used as follows:
+
+ (#)Initialize the CRYP low level resources by implementing the HAL_CRYP_MspInit():
+ (##) Enable the CRYP interface clock using __CRYP_CLK_ENABLE()
+ (##) In case of using interrupts (e.g. HAL_CRYP_AESECB_Encrypt_IT())
+ (+++) Configure the CRYP interrupt priority using HAL_NVIC_SetPriority()
+ (+++) Enable the CRYP IRQ handler using HAL_NVIC_EnableIRQ()
+ (+++) In CRYP IRQ handler, call HAL_CRYP_IRQHandler()
+ (##) In case of using DMA to control data transfer (e.g. HAL_CRYP_AESECB_Encrypt_DMA())
+ (++) Enable the DMAx interface clock using
+ (+++) __DMAx_CLK_ENABLE()
+ (++) Configure and enable two DMA streams one for managing data transfer from
+ memory to peripheral (input stream) and another stream for managing data
+ transfer from peripheral to memory (output stream)
+ (++) Associate the initilalized DMA handle to the CRYP DMA handle
+ using __HAL_LINKDMA()
+ (++) Configure the priority and enable the NVIC for the transfer complete
+ interrupt on the two DMA Streams. The output stream should have higher
+ priority than the input stream.
+ (+++) HAL_NVIC_SetPriority()
+ (+++) HAL_NVIC_EnableIRQ()
+
+ (#)Initialize the CRYP HAL using HAL_CRYP_Init(). This function configures mainly:
+ (##) The data type: 1-bit, 8-bit, 16-bit and 32-bit
+ (##) The key size: 128, 192 and 256. This parameter is relevant only for AES
+ (##) The encryption/decryption key. It's size depends on the algorithm
+ used for encryption/decryption
+ (##) The initialization vector (counter). It is not used ECB mode.
+
+ (#)Three processing (encryption/decryption) functions are available:
+ (##) Polling mode: encryption and decryption APIs are blocking functions
+ i.e. they process the data and wait till the processing is finished
+ e.g. HAL_CRYP_AESCBC_Encrypt()
+ (##) Interrupt mode: encryption and decryption APIs are not blocking functions
+ i.e. they process the data under interrupt
+ e.g. HAL_CRYP_AESCBC_Encrypt_IT()
+ (##) DMA mode: encryption and decryption APIs are not blocking functions
+ i.e. the data transfer is ensured by DMA
+ e.g. HAL_CRYP_AESCBC_Encrypt_DMA()
+
+ (#)When the processing function is called at first time after HAL_CRYP_Init()
+ the CRYP peripheral is initialized and processes the buffer in input.
+ At second call, the processing function performs an append of the already
+ processed buffer.
+ When a new data block is to be processed, call HAL_CRYP_Init() then the
+ processing function.
+
+ (#)Call HAL_CRYP_DeInit() to deinitialize the CRYP peripheral.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup CRYP
+ * @brief CRYP HAL module driver.
+ * @{
+ */
+
+#ifdef HAL_CRYP_MODULE_ENABLED
+
+#if defined(STM32F415xx) || defined(STM32F417xx) || defined(STM32F437xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void CRYP_SetInitVector(CRYP_HandleTypeDef *hcryp, uint8_t *InitVector, uint32_t IVSize);
+static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint8_t *Key, uint32_t KeySize);
+static HAL_StatusTypeDef CRYP_ProcessData(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout);
+static HAL_StatusTypeDef CRYP_ProcessData2Words(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout);
+static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma);
+static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma);
+static void CRYP_DMAError(DMA_HandleTypeDef *hdma);
+static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr);
+static void CRYP_SetTDESECBMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction);
+static void CRYP_SetTDESCBCMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction);
+static void CRYP_SetDESECBMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction);
+static void CRYP_SetDESCBCMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup CRYP_Private_Functions
+ * @{
+ */
+
+/** @defgroup CRYP_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de-initialization functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize the CRYP according to the specified parameters
+ in the CRYP_InitTypeDef and creates the associated handle
+ (+) DeInitialize the CRYP peripheral
+ (+) Initialize the CRYP MSP
+ (+) DeInitialize CRYP MSP
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the CRYP according to the specified
+ * parameters in the CRYP_InitTypeDef and creates the associated handle.
+ * @param hcryp: CRYP handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_Init(CRYP_HandleTypeDef *hcryp)
+{
+ /* Check the CRYP handle allocation */
+ if(hcryp == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_CRYP_KEYSIZE(hcryp->Init.KeySize));
+ assert_param(IS_CRYP_DATATYPE(hcryp->Init.DataType));
+
+ if(hcryp->State == HAL_CRYP_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_CRYP_MspInit(hcryp);
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set the key size and data type*/
+ CRYP->CR = (uint32_t) (hcryp->Init.KeySize | hcryp->Init.DataType);
+
+ /* Reset CrypInCount and CrypOutCount */
+ hcryp->CrypInCount = 0;
+ hcryp->CrypOutCount = 0;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Set the default CRYP phase */
+ hcryp->Phase = HAL_CRYP_PHASE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the CRYP peripheral.
+ * @param hcryp: CRYP handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp)
+{
+ /* Check the CRYP handle allocation */
+ if(hcryp == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set the default CRYP phase */
+ hcryp->Phase = HAL_CRYP_PHASE_READY;
+
+ /* Reset CrypInCount and CrypOutCount */
+ hcryp->CrypInCount = 0;
+ hcryp->CrypOutCount = 0;
+
+ /* Disable the CRYP Peripheral Clock */
+ __HAL_CRYP_DISABLE();
+
+ /* DeInit the low level hardware: CLOCK, NVIC.*/
+ HAL_CRYP_MspDeInit(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP MSP.
+ * @param hcryp: CRYP handle
+ * @retval None
+ */
+__weak void HAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CRYP_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes CRYP MSP.
+ * @param hcryp: CRYP handle
+ * @retval None
+ */
+__weak void HAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CRYP_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup CRYP_Group2 AES processing functions
+ * @brief processing functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### AES processing functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Encrypt plaintext using AES-128/192/256 using chaining modes
+ (+) Decrypt cyphertext using AES-128/192/256 using chaining modes
+ [..] Three processing functions are available:
+ (+) Polling mode
+ (+) Interrupt mode
+ (+) DMA mode
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the CRYP peripheral in AES ECB encryption mode
+ * then encrypt pPlainData. The cypher data are available in pCypherData
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16.
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData(hcryp,pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CBC encryption mode
+ * then encrypt pPlainData. The cypher data are available in pCypherData
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16.
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData(hcryp,pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CTR encryption mode
+ * then encrypt pPlainData. The cypher data are available in pCypherData
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16.
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+
+
+/**
+ * @brief Initializes the CRYP peripheral in AES ECB decryption mode
+ * then decrypted pCypherData. The cypher data are available in pPlainData
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16.
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES Key mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(CRYP->SR, CRYP_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+
+ /* Reset the ALGOMODE bits*/
+ CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
+
+ /* Set the CRYP peripheral in AES ECB decryption mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB | CRYP_CR_ALGODIR);
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES ECB decryption mode
+ * then decrypted pCypherData. The cypher data are available in pPlainData
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16.
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES Key mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Get Timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(CRYP->SR, CRYP_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Reset the ALGOMODE bits*/
+ CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
+
+ /* Set the CRYP peripheral in AES CBC decryption mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC | CRYP_CR_ALGODIR);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CTR decryption mode
+ * then decrypted pCypherData. The cypher data are available in pPlainData
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16.
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CTR mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR | CRYP_CR_ALGODIR);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES ECB encryption mode using Interrupt.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Locked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CBC encryption mode using Interrupt.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CBC mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Locked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CTR encryption mode using Interrupt.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CTR mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Initializes the CRYP peripheral in AES ECB decryption mode using Interrupt.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16.
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t timeout = 0;
+
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES Key mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while(HAL_IS_BIT_SET(CRYP->SR, CRYP_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Reset the ALGOMODE bits*/
+ CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
+
+ /* Set the CRYP peripheral in AES ECB decryption mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB | CRYP_CR_ALGODIR);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CBC decryption mode using IT.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Get the buffer addresses and sizes */
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES Key mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while(HAL_IS_BIT_SET(CRYP->SR, CRYP_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Reset the ALGOMODE bits*/
+ CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
+
+ /* Set the CRYP peripheral in AES CBC decryption mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC | CRYP_CR_ALGODIR);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CTR decryption mode using Interrupt.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Get the buffer addresses and sizes */
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CTR mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR | CRYP_CR_ALGODIR);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES ECB encryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pPlainData;
+ outputaddr = (uint32_t)pCypherData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CBC encryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16.
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pPlainData;
+ outputaddr = (uint32_t)pCypherData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CTR encryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16.
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pPlainData;
+ outputaddr = (uint32_t)pCypherData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES ECB decryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pCypherData;
+ outputaddr = (uint32_t)pPlainData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES Key mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while(HAL_IS_BIT_SET(CRYP->SR, CRYP_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Reset the ALGOMODE bits*/
+ CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
+
+ /* Set the CRYP peripheral in AES ECB decryption mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB | CRYP_CR_ALGODIR);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CBC encryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pCypherData;
+ outputaddr = (uint32_t)pPlainData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES Key mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_KEY | CRYP_CR_ALGODIR);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while(HAL_IS_BIT_SET(CRYP->SR, CRYP_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Reset the ALGOMODE bits*/
+ CRYP->CR &= (uint32_t)(~CRYP_CR_ALGOMODE);
+
+ /* Set the CRYP peripheral in AES CBC decryption mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC | CRYP_CR_ALGODIR);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CTR decryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pCypherData;
+ outputaddr = (uint32_t)pPlainData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CTR mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR | CRYP_CR_ALGODIR);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+
+/**
+ * @}
+ */
+/** @defgroup CRYP_Group3 DES processing functions
+ * @brief processing functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### DES processing functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Encrypt plaintext using DES using ECB or CBC chaining modes
+ (+) Decrypt cyphertext using using ECB or CBC chaining modes
+ [..] Three processing functions are available:
+ (+) polling mode
+ (+) interrupt mode
+ (+) DMA mode
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the CRYP peripheral in DES ECB encryption mode.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES ECB encryption mode */
+ CRYP_SetDESECBMode(hcryp, 0);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES ECB decryption mode.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES ECB decryption mode */
+ CRYP_SetDESECBMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES CBC encryption mode.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES CBC encryption mode */
+ CRYP_SetDESCBCMode(hcryp, 0);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES ECB decryption mode.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES CBC decryption mode */
+ CRYP_SetDESCBCMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES ECB encryption mode using IT.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES ECB encryption mode */
+ CRYP_SetDESECBMode(hcryp, 0);
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+
+ hcryp->pCrypInBuffPtr += 8;
+ hcryp->CrypInCount -= 8;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+
+ hcryp->pCrypOutBuffPtr += 8;
+ hcryp->CrypOutCount -= 8;
+ if(hcryp->CrypOutCount == 0)
+ {
+ /* Disable IT */
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES CBC encryption mode using interrupt.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES CBC encryption mode */
+ CRYP_SetDESCBCMode(hcryp, 0);
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+
+ hcryp->pCrypInBuffPtr += 8;
+ hcryp->CrypInCount -= 8;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+
+ hcryp->pCrypOutBuffPtr += 8;
+ hcryp->CrypOutCount -= 8;
+ if(hcryp->CrypOutCount == 0)
+ {
+ /* Disable IT */
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES ECB decryption mode using IT.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES ECB decryption mode */
+ CRYP_SetDESECBMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+
+ hcryp->pCrypInBuffPtr += 8;
+ hcryp->CrypInCount -= 8;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+
+ hcryp->pCrypOutBuffPtr += 8;
+ hcryp->CrypOutCount -= 8;
+ if(hcryp->CrypOutCount == 0)
+ {
+ /* Disable IT */
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES ECB decryption mode using interrupt.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES CBC decryption mode */
+ CRYP_SetDESCBCMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+
+ hcryp->pCrypInBuffPtr += 8;
+ hcryp->CrypInCount -= 8;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+
+ hcryp->pCrypOutBuffPtr += 8;
+ hcryp->CrypOutCount -= 8;
+ if(hcryp->CrypOutCount == 0)
+ {
+ /* Disable IT */
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES ECB encryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pPlainData;
+ outputaddr = (uint32_t)pCypherData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES ECB encryption mode */
+ CRYP_SetDESECBMode(hcryp, 0);
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES CBC encryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pPlainData;
+ outputaddr = (uint32_t)pCypherData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES CBC encryption mode */
+ CRYP_SetDESCBCMode(hcryp, 0);
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES ECB decryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pCypherData;
+ outputaddr = (uint32_t)pPlainData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES ECB decryption mode */
+ CRYP_SetDESECBMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in DES ECB decryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pCypherData;
+ outputaddr = (uint32_t)pPlainData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in DES CBC decryption mode */
+ CRYP_SetDESCBCMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup CRYP_Group4 TDES processing functions
+ * @brief processing functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### TDES processing functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Encrypt plaintext using TDES using ECB or CBC chaining modes
+ (+) Decrypt cyphertext using TDES using ECB or CBC chaining modes
+ [..] Three processing functions are available:
+ (+) polling mode
+ (+) interrupt mode
+ (+) DMA mode
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES ECB encryption mode
+ * then encrypt pPlainData. The cypher data are available in pCypherData
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES ECB encryption mode */
+ CRYP_SetTDESECBMode(hcryp, 0);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES ECB decryption mode
+ * then decrypted pCypherData. The cypher data are available in pPlainData
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES ECB decryption mode */
+ CRYP_SetTDESECBMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Write Cypher Data and Get Plain Data */
+ if(CRYP_ProcessData2Words(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES CBC encryption mode
+ * then encrypt pPlainData. The cypher data are available in pCypherData
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES CBC encryption mode */
+ CRYP_SetTDESCBCMode(hcryp, 0);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYP_ProcessData2Words(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES CBC decryption mode
+ * then decrypted pCypherData. The cypher data are available in pPlainData
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
+{
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES CBC decryption mode */
+ CRYP_SetTDESCBCMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Write Cypher Data and Get Plain Data */
+ if(CRYP_ProcessData2Words(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES ECB encryption mode using interrupt.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES ECB encryption mode */
+ CRYP_SetTDESECBMode(hcryp, 0);
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+
+ hcryp->pCrypInBuffPtr += 8;
+ hcryp->CrypInCount -= 8;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+
+ hcryp->pCrypOutBuffPtr += 8;
+ hcryp->CrypOutCount -= 8;
+ if(hcryp->CrypOutCount == 0)
+ {
+ /* Disable IT */
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call the Output data transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES CBC encryption mode.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES CBC encryption mode */
+ CRYP_SetTDESCBCMode(hcryp, 0);
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+
+ hcryp->pCrypInBuffPtr += 8;
+ hcryp->CrypInCount -= 8;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+
+ hcryp->pCrypOutBuffPtr += 8;
+ hcryp->CrypOutCount -= 8;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES ECB decryption mode.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES ECB decryption mode */
+ CRYP_SetTDESECBMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+
+ hcryp->pCrypInBuffPtr += 8;
+ hcryp->CrypInCount -= 8;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+
+ hcryp->pCrypOutBuffPtr += 8;
+ hcryp->CrypOutCount -= 8;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES CBC decryption mode.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES CBC decryption mode */
+ CRYP_SetTDESCBCMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+
+ hcryp->pCrypInBuffPtr += 8;
+ hcryp->CrypInCount -= 8;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if(__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+
+ hcryp->pCrypOutBuffPtr += 8;
+ hcryp->CrypOutCount -= 8;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES ECB encryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pPlainData;
+ outputaddr = (uint32_t)pCypherData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES ECB encryption mode */
+ CRYP_SetTDESECBMode(hcryp, 0);
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES CBC encryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pPlainData;
+ outputaddr = (uint32_t)pCypherData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES CBC encryption mode */
+ CRYP_SetTDESCBCMode(hcryp, 0);
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES ECB decryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pCypherData;
+ outputaddr = (uint32_t)pPlainData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES ECB decryption mode */
+ CRYP_SetTDESECBMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in TDES CBC decryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 8
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pCypherData;
+ outputaddr = (uint32_t)pPlainData;
+
+ /* Change the CRYP state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Set CRYP peripheral in TDES CBC decryption mode */
+ CRYP_SetTDESCBCMode(hcryp, CRYP_CR_ALGODIR);
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup CRYP_Group5 DMA callback functions
+ * @brief DMA callback functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### DMA callback functions #####
+ ==============================================================================
+ [..] This section provides DMA callback functions:
+ (+) DMA Input data transfer complete
+ (+) DMA Output data transfer complete
+ (+) DMA error
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Input FIFO transfer completed callbacks.
+ * @param hcryp: CRYP handle
+ * @retval None
+ */
+__weak void HAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CRYP_InCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Output FIFO transfer completed callbacks.
+ * @param hcryp: CRYP handle
+ * @retval None
+ */
+__weak void HAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CRYP_OutCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief CRYP error callbacks.
+ * @param hcryp: CRYP handle
+ * @retval None
+ */
+ __weak void HAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_CRYP_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup CRYP_Group6 CRYP IRQ handler management
+ * @brief CRYP IRQ handler.
+ *
+@verbatim
+ ==============================================================================
+ ##### CRYP IRQ handler management #####
+ ==============================================================================
+[..] This section provides CRYP IRQ handler function.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief This function handles CRYP interrupt request.
+ * @param hcryp: CRYP handle
+ * @retval None
+ */
+void HAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp)
+{
+ switch(CRYP->CR & CRYP_CR_ALGOMODE_DIRECTION)
+ {
+ case CRYP_CR_ALGOMODE_TDES_ECB_ENCRYPT:
+ HAL_CRYP_TDESECB_Encrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_TDES_ECB_DECRYPT:
+ HAL_CRYP_TDESECB_Decrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_TDES_CBC_ENCRYPT:
+ HAL_CRYP_TDESCBC_Encrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_TDES_CBC_DECRYPT:
+ HAL_CRYP_TDESCBC_Decrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_DES_ECB_ENCRYPT:
+ HAL_CRYP_DESECB_Encrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_DES_ECB_DECRYPT:
+ HAL_CRYP_DESECB_Decrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_DES_CBC_ENCRYPT:
+ HAL_CRYP_DESCBC_Encrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_DES_CBC_DECRYPT:
+ HAL_CRYP_DESCBC_Decrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT:
+ HAL_CRYP_AESECB_Encrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_AES_ECB_DECRYPT:
+ HAL_CRYP_AESECB_Decrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT:
+ HAL_CRYP_AESCBC_Encrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_AES_CBC_DECRYPT:
+ HAL_CRYP_AESCBC_Decrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT:
+ HAL_CRYP_AESCTR_Encrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_AES_CTR_DECRYPT:
+ HAL_CRYP_AESCTR_Decrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ default:
+ break;
+ }
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup CRYP_Group7 Peripheral State functions
+ * @brief Peripheral State functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State functions #####
+ ==============================================================================
+ [..]
+ This subsection permits to get in run-time the status of the peripheral.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the CRYP state.
+ * @param hcryp: CRYP handle
+ * @retval HAL state
+ */
+HAL_CRYP_STATETypeDef HAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp)
+{
+ return hcryp->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief DMA CRYP Input Data process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma)
+{
+ CRYP_HandleTypeDef* hcryp = (CRYP_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Disable the DMA transfer for input FIFO request by resetting the DIEN bit
+ in the DMACR register */
+ CRYP->DMACR &= (uint32_t)(~CRYP_DMACR_DIEN);
+
+ /* Call input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+}
+
+/**
+ * @brief DMA CRYP Output Data process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma)
+{
+ CRYP_HandleTypeDef* hcryp = (CRYP_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Disable the DMA transfer for output FIFO request by resetting the DOEN bit
+ in the DMACR register */
+ CRYP->DMACR &= (uint32_t)(~CRYP_DMACR_DOEN);
+
+ /* Disable CRYP */
+ __HAL_CRYP_DISABLE();
+
+ /* Change the CRYP state to ready */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Call output data transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+}
+
+/**
+ * @brief DMA CRYP communication error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void CRYP_DMAError(DMA_HandleTypeDef *hdma)
+{
+ CRYP_HandleTypeDef* hcryp = (CRYP_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+ hcryp->State= HAL_CRYP_STATE_READY;
+ HAL_CRYP_ErrorCallback(hcryp);
+}
+
+/**
+ * @brief Writes the Key in Key registers.
+ * @param hcryp: CRYP handle
+ * @param Key: Pointer to Key buffer
+ * @param KeySize: Size of Key
+ * @retval None
+ */
+static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint8_t *Key, uint32_t KeySize)
+{
+ uint32_t keyaddr = (uint32_t)Key;
+
+ switch(KeySize)
+ {
+ case CRYP_KEYSIZE_256B:
+ /* Key Initialisation */
+ CRYP->K0LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K0RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K1LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K1RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3RR = __REV(*(uint32_t*)(keyaddr));
+ break;
+ case CRYP_KEYSIZE_192B:
+ CRYP->K1LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K1RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3RR = __REV(*(uint32_t*)(keyaddr));
+ break;
+ case CRYP_KEYSIZE_128B:
+ CRYP->K2LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3RR = __REV(*(uint32_t*)(keyaddr));
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * @brief Writes the InitVector/InitCounter in IV registers.
+ * @param hcryp: CRYP handle
+ * @param InitVector: Pointer to InitVector/InitCounter buffer
+ * @param IVSize: Size of the InitVector/InitCounter
+ * @retval None
+ */
+static void CRYP_SetInitVector(CRYP_HandleTypeDef *hcryp, uint8_t *InitVector, uint32_t IVSize)
+{
+ uint32_t ivaddr = (uint32_t)InitVector;
+
+ switch(IVSize)
+ {
+ case CRYP_KEYSIZE_128B:
+ CRYP->IV0LR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV0RR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV1LR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV1RR = __REV(*(uint32_t*)(ivaddr));
+ break;
+ /* Whatever key size 192 or 256, Init vector is written in IV0LR and IV0RR */
+ case CRYP_KEYSIZE_192B:
+ CRYP->IV0LR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV0RR = __REV(*(uint32_t*)(ivaddr));
+ break;
+ case CRYP_KEYSIZE_256B:
+ CRYP->IV0LR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV0RR = __REV(*(uint32_t*)(ivaddr));
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * @brief Process Data: Writes Input data in polling mode and read the output data
+ * @param hcryp: CRYP handle
+ * @param Input: Pointer to the Input buffer
+ * @param Ilength: Length of the Input buffer, must be a multiple of 16.
+ * @param Output: Pointer to the returned buffer
+ * @retval None
+ */
+static HAL_StatusTypeDef CRYP_ProcessData(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ uint32_t i = 0;
+ uint32_t inputaddr = (uint32_t)Input;
+ uint32_t outputaddr = (uint32_t)Output;
+
+ for(i=0; (i < Ilength); i+=16)
+ {
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_OFNE))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ }
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Process Data: Write Input data in polling mode.
+ * @param hcryp: CRYP handle
+ * @param Input: Pointer to the Input buffer
+ * @param Ilength: Length of the Input buffer, must be a multiple of 8
+ * @param Output: Pointer to the returned buffer
+ * @param Timeout: Specify Timeout value
+ * @retval None
+ */
+static HAL_StatusTypeDef CRYP_ProcessData2Words(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ uint32_t i = 0;
+ uint32_t inputaddr = (uint32_t)Input;
+ uint32_t outputaddr = (uint32_t)Output;
+
+ for(i=0; (i < Ilength); i+=8)
+ {
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_OFNE))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ }
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Set the DMA configuration and start the DMA transfer
+ * @param hcryp: CRYP handle
+ * @param inputaddr: address of the Input buffer
+ * @param Size: Size of the Input buffer, must be a multiple of 16.
+ * @param outputaddr: address of the Output buffer
+ * @retval None
+ */
+static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr)
+{
+ /* Set the CRYP DMA transfer complete callback */
+ hcryp->hdmain->XferCpltCallback = CRYP_DMAInCplt;
+ /* Set the DMA error callback */
+ hcryp->hdmain->XferErrorCallback = CRYP_DMAError;
+
+ /* Set the CRYP DMA transfer complete callback */
+ hcryp->hdmaout->XferCpltCallback = CRYP_DMAOutCplt;
+ /* Set the DMA error callback */
+ hcryp->hdmaout->XferErrorCallback = CRYP_DMAError;
+
+ /* Enable CRYP */
+ __HAL_CRYP_ENABLE();
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hcryp->hdmain, inputaddr, (uint32_t)&CRYP->DR, Size/4);
+
+ /* Enable In DMA request */
+ CRYP->DMACR = (CRYP_DMACR_DIEN);
+
+ /* Enable the DMA Out DMA Stream */
+ HAL_DMA_Start_IT(hcryp->hdmaout, (uint32_t)&CRYP->DOUT, outputaddr, Size/4);
+
+ /* Enable Out DMA request */
+ CRYP->DMACR |= CRYP_DMACR_DOEN;
+
+}
+
+/**
+ * @brief Sets the CRYP peripheral in DES ECB mode.
+ * @param hcryp: CRYP handle
+ * @param Direction: Encryption or decryption
+ * @retval None
+ */
+static void CRYP_SetDESECBMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction)
+{
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_DES_ECB | Direction);
+
+ /* Set the key */
+ CRYP->K1LR = __REV(*(uint32_t*)(hcryp->Init.pKey));
+ CRYP->K1RR = __REV(*(uint32_t*)(hcryp->Init.pKey+4));
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+}
+
+/**
+ * @brief Sets the CRYP peripheral in DES CBC mode.
+ * @param hcryp: CRYP handle
+ * @param Direction: Encryption or decryption
+ * @retval None
+ */
+static void CRYP_SetDESCBCMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction)
+{
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_DES_CBC | Direction);
+
+ /* Set the key */
+ CRYP->K1LR = __REV(*(uint32_t*)(hcryp->Init.pKey));
+ CRYP->K1RR = __REV(*(uint32_t*)(hcryp->Init.pKey+4));
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_256B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+}
+
+/**
+ * @brief Sets the CRYP peripheral in TDES ECB mode.
+ * @param hcryp: CRYP handle
+ * @param Direction: Encryption or decryption
+ * @retval None
+ */
+static void CRYP_SetTDESECBMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction)
+{
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the CRYP peripheral in AES ECB mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_TDES_ECB | Direction);
+
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, CRYP_KEYSIZE_192B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+}
+
+/**
+ * @brief Sets the CRYP peripheral in TDES CBC mode
+ * @param hcryp: CRYP handle
+ * @param Direction: Encryption or decryption
+ * @retval None
+ */
+static void CRYP_SetTDESCBCMode(CRYP_HandleTypeDef *hcryp, uint32_t Direction)
+{
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the CRYP peripheral in AES CBC mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_TDES_CBC | Direction);
+
+ /* Set the key */
+ CRYP_SetKey(hcryp, hcryp->Init.pKey, CRYP_KEYSIZE_192B);
+
+ /* Set the Initialization Vector */
+ CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_256B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+}
+
+/**
+ * @}
+ */
+
+#endif /* STM32F415xx || STM32F417xx || STM32F437xx || STM32F439xx */
+
+#endif /* HAL_CRYP_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cryp_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cryp_ex.c
new file mode 100644
index 0000000..8887047
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cryp_ex.c
@@ -0,0 +1,2998 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_cryp_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief Extended CRYP HAL module driver
+ * This file provides firmware functions to manage the following
+ * functionalities of CRYP extension peripheral:
+ * + Extended AES processing functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The CRYP Extension HAL driver can be used as follows:
+ (#)Initialize the CRYP low level resources by implementing the HAL_CRYP_MspInit():
+ (##) Enable the CRYP interface clock using __CRYP_CLK_ENABLE()
+ (##) In case of using interrupts (e.g. HAL_CRYPEx_AESGCM_Encrypt_IT())
+ (+++) Configure the CRYP interrupt priority using HAL_NVIC_SetPriority()
+ (+++) Enable the CRYP IRQ handler using HAL_NVIC_EnableIRQ()
+ (+) In CRYP IRQ handler, call HAL_CRYP_IRQHandler()
+ (##) In case of using DMA to control data transfer (e.g. HAL_AES_ECB_Encrypt_DMA())
+ (+++) Enable the DMAx interface clock using __DMAx_CLK_ENABLE()
+ (+++) Configure and enable two DMA streams one for managing data transfer from
+ memory to peripheral (input stream) and another stream for managing data
+ transfer from peripheral to memory (output stream)
+ (+++) Associate the initilalized DMA handle to the CRYP DMA handle
+ using __HAL_LINKDMA()
+ (+++) Configure the priority and enable the NVIC for the transfer complete
+ interrupt on the two DMA Streams. The output stream should have higher
+ priority than the input stream HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ()
+ (#)Initialize the CRYP HAL using HAL_CRYP_Init(). This function configures mainly:
+ (##) The data type: 1-bit, 8-bit, 16-bit and 32-bit
+ (##) The key size: 128, 192 and 256. This parameter is relevant only for AES
+ (##) The encryption/decryption key. Its size depends on the algorithm
+ used for encryption/decryption
+ (##) The initialization vector (counter). It is not used ECB mode.
+ (#)Three processing (encryption/decryption) functions are available:
+ (##) Polling mode: encryption and decryption APIs are blocking functions
+ i.e. they process the data and wait till the processing is finished
+ e.g. HAL_CRYPEx_AESGCM_Encrypt()
+ (##) Interrupt mode: encryption and decryption APIs are not blocking functions
+ i.e. they process the data under interrupt
+ e.g. HAL_CRYPEx_AESGCM_Encrypt_IT()
+ (##) DMA mode: encryption and decryption APIs are not blocking functions
+ i.e. the data transfer is ensured by DMA
+ e.g. HAL_CRYPEx_AESGCM_Encrypt_DMA()
+ (#)When the processing function is called at first time after HAL_CRYP_Init()
+ the CRYP peripheral is initialized and processes the buffer in input.
+ At second call, the processing function performs an append of the already
+ processed buffer.
+ When a new data block is to be processed, call HAL_CRYP_Init() then the
+ processing function.
+ (#)In AES-GCM and AES-CCM modes are an authenticated encryption algorithms
+ which provide authentication messages.
+ HAL_AES_GCM_Finish() and HAL_AES_CCM_Finish() are used to provide those
+ authentication messages.
+ Call those functions after the processing ones (polling, interrupt or DMA).
+ e.g. in AES-CCM mode call HAL_CRYPEx_AESCCM_Encrypt() to encrypt the plain data
+ then call HAL_CRYPEx_AESCCM_Finish() to get the authentication message
+ (#)Call HAL_CRYP_DeInit() to deinitialize the CRYP peripheral.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup CRYPEx
+ * @brief CRYP Extension HAL module driver.
+ * @{
+ */
+
+#ifdef HAL_CRYP_MODULE_ENABLED
+
+#if defined(STM32F437xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void CRYPEx_GCMCCM_SetInitVector(CRYP_HandleTypeDef *hcryp, uint8_t *InitVector, uint32_t IVSize);
+static void CRYPEx_GCMCCM_SetKey(CRYP_HandleTypeDef *hcryp, uint8_t *Key, uint32_t KeySize);
+static HAL_StatusTypeDef CRYPEx_GCMCCM_ProcessData(CRYP_HandleTypeDef *hcryp, uint8_t *Input, uint16_t Ilength, uint8_t *Output, uint32_t Timeout);
+static HAL_StatusTypeDef CRYPEx_GCMCCM_SetHeaderPhase(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint32_t Timeout);
+static void CRYPEx_GCMCCM_DMAInCplt(DMA_HandleTypeDef *hdma);
+static void CRYPEx_GCMCCM_DMAOutCplt(DMA_HandleTypeDef *hdma);
+static void CRYPEx_GCMCCM_DMAError(DMA_HandleTypeDef *hdma);
+static void CRYPEx_GCMCCM_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup CRYPEx_Private_Functions
+ * @{
+ */
+
+/** @defgroup CRYPEx_Group1 Extended AES processing functions
+ * @brief Extended processing functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### Extended AES processing functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Encrypt plaintext using AES-128/192/256 using GCM and CCM chaining modes
+ (+) Decrypt cyphertext using AES-128/192/256 using GCM and CCM chaining modes
+ (+) Finish the processing. This function is available only for GCM and CCM
+ [..] Three processing methods are available:
+ (+) Polling mode
+ (+) Interrupt mode
+ (+) DMA mode
+
+@endverbatim
+ * @{
+ */
+
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CCM encryption mode then
+ * encrypt pPlainData. The cypher data are available in pCypherData.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+ uint32_t headersize = hcryp->Init.HeaderSize;
+ uint32_t headeraddr = (uint32_t)hcryp->Init.Header;
+ uint32_t loopcounter = 0;
+ uint32_t bufferidx = 0;
+ uint8_t blockb0[16] = {0};/* Block B0 */
+ uint8_t ctr[16] = {0}; /* Counter */
+ uint32_t b0addr = (uint32_t)blockb0;
+
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /************************ Formatting the header block *********************/
+ if(headersize != 0)
+ {
+ /* Check that the associated data (or header) length is lower than 2^16 - 2^8 = 65536 - 256 = 65280 */
+ if(headersize < 65280)
+ {
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize >> 8) & 0xFF);
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize) & 0xFF);
+ headersize += 2;
+ }
+ else
+ {
+ /* Header is encoded as 0xff || 0xfe || [headersize]32, i.e., six octets */
+ hcryp->Init.pScratch[bufferidx++] = 0xFF;
+ hcryp->Init.pScratch[bufferidx++] = 0xFE;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0xff000000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x00ff0000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x0000ff00;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x000000ff;
+ headersize += 6;
+ }
+ /* Copy the header buffer in internal buffer "hcryp->Init.pScratch" */
+ for(loopcounter = 0; loopcounter < headersize; loopcounter++)
+ {
+ hcryp->Init.pScratch[bufferidx++] = hcryp->Init.Header[loopcounter];
+ }
+ /* Check if the header size is modulo 16 */
+ if ((headersize % 16) != 0)
+ {
+ /* Padd the header buffer with 0s till the hcryp->Init.pScratch length is modulo 16 */
+ for(loopcounter = headersize; loopcounter <= ((headersize/16) + 1) * 16; loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = 0;
+ }
+ /* Set the header size to modulo 16 */
+ headersize = ((headersize/16) + 1) * 16;
+ }
+ /* Set the pointer headeraddr to hcryp->Init.pScratch */
+ headeraddr = (uint32_t)hcryp->Init.pScratch;
+ }
+ /*********************** Formatting the block B0 **************************/
+ if(headersize != 0)
+ {
+ blockb0[0] = 0x40;
+ }
+ /* Flags byte */
+ /* blockb0[0] |= 0u | (((( (uint8_t) hcryp->Init.TagSize - 2) / 2) & 0x07 ) << 3 ) | ( ( (uint8_t) (15 - hcryp->Init.IVSize) - 1) & 0x07) */
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)(((uint8_t)(hcryp->Init.TagSize - (uint8_t)(2))) >> 1) & (uint8_t)0x07 ) << 3);
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)((uint8_t)(15) - hcryp->Init.IVSize) - (uint8_t)1) & (uint8_t)0x07);
+
+ for (loopcounter = 0; loopcounter < hcryp->Init.IVSize; loopcounter++)
+ {
+ blockb0[loopcounter+1] = hcryp->Init.pInitVect[loopcounter];
+ }
+ for ( ; loopcounter < 13; loopcounter++)
+ {
+ blockb0[loopcounter+1] = 0;
+ }
+
+ blockb0[14] = (Size >> 8);
+ blockb0[15] = (Size & 0xFF);
+
+ /************************* Formatting the initial counter *****************/
+ /* Byte 0:
+ Bits 7 and 6 are reserved and shall be set to 0
+ Bits 3, 4, and 5 shall also be set to 0, to ensure that all the counter blocks
+ are distinct from B0
+ Bits 0, 1, and 2 contain the same encoding of q as in B0
+ */
+ ctr[0] = blockb0[0] & 0x07;
+ /* byte 1 to NonceSize is the IV (Nonce) */
+ for(loopcounter = 1; loopcounter < hcryp->Init.IVSize + 1; loopcounter++)
+ {
+ ctr[loopcounter] = blockb0[loopcounter];
+ }
+ /* Set the LSB to 1 */
+ ctr[15] |= 0x01;
+
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CCM mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CCM_ENCRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, ctr, CRYP_KEYSIZE_128B);
+
+ /* Select init phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_INIT);
+
+ b0addr = (uint32_t)blockb0;
+ /* Write the blockb0 block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /***************************** Header phase *******************************/
+ if(headersize != 0)
+ {
+ /* Select header phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_HEADER);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ for(loopcounter = 0; (loopcounter < headersize); loopcounter+=16)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_IFEM))
+ {
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ /* Write the header block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ }
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((CRYP->SR & CRYP_FLAG_BUSY) == CRYP_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ /* Save formatted counter into the scratch buffer pScratch */
+ for(loopcounter = 0; (loopcounter < 16); loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = ctr[loopcounter];
+ }
+ /* Reset bit 0 */
+ hcryp->Init.pScratch[15] &= 0xfe;
+
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYPEx_GCMCCM_ProcessData(hcryp,pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES GCM encryption mode then
+ * encrypt pPlainData. The cypher data are available in pCypherData.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES GCM mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_GCM_ENCRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Set the header phase */
+ if(CRYPEx_GCMCCM_SetHeaderPhase(hcryp, hcryp->Init.Header, hcryp->Init.HeaderSize, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Disable the CRYP peripheral */
+ __HAL_CRYP_DISABLE();
+
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYPEx_GCMCCM_ProcessData(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES GCM decryption mode then
+ * decrypted pCypherData. The cypher data are available in pPlainData.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the cyphertext buffer, must be a multiple of 16
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES GCM decryption mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_GCM_DECRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Get the timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Set the header phase */
+ if(CRYPEx_GCMCCM_SetHeaderPhase(hcryp, hcryp->Init.Header, hcryp->Init.HeaderSize, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ /* Disable the CRYP peripheral */
+ __HAL_CRYP_DISABLE();
+
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYPEx_GCMCCM_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Computes the authentication TAG.
+ * @param hcryp: CRYP handle
+ * @param Size: Total length of the plain/cyphertext buffer
+ * @param AuthTag: Pointer to the authentication buffer
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Finish(CRYP_HandleTypeDef *hcryp, uint16_t Size, uint8_t *AuthTag, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+ uint32_t headerlength = hcryp->Init.HeaderSize * 8; /* Header length in bits */
+ uint32_t inputlength = Size * 8; /* input length in bits */
+ uint32_t tagaddr = (uint32_t)AuthTag;
+
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_PROCESS)
+ {
+ /* Change the CRYP phase */
+ hcryp->Phase = HAL_CRYP_PHASE_FINAL;
+
+ /* Disable CRYP to start the final phase */
+ __HAL_CRYP_DISABLE();
+
+ /* Select final phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_FINAL);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Write the number of bits in header (64 bits) followed by the number of bits
+ in the payload */
+ if(hcryp->Init.DataType == CRYP_DATATYPE_1B)
+ {
+ CRYP->DR = 0;
+ CRYP->DR = __RBIT(headerlength);
+ CRYP->DR = 0;
+ CRYP->DR = __RBIT(inputlength);
+ }
+ else if(hcryp->Init.DataType == CRYP_DATATYPE_8B)
+ {
+ CRYP->DR = 0;
+ CRYP->DR = __REV(headerlength);
+ CRYP->DR = 0;
+ CRYP->DR = __REV(inputlength);
+ }
+ else if(hcryp->Init.DataType == CRYP_DATATYPE_16B)
+ {
+ CRYP->DR = 0;
+ CRYP->DR = __REV16(headerlength);
+ CRYP->DR = 0;
+ CRYP->DR = __REV16(inputlength);
+ }
+ else if(hcryp->Init.DataType == CRYP_DATATYPE_32B)
+ {
+ CRYP->DR = 0;
+ CRYP->DR = (uint32_t)(headerlength);
+ CRYP->DR = 0;
+ CRYP->DR = (uint32_t)(inputlength);
+ }
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_OFNE))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the Auth TAG in the IN FIFO */
+ *(uint32_t*)(tagaddr) = CRYP->DOUT;
+ tagaddr+=4;
+ *(uint32_t*)(tagaddr) = CRYP->DOUT;
+ tagaddr+=4;
+ *(uint32_t*)(tagaddr) = CRYP->DOUT;
+ tagaddr+=4;
+ *(uint32_t*)(tagaddr) = CRYP->DOUT;
+ }
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Computes the authentication TAG for AES CCM mode.
+ * @note This API is called after HAL_AES_CCM_Encrypt()/HAL_AES_CCM_Decrypt()
+ * @param hcryp: CRYP handle
+ * @param AuthTag: Pointer to the authentication buffer
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Finish(CRYP_HandleTypeDef *hcryp, uint8_t *AuthTag, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+ uint32_t tagaddr = (uint32_t)AuthTag;
+ uint32_t ctraddr = (uint32_t)hcryp->Init.pScratch;
+ uint32_t temptag[4] = {0}; /* Temporary TAG (MAC) */
+ uint32_t loopcounter;
+
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_PROCESS)
+ {
+ /* Change the CRYP phase */
+ hcryp->Phase = HAL_CRYP_PHASE_FINAL;
+
+ /* Disable CRYP to start the final phase */
+ __HAL_CRYP_DISABLE();
+
+ /* Select final phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_FINAL);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Write the counter block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)ctraddr;
+ ctraddr+=4;
+ CRYP->DR = *(uint32_t*)ctraddr;
+ ctraddr+=4;
+ CRYP->DR = *(uint32_t*)ctraddr;
+ ctraddr+=4;
+ CRYP->DR = *(uint32_t*)ctraddr;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_OFNE))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the Auth TAG in the IN FIFO */
+ temptag[0] = CRYP->DOUT;
+ temptag[1] = CRYP->DOUT;
+ temptag[2] = CRYP->DOUT;
+ temptag[3] = CRYP->DOUT;
+ }
+
+ /* Copy temporary authentication TAG in user TAG buffer */
+ for(loopcounter = 0; loopcounter < hcryp->Init.TagSize ; loopcounter++)
+ {
+ /* Set the authentication TAG buffer */
+ *((uint8_t*)tagaddr+loopcounter) = *((uint8_t*)temptag+loopcounter);
+ }
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CCM decryption mode then
+ * decrypted pCypherData. The cypher data are available in pPlainData.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+ uint32_t headersize = hcryp->Init.HeaderSize;
+ uint32_t headeraddr = (uint32_t)hcryp->Init.Header;
+ uint32_t loopcounter = 0;
+ uint32_t bufferidx = 0;
+ uint8_t blockb0[16] = {0};/* Block B0 */
+ uint8_t ctr[16] = {0}; /* Counter */
+ uint32_t b0addr = (uint32_t)blockb0;
+
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /************************ Formatting the header block *********************/
+ if(headersize != 0)
+ {
+ /* Check that the associated data (or header) length is lower than 2^16 - 2^8 = 65536 - 256 = 65280 */
+ if(headersize < 65280)
+ {
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize >> 8) & 0xFF);
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize) & 0xFF);
+ headersize += 2;
+ }
+ else
+ {
+ /* Header is encoded as 0xff || 0xfe || [headersize]32, i.e., six octets */
+ hcryp->Init.pScratch[bufferidx++] = 0xFF;
+ hcryp->Init.pScratch[bufferidx++] = 0xFE;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0xff000000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x00ff0000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x0000ff00;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x000000ff;
+ headersize += 6;
+ }
+ /* Copy the header buffer in internal buffer "hcryp->Init.pScratch" */
+ for(loopcounter = 0; loopcounter < headersize; loopcounter++)
+ {
+ hcryp->Init.pScratch[bufferidx++] = hcryp->Init.Header[loopcounter];
+ }
+ /* Check if the header size is modulo 16 */
+ if ((headersize % 16) != 0)
+ {
+ /* Padd the header buffer with 0s till the hcryp->Init.pScratch length is modulo 16 */
+ for(loopcounter = headersize; loopcounter <= ((headersize/16) + 1) * 16; loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = 0;
+ }
+ /* Set the header size to modulo 16 */
+ headersize = ((headersize/16) + 1) * 16;
+ }
+ /* Set the pointer headeraddr to hcryp->Init.pScratch */
+ headeraddr = (uint32_t)hcryp->Init.pScratch;
+ }
+ /*********************** Formatting the block B0 **************************/
+ if(headersize != 0)
+ {
+ blockb0[0] = 0x40;
+ }
+ /* Flags byte */
+ /* blockb0[0] |= 0u | (((( (uint8_t) hcryp->Init.TagSize - 2) / 2) & 0x07 ) << 3 ) | ( ( (uint8_t) (15 - hcryp->Init.IVSize) - 1) & 0x07) */
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)(((uint8_t)(hcryp->Init.TagSize - (uint8_t)(2))) >> 1) & (uint8_t)0x07 ) << 3);
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)((uint8_t)(15) - hcryp->Init.IVSize) - (uint8_t)1) & (uint8_t)0x07);
+
+ for (loopcounter = 0; loopcounter < hcryp->Init.IVSize; loopcounter++)
+ {
+ blockb0[loopcounter+1] = hcryp->Init.pInitVect[loopcounter];
+ }
+ for ( ; loopcounter < 13; loopcounter++)
+ {
+ blockb0[loopcounter+1] = 0;
+ }
+
+ blockb0[14] = (Size >> 8);
+ blockb0[15] = (Size & 0xFF);
+
+ /************************* Formatting the initial counter *****************/
+ /* Byte 0:
+ Bits 7 and 6 are reserved and shall be set to 0
+ Bits 3, 4, and 5 shall also be set to 0, to ensure that all the counter
+ blocks are distinct from B0
+ Bits 0, 1, and 2 contain the same encoding of q as in B0
+ */
+ ctr[0] = blockb0[0] & 0x07;
+ /* byte 1 to NonceSize is the IV (Nonce) */
+ for(loopcounter = 1; loopcounter < hcryp->Init.IVSize + 1; loopcounter++)
+ {
+ ctr[loopcounter] = blockb0[loopcounter];
+ }
+ /* Set the LSB to 1 */
+ ctr[15] |= 0x01;
+
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CCM mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CCM_DECRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, ctr, CRYP_KEYSIZE_128B);
+
+ /* Select init phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_INIT);
+
+ b0addr = (uint32_t)blockb0;
+ /* Write the blockb0 block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /***************************** Header phase *******************************/
+ if(headersize != 0)
+ {
+ /* Select header phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_HEADER);
+
+ /* Enable Crypto processor */
+ __HAL_CRYP_ENABLE();
+
+ for(loopcounter = 0; (loopcounter < headersize); loopcounter+=16)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_IFEM))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Write the header block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ }
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((CRYP->SR & CRYP_FLAG_BUSY) == CRYP_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ /* Save formatted counter into the scratch buffer pScratch */
+ for(loopcounter = 0; (loopcounter < 16); loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = ctr[loopcounter];
+ }
+ /* Reset bit 0 */
+ hcryp->Init.pScratch[15] &= 0xfe;
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Write Plain Data and Get Cypher Data */
+ if(CRYPEx_GCMCCM_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES GCM encryption mode using IT.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Get the buffer addresses and sizes */
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES GCM mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_GCM_ENCRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP to start the init phase */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+
+ }
+ }
+
+ /* Set the header phase */
+ if(CRYPEx_GCMCCM_SetHeaderPhase(hcryp, hcryp->Init.Header, hcryp->Init.HeaderSize, 1) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ /* Disable the CRYP peripheral */
+ __HAL_CRYP_DISABLE();
+
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ if(Size != 0)
+ {
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+ }
+ else
+ {
+ /* Process Locked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state and phase */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ }
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if (__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if (__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CCM encryption mode using interrupt.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ uint32_t headersize = hcryp->Init.HeaderSize;
+ uint32_t headeraddr = (uint32_t)hcryp->Init.Header;
+ uint32_t loopcounter = 0;
+ uint32_t bufferidx = 0;
+ uint8_t blockb0[16] = {0};/* Block B0 */
+ uint8_t ctr[16] = {0}; /* Counter */
+ uint32_t b0addr = (uint32_t)blockb0;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /************************ Formatting the header block *******************/
+ if(headersize != 0)
+ {
+ /* Check that the associated data (or header) length is lower than 2^16 - 2^8 = 65536 - 256 = 65280 */
+ if(headersize < 65280)
+ {
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize >> 8) & 0xFF);
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize) & 0xFF);
+ headersize += 2;
+ }
+ else
+ {
+ /* Header is encoded as 0xff || 0xfe || [headersize]32, i.e., six octets */
+ hcryp->Init.pScratch[bufferidx++] = 0xFF;
+ hcryp->Init.pScratch[bufferidx++] = 0xFE;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0xff000000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x00ff0000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x0000ff00;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x000000ff;
+ headersize += 6;
+ }
+ /* Copy the header buffer in internal buffer "hcryp->Init.pScratch" */
+ for(loopcounter = 0; loopcounter < headersize; loopcounter++)
+ {
+ hcryp->Init.pScratch[bufferidx++] = hcryp->Init.Header[loopcounter];
+ }
+ /* Check if the header size is modulo 16 */
+ if ((headersize % 16) != 0)
+ {
+ /* Padd the header buffer with 0s till the hcryp->Init.pScratch length is modulo 16 */
+ for(loopcounter = headersize; loopcounter <= ((headersize/16) + 1) * 16; loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = 0;
+ }
+ /* Set the header size to modulo 16 */
+ headersize = ((headersize/16) + 1) * 16;
+ }
+ /* Set the pointer headeraddr to hcryp->Init.pScratch */
+ headeraddr = (uint32_t)hcryp->Init.pScratch;
+ }
+ /*********************** Formatting the block B0 ************************/
+ if(headersize != 0)
+ {
+ blockb0[0] = 0x40;
+ }
+ /* Flags byte */
+ /* blockb0[0] |= 0u | (((( (uint8_t) hcryp->Init.TagSize - 2) / 2) & 0x07 ) << 3 ) | ( ( (uint8_t) (15 - hcryp->Init.IVSize) - 1) & 0x07) */
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)(((uint8_t)(hcryp->Init.TagSize - (uint8_t)(2))) >> 1) & (uint8_t)0x07 ) << 3);
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)((uint8_t)(15) - hcryp->Init.IVSize) - (uint8_t)1) & (uint8_t)0x07);
+
+ for (loopcounter = 0; loopcounter < hcryp->Init.IVSize; loopcounter++)
+ {
+ blockb0[loopcounter+1] = hcryp->Init.pInitVect[loopcounter];
+ }
+ for ( ; loopcounter < 13; loopcounter++)
+ {
+ blockb0[loopcounter+1] = 0;
+ }
+
+ blockb0[14] = (Size >> 8);
+ blockb0[15] = (Size & 0xFF);
+
+ /************************* Formatting the initial counter ***************/
+ /* Byte 0:
+ Bits 7 and 6 are reserved and shall be set to 0
+ Bits 3, 4, and 5 shall also be set to 0, to ensure that all the counter
+ blocks are distinct from B0
+ Bits 0, 1, and 2 contain the same encoding of q as in B0
+ */
+ ctr[0] = blockb0[0] & 0x07;
+ /* byte 1 to NonceSize is the IV (Nonce) */
+ for(loopcounter = 1; loopcounter < hcryp->Init.IVSize + 1; loopcounter++)
+ {
+ ctr[loopcounter] = blockb0[loopcounter];
+ }
+ /* Set the LSB to 1 */
+ ctr[15] |= 0x01;
+
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CCM mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CCM_ENCRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, ctr, hcryp->Init.KeySize);
+
+ /* Select init phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_INIT);
+
+ b0addr = (uint32_t)blockb0;
+ /* Write the blockb0 block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /***************************** Header phase *****************************/
+ if(headersize != 0)
+ {
+ /* Select header phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_HEADER);
+
+ /* Enable Crypto processor */
+ __HAL_CRYP_ENABLE();
+
+ for(loopcounter = 0; (loopcounter < headersize); loopcounter+=16)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_IFEM))
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Write the header block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ }
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->SR & CRYP_FLAG_BUSY) == CRYP_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Save formatted counter into the scratch buffer pScratch */
+ for(loopcounter = 0; (loopcounter < 16); loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = ctr[loopcounter];
+ }
+ /* Reset bit 0 */
+ hcryp->Init.pScratch[15] &= 0xfe;
+
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ if(Size != 0)
+ {
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+ }
+ else
+ {
+ /* Change the CRYP state and phase */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ }
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if (__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call Input transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if (__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES GCM decryption mode using IT.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the cyphertext buffer, must be a multiple of 16
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ /* Get the buffer addresses and sizes */
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES GCM decryption mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_GCM_DECRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP to start the init phase */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Set the header phase */
+ if(CRYPEx_GCMCCM_SetHeaderPhase(hcryp, hcryp->Init.Header, hcryp->Init.HeaderSize, 1) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ /* Disable the CRYP peripheral */
+ __HAL_CRYP_DISABLE();
+
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ if(Size != 0)
+ {
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+ }
+ else
+ {
+ /* Process Locked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP state and phase */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ }
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if (__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if (__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CCM decryption mode using interrupt
+ * then decrypted pCypherData. The cypher data are available in pPlainData.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+ uint32_t timeout = 0;
+ uint32_t headersize = hcryp->Init.HeaderSize;
+ uint32_t headeraddr = (uint32_t)hcryp->Init.Header;
+ uint32_t loopcounter = 0;
+ uint32_t bufferidx = 0;
+ uint8_t blockb0[16] = {0};/* Block B0 */
+ uint8_t ctr[16] = {0}; /* Counter */
+ uint32_t b0addr = (uint32_t)blockb0;
+
+ if(hcryp->State == HAL_CRYP_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /************************ Formatting the header block *******************/
+ if(headersize != 0)
+ {
+ /* Check that the associated data (or header) length is lower than 2^16 - 2^8 = 65536 - 256 = 65280 */
+ if(headersize < 65280)
+ {
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize >> 8) & 0xFF);
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize) & 0xFF);
+ headersize += 2;
+ }
+ else
+ {
+ /* Header is encoded as 0xff || 0xfe || [headersize]32, i.e., six octets */
+ hcryp->Init.pScratch[bufferidx++] = 0xFF;
+ hcryp->Init.pScratch[bufferidx++] = 0xFE;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0xff000000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x00ff0000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x0000ff00;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x000000ff;
+ headersize += 6;
+ }
+ /* Copy the header buffer in internal buffer "hcryp->Init.pScratch" */
+ for(loopcounter = 0; loopcounter < headersize; loopcounter++)
+ {
+ hcryp->Init.pScratch[bufferidx++] = hcryp->Init.Header[loopcounter];
+ }
+ /* Check if the header size is modulo 16 */
+ if ((headersize % 16) != 0)
+ {
+ /* Padd the header buffer with 0s till the hcryp->Init.pScratch length is modulo 16 */
+ for(loopcounter = headersize; loopcounter <= ((headersize/16) + 1) * 16; loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = 0;
+ }
+ /* Set the header size to modulo 16 */
+ headersize = ((headersize/16) + 1) * 16;
+ }
+ /* Set the pointer headeraddr to hcryp->Init.pScratch */
+ headeraddr = (uint32_t)hcryp->Init.pScratch;
+ }
+ /*********************** Formatting the block B0 ************************/
+ if(headersize != 0)
+ {
+ blockb0[0] = 0x40;
+ }
+ /* Flags byte */
+ /* blockb0[0] |= 0u | (((( (uint8_t) hcryp->Init.TagSize - 2) / 2) & 0x07 ) << 3 ) | ( ( (uint8_t) (15 - hcryp->Init.IVSize) - 1) & 0x07) */
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)(((uint8_t)(hcryp->Init.TagSize - (uint8_t)(2))) >> 1) & (uint8_t)0x07 ) << 3);
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)((uint8_t)(15) - hcryp->Init.IVSize) - (uint8_t)1) & (uint8_t)0x07);
+
+ for (loopcounter = 0; loopcounter < hcryp->Init.IVSize; loopcounter++)
+ {
+ blockb0[loopcounter+1] = hcryp->Init.pInitVect[loopcounter];
+ }
+ for ( ; loopcounter < 13; loopcounter++)
+ {
+ blockb0[loopcounter+1] = 0;
+ }
+
+ blockb0[14] = (Size >> 8);
+ blockb0[15] = (Size & 0xFF);
+
+ /************************* Formatting the initial counter ***************/
+ /* Byte 0:
+ Bits 7 and 6 are reserved and shall be set to 0
+ Bits 3, 4, and 5 shall also be set to 0, to ensure that all the counter
+ blocks are distinct from B0
+ Bits 0, 1, and 2 contain the same encoding of q as in B0
+ */
+ ctr[0] = blockb0[0] & 0x07;
+ /* byte 1 to NonceSize is the IV (Nonce) */
+ for(loopcounter = 1; loopcounter < hcryp->Init.IVSize + 1; loopcounter++)
+ {
+ ctr[loopcounter] = blockb0[loopcounter];
+ }
+ /* Set the LSB to 1 */
+ ctr[15] |= 0x01;
+
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CCM mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CCM_DECRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, ctr, hcryp->Init.KeySize);
+
+ /* Select init phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_INIT);
+
+ b0addr = (uint32_t)blockb0;
+ /* Write the blockb0 block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /***************************** Header phase *****************************/
+ if(headersize != 0)
+ {
+ /* Select header phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_HEADER);
+
+ /* Enable Crypto processor */
+ __HAL_CRYP_ENABLE();
+
+ for(loopcounter = 0; (loopcounter < headersize); loopcounter+=16)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_IFEM))
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Write the header block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ }
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->SR & CRYP_FLAG_BUSY) == CRYP_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Save formatted counter into the scratch buffer pScratch */
+ for(loopcounter = 0; (loopcounter < 16); loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = ctr[loopcounter];
+ }
+ /* Reset bit 0 */
+ hcryp->Init.pScratch[15] &= 0xfe;
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Enable Interrupts */
+ __HAL_CRYP_ENABLE_IT(CRYP_IT_INI | CRYP_IT_OUTI);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else if (__HAL_CRYP_GET_IT(CRYP_IT_INI))
+ {
+ inputaddr = (uint32_t)hcryp->pCrypInBuffPtr;
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ hcryp->pCrypInBuffPtr += 16;
+ hcryp->CrypInCount -= 16;
+ if(hcryp->CrypInCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_INI);
+ /* Call the Input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+ }
+ }
+ else if (__HAL_CRYP_GET_IT(CRYP_IT_OUTI))
+ {
+ outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ hcryp->pCrypOutBuffPtr += 16;
+ hcryp->CrypOutCount -= 16;
+ if(hcryp->CrypOutCount == 0)
+ {
+ __HAL_CRYP_DISABLE_IT(CRYP_IT_OUTI);
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+ /* Call Input transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+ }
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES GCM encryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pPlainData;
+ outputaddr = (uint32_t)pCypherData;
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES GCM mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_GCM_ENCRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Enable CRYP to start the init phase */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the header phase */
+ if(CRYPEx_GCMCCM_SetHeaderPhase(hcryp, hcryp->Init.Header, hcryp->Init.HeaderSize, 1) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ /* Disable the CRYP peripheral */
+ __HAL_CRYP_DISABLE();
+
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYPEx_GCMCCM_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Unlock process */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CCM encryption mode using interrupt.
+ * @param hcryp: CRYP handle
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData)
+{
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+ uint32_t headersize;
+ uint32_t headeraddr;
+ uint32_t loopcounter = 0;
+ uint32_t bufferidx = 0;
+ uint8_t blockb0[16] = {0};/* Block B0 */
+ uint8_t ctr[16] = {0}; /* Counter */
+ uint32_t b0addr = (uint32_t)blockb0;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pPlainData;
+ outputaddr = (uint32_t)pCypherData;
+
+ headersize = hcryp->Init.HeaderSize;
+ headeraddr = (uint32_t)hcryp->Init.Header;
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pPlainData;
+ hcryp->pCrypOutBuffPtr = pCypherData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /************************ Formatting the header block *******************/
+ if(headersize != 0)
+ {
+ /* Check that the associated data (or header) length is lower than 2^16 - 2^8 = 65536 - 256 = 65280 */
+ if(headersize < 65280)
+ {
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize >> 8) & 0xFF);
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize) & 0xFF);
+ headersize += 2;
+ }
+ else
+ {
+ /* Header is encoded as 0xff || 0xfe || [headersize]32, i.e., six octets */
+ hcryp->Init.pScratch[bufferidx++] = 0xFF;
+ hcryp->Init.pScratch[bufferidx++] = 0xFE;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0xff000000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x00ff0000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x0000ff00;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x000000ff;
+ headersize += 6;
+ }
+ /* Copy the header buffer in internal buffer "hcryp->Init.pScratch" */
+ for(loopcounter = 0; loopcounter < headersize; loopcounter++)
+ {
+ hcryp->Init.pScratch[bufferidx++] = hcryp->Init.Header[loopcounter];
+ }
+ /* Check if the header size is modulo 16 */
+ if ((headersize % 16) != 0)
+ {
+ /* Padd the header buffer with 0s till the hcryp->Init.pScratch length is modulo 16 */
+ for(loopcounter = headersize; loopcounter <= ((headersize/16) + 1) * 16; loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = 0;
+ }
+ /* Set the header size to modulo 16 */
+ headersize = ((headersize/16) + 1) * 16;
+ }
+ /* Set the pointer headeraddr to hcryp->Init.pScratch */
+ headeraddr = (uint32_t)hcryp->Init.pScratch;
+ }
+ /*********************** Formatting the block B0 ************************/
+ if(headersize != 0)
+ {
+ blockb0[0] = 0x40;
+ }
+ /* Flags byte */
+ /* blockb0[0] |= 0u | (((( (uint8_t) hcryp->Init.TagSize - 2) / 2) & 0x07 ) << 3 ) | ( ( (uint8_t) (15 - hcryp->Init.IVSize) - 1) & 0x07) */
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)(((uint8_t)(hcryp->Init.TagSize - (uint8_t)(2))) >> 1) & (uint8_t)0x07 ) << 3);
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)((uint8_t)(15) - hcryp->Init.IVSize) - (uint8_t)1) & (uint8_t)0x07);
+
+ for (loopcounter = 0; loopcounter < hcryp->Init.IVSize; loopcounter++)
+ {
+ blockb0[loopcounter+1] = hcryp->Init.pInitVect[loopcounter];
+ }
+ for ( ; loopcounter < 13; loopcounter++)
+ {
+ blockb0[loopcounter+1] = 0;
+ }
+
+ blockb0[14] = (Size >> 8);
+ blockb0[15] = (Size & 0xFF);
+
+ /************************* Formatting the initial counter ***************/
+ /* Byte 0:
+ Bits 7 and 6 are reserved and shall be set to 0
+ Bits 3, 4, and 5 shall also be set to 0, to ensure that all the counter
+ blocks are distinct from B0
+ Bits 0, 1, and 2 contain the same encoding of q as in B0
+ */
+ ctr[0] = blockb0[0] & 0x07;
+ /* byte 1 to NonceSize is the IV (Nonce) */
+ for(loopcounter = 1; loopcounter < hcryp->Init.IVSize + 1; loopcounter++)
+ {
+ ctr[loopcounter] = blockb0[loopcounter];
+ }
+ /* Set the LSB to 1 */
+ ctr[15] |= 0x01;
+
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CCM mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CCM_ENCRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, ctr, CRYP_KEYSIZE_128B);
+
+ /* Select init phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_INIT);
+
+ b0addr = (uint32_t)blockb0;
+ /* Write the blockb0 block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /***************************** Header phase *****************************/
+ if(headersize != 0)
+ {
+ /* Select header phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_HEADER);
+
+ /* Enable Crypto processor */
+ __HAL_CRYP_ENABLE();
+
+ for(loopcounter = 0; (loopcounter < headersize); loopcounter+=16)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_IFEM))
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Write the header block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ }
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->SR & CRYP_FLAG_BUSY) == CRYP_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Save formatted counter into the scratch buffer pScratch */
+ for(loopcounter = 0; (loopcounter < 16); loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = ctr[loopcounter];
+ }
+ /* Reset bit 0 */
+ hcryp->Init.pScratch[15] &= 0xfe;
+
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYPEx_GCMCCM_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Unlock process */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES GCM decryption mode using DMA.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer.
+ * @param Size: Length of the cyphertext buffer, must be a multiple of 16
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pCypherData;
+ outputaddr = (uint32_t)pPlainData;
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES GCM decryption mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_GCM_DECRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, hcryp->Init.pInitVect, CRYP_KEYSIZE_128B);
+
+ /* Enable CRYP to start the init phase */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Set the header phase */
+ if(CRYPEx_GCMCCM_SetHeaderPhase(hcryp, hcryp->Init.Header, hcryp->Init.HeaderSize, 1) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ /* Disable the CRYP peripheral */
+ __HAL_CRYP_DISABLE();
+
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+
+ /* Set the input and output addresses and start DMA transfer */
+ CRYPEx_GCMCCM_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Unlock process */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Initializes the CRYP peripheral in AES CCM decryption mode using DMA
+ * then decrypted pCypherData. The cypher data are available in pPlainData.
+ * @param hcryp: CRYP handle
+ * @param pCypherData: Pointer to the cyphertext buffer
+ * @param Size: Length of the plaintext buffer, must be a multiple of 16
+ * @param pPlainData: Pointer to the plaintext buffer
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData)
+{
+ uint32_t timeout = 0;
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+ uint32_t headersize;
+ uint32_t headeraddr;
+ uint32_t loopcounter = 0;
+ uint32_t bufferidx = 0;
+ uint8_t blockb0[16] = {0};/* Block B0 */
+ uint8_t ctr[16] = {0}; /* Counter */
+ uint32_t b0addr = (uint32_t)blockb0;
+
+ if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hcryp);
+
+ inputaddr = (uint32_t)pCypherData;
+ outputaddr = (uint32_t)pPlainData;
+
+ headersize = hcryp->Init.HeaderSize;
+ headeraddr = (uint32_t)hcryp->Init.Header;
+
+ hcryp->CrypInCount = Size;
+ hcryp->pCrypInBuffPtr = pCypherData;
+ hcryp->pCrypOutBuffPtr = pPlainData;
+ hcryp->CrypOutCount = Size;
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hcryp->Phase == HAL_CRYP_PHASE_READY)
+ {
+ /************************ Formatting the header block *******************/
+ if(headersize != 0)
+ {
+ /* Check that the associated data (or header) length is lower than 2^16 - 2^8 = 65536 - 256 = 65280 */
+ if(headersize < 65280)
+ {
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize >> 8) & 0xFF);
+ hcryp->Init.pScratch[bufferidx++] = (uint8_t) ((headersize) & 0xFF);
+ headersize += 2;
+ }
+ else
+ {
+ /* Header is encoded as 0xff || 0xfe || [headersize]32, i.e., six octets */
+ hcryp->Init.pScratch[bufferidx++] = 0xFF;
+ hcryp->Init.pScratch[bufferidx++] = 0xFE;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0xff000000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x00ff0000;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x0000ff00;
+ hcryp->Init.pScratch[bufferidx++] = headersize & 0x000000ff;
+ headersize += 6;
+ }
+ /* Copy the header buffer in internal buffer "hcryp->Init.pScratch" */
+ for(loopcounter = 0; loopcounter < headersize; loopcounter++)
+ {
+ hcryp->Init.pScratch[bufferidx++] = hcryp->Init.Header[loopcounter];
+ }
+ /* Check if the header size is modulo 16 */
+ if ((headersize % 16) != 0)
+ {
+ /* Padd the header buffer with 0s till the hcryp->Init.pScratch length is modulo 16 */
+ for(loopcounter = headersize; loopcounter <= ((headersize/16) + 1) * 16; loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = 0;
+ }
+ /* Set the header size to modulo 16 */
+ headersize = ((headersize/16) + 1) * 16;
+ }
+ /* Set the pointer headeraddr to hcryp->Init.pScratch */
+ headeraddr = (uint32_t)hcryp->Init.pScratch;
+ }
+ /*********************** Formatting the block B0 ************************/
+ if(headersize != 0)
+ {
+ blockb0[0] = 0x40;
+ }
+ /* Flags byte */
+ /* blockb0[0] |= 0u | (((( (uint8_t) hcryp->Init.TagSize - 2) / 2) & 0x07 ) << 3 ) | ( ( (uint8_t) (15 - hcryp->Init.IVSize) - 1) & 0x07) */
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)(((uint8_t)(hcryp->Init.TagSize - (uint8_t)(2))) >> 1) & (uint8_t)0x07 ) << 3);
+ blockb0[0] |= (uint8_t)((uint8_t)((uint8_t)((uint8_t)(15) - hcryp->Init.IVSize) - (uint8_t)1) & (uint8_t)0x07);
+
+ for (loopcounter = 0; loopcounter < hcryp->Init.IVSize; loopcounter++)
+ {
+ blockb0[loopcounter+1] = hcryp->Init.pInitVect[loopcounter];
+ }
+ for ( ; loopcounter < 13; loopcounter++)
+ {
+ blockb0[loopcounter+1] = 0;
+ }
+
+ blockb0[14] = (Size >> 8);
+ blockb0[15] = (Size & 0xFF);
+
+ /************************* Formatting the initial counter ***************/
+ /* Byte 0:
+ Bits 7 and 6 are reserved and shall be set to 0
+ Bits 3, 4, and 5 shall also be set to 0, to ensure that all the counter
+ blocks are distinct from B0
+ Bits 0, 1, and 2 contain the same encoding of q as in B0
+ */
+ ctr[0] = blockb0[0] & 0x07;
+ /* byte 1 to NonceSize is the IV (Nonce) */
+ for(loopcounter = 1; loopcounter < hcryp->Init.IVSize + 1; loopcounter++)
+ {
+ ctr[loopcounter] = blockb0[loopcounter];
+ }
+ /* Set the LSB to 1 */
+ ctr[15] |= 0x01;
+
+ /* Set the key */
+ CRYPEx_GCMCCM_SetKey(hcryp, hcryp->Init.pKey, hcryp->Init.KeySize);
+
+ /* Set the CRYP peripheral in AES CCM mode */
+ __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CCM_DECRYPT);
+
+ /* Set the Initialization Vector */
+ CRYPEx_GCMCCM_SetInitVector(hcryp, ctr, CRYP_KEYSIZE_128B);
+
+ /* Select init phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_INIT);
+
+ b0addr = (uint32_t)blockb0;
+ /* Write the blockb0 block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+ b0addr+=4;
+ CRYP->DR = *(uint32_t*)(b0addr);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->CR & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN)
+ {
+ /* Check for the Timeout */
+
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+
+ }
+ }
+ /***************************** Header phase *****************************/
+ if(headersize != 0)
+ {
+ /* Select header phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_HEADER);
+
+ /* Enable Crypto processor */
+ __HAL_CRYP_ENABLE();
+
+ for(loopcounter = 0; (loopcounter < headersize); loopcounter+=16)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_IFEM))
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Write the header block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ }
+
+/* Get timeout */
+ timeout = HAL_GetTick() + 1;
+
+ while((CRYP->SR & CRYP_FLAG_BUSY) == CRYP_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Save formatted counter into the scratch buffer pScratch */
+ for(loopcounter = 0; (loopcounter < 16); loopcounter++)
+ {
+ hcryp->Init.pScratch[loopcounter] = ctr[loopcounter];
+ }
+ /* Reset bit 0 */
+ hcryp->Init.pScratch[15] &= 0xfe;
+ /* Select payload phase once the header phase is performed */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_PAYLOAD);
+
+ /* Flush FIFO */
+ __HAL_CRYP_FIFO_FLUSH();
+
+ /* Set the phase */
+ hcryp->Phase = HAL_CRYP_PHASE_PROCESS;
+ }
+ /* Set the input and output addresses and start DMA transfer */
+ CRYPEx_GCMCCM_SetDMAConfig(hcryp, inputaddr, Size, outputaddr);
+
+ /* Unlock process */
+ __HAL_UNLOCK(hcryp);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief This function handles CRYP interrupt request.
+ * @param hcryp: CRYP handle
+ * @retval None
+ */
+void HAL_CRYPEx_GCMCCM_IRQHandler(CRYP_HandleTypeDef *hcryp)
+{
+ switch(CRYP->CR & CRYP_CR_ALGOMODE_DIRECTION)
+ {
+ case CRYP_CR_ALGOMODE_AES_GCM_ENCRYPT:
+ HAL_CRYPEx_AESGCM_Encrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_AES_GCM_DECRYPT:
+ HAL_CRYPEx_AESGCM_Decrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_AES_CCM_ENCRYPT:
+ HAL_CRYPEx_AESCCM_Encrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ case CRYP_CR_ALGOMODE_AES_CCM_DECRYPT:
+ HAL_CRYPEx_AESCCM_Decrypt_IT(hcryp, NULL, 0, NULL);
+ break;
+
+ default:
+ break;
+ }
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief DMA CRYP Input Data process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void CRYPEx_GCMCCM_DMAInCplt(DMA_HandleTypeDef *hdma)
+{
+ CRYP_HandleTypeDef* hcryp = ( CRYP_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ /* Disable the DMA transfer for input Fifo request by resetting the DIEN bit
+ in the DMACR register */
+ CRYP->DMACR &= (uint32_t)(~CRYP_DMACR_DIEN);
+
+ /* Call input data transfer complete callback */
+ HAL_CRYP_InCpltCallback(hcryp);
+}
+
+/**
+ * @brief DMA CRYP Output Data process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void CRYPEx_GCMCCM_DMAOutCplt(DMA_HandleTypeDef *hdma)
+{
+ CRYP_HandleTypeDef* hcryp = ( CRYP_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ /* Disable the DMA transfer for output Fifo request by resetting the DOEN bit
+ in the DMACR register */
+ CRYP->DMACR &= (uint32_t)(~CRYP_DMACR_DOEN);
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_DISABLE();
+
+ /* Change the CRYP peripheral state */
+ hcryp->State = HAL_CRYP_STATE_READY;
+
+ /* Call output data transfer complete callback */
+ HAL_CRYP_OutCpltCallback(hcryp);
+}
+
+/**
+ * @brief DMA CRYP communication error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void CRYPEx_GCMCCM_DMAError(DMA_HandleTypeDef *hdma)
+{
+ CRYP_HandleTypeDef* hcryp = ( CRYP_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ hcryp->State= HAL_CRYP_STATE_READY;
+ HAL_CRYP_ErrorCallback(hcryp);
+}
+
+/**
+ * @brief Writes the Key in Key registers.
+ * @param hcryp: CRYP handle
+ * @param Key: Pointer to Key buffer
+ * @param KeySize: Size of Key
+ * @retval None
+ */
+static void CRYPEx_GCMCCM_SetKey(CRYP_HandleTypeDef *hcryp, uint8_t *Key, uint32_t KeySize)
+{
+ uint32_t keyaddr = (uint32_t)Key;
+
+ switch(KeySize)
+ {
+ case CRYP_KEYSIZE_256B:
+ /* Key Initialisation */
+ CRYP->K0LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K0RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K1LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K1RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3RR = __REV(*(uint32_t*)(keyaddr));
+ break;
+ case CRYP_KEYSIZE_192B:
+ CRYP->K1LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K1RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3RR = __REV(*(uint32_t*)(keyaddr));
+ break;
+ case CRYP_KEYSIZE_128B:
+ CRYP->K2LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K2RR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3LR = __REV(*(uint32_t*)(keyaddr));
+ keyaddr+=4;
+ CRYP->K3RR = __REV(*(uint32_t*)(keyaddr));
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * @brief Writes the InitVector/InitCounter in IV registers.
+ * @param hcryp: CRYP handle
+ * @param InitVector: Pointer to InitVector/InitCounter buffer
+ * @param IVSize: Size of the InitVector/InitCounter
+ * @retval None
+ */
+static void CRYPEx_GCMCCM_SetInitVector(CRYP_HandleTypeDef *hcryp, uint8_t *InitVector, uint32_t IVSize)
+{
+ uint32_t ivaddr = (uint32_t)InitVector;
+
+ switch(IVSize)
+ {
+ case CRYP_KEYSIZE_128B:
+ CRYP->IV0LR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV0RR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV1LR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV1RR = __REV(*(uint32_t*)(ivaddr));
+ break;
+ /* Whatever key size 192 or 256, Init vector is written in IV0LR and IV0RR */
+ case CRYP_KEYSIZE_192B:
+ CRYP->IV0LR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV0RR = __REV(*(uint32_t*)(ivaddr));
+ break;
+ case CRYP_KEYSIZE_256B:
+ CRYP->IV0LR = __REV(*(uint32_t*)(ivaddr));
+ ivaddr+=4;
+ CRYP->IV0RR = __REV(*(uint32_t*)(ivaddr));
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * @brief Process Data: Writes Input data in polling mode and read the Output data.
+ * @param hcryp: CRYP handle
+ * @param Input: Pointer to the Input buffer.
+ * @param Ilength: Length of the Input buffer, must be a multiple of 16
+ * @param Output: Pointer to the returned buffer
+ * @param Timeout: Timeout value
+ * @retval None
+ */
+static HAL_StatusTypeDef CRYPEx_GCMCCM_ProcessData(CRYP_HandleTypeDef *hcryp, uint8_t *Input, uint16_t Ilength, uint8_t *Output, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+ uint32_t i = 0;
+ uint32_t inputaddr = (uint32_t)Input;
+ uint32_t outputaddr = (uint32_t)Output;
+
+ for(i=0; (i < Ilength); i+=16)
+ {
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+ CRYP->DR = *(uint32_t*)(inputaddr);
+ inputaddr+=4;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_OFNE))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Read the Output block from the OUT FIFO */
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = CRYP->DOUT;
+ outputaddr+=4;
+ }
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets the header phase
+ * @param hcryp: CRYP handle
+ * @param Input: Pointer to the Input buffer.
+ * @param Ilength: Length of the Input buffer, must be a multiple of 16
+ * @param Timeout: Timeout value
+ * @retval None
+ */
+static HAL_StatusTypeDef CRYPEx_GCMCCM_SetHeaderPhase(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+ uint32_t loopcounter = 0;
+ uint32_t headeraddr = (uint32_t)Input;
+
+ /***************************** Header phase *********************************/
+ if(hcryp->Init.HeaderSize != 0)
+ {
+ /* Select header phase */
+ __HAL_CRYP_SET_PHASE(CRYP_PHASE_HEADER);
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ for(loopcounter = 0; (loopcounter < hcryp->Init.HeaderSize); loopcounter+=16)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(CRYP->SR, CRYP_FLAG_IFEM))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Write the Input block in the IN FIFO */
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ CRYP->DR = *(uint32_t*)(headeraddr);
+ headeraddr+=4;
+ }
+
+ /* Wait until the complete message has been processed */
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((CRYP->SR & CRYP_FLAG_BUSY) == CRYP_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hcryp->State = HAL_CRYP_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hcryp);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets the DMA configuration and start the DMA transfert.
+ * @param hcryp: CRYP handle
+ * @param inputaddr: Address of the Input buffer
+ * @param Size: Size of the Input buffer, must be a multiple of 16
+ * @param outputaddr: Address of the Output buffer
+ * @retval None
+ */
+static void CRYPEx_GCMCCM_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr)
+{
+ /* Set the CRYP DMA transfer complete callback */
+ hcryp->hdmain->XferCpltCallback = CRYPEx_GCMCCM_DMAInCplt;
+ /* Set the DMA error callback */
+ hcryp->hdmain->XferErrorCallback = CRYPEx_GCMCCM_DMAError;
+
+ /* Set the CRYP DMA transfer complete callback */
+ hcryp->hdmaout->XferCpltCallback = CRYPEx_GCMCCM_DMAOutCplt;
+ /* Set the DMA error callback */
+ hcryp->hdmaout->XferErrorCallback = CRYPEx_GCMCCM_DMAError;
+
+ /* Enable the CRYP peripheral */
+ __HAL_CRYP_ENABLE();
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hcryp->hdmain, inputaddr, (uint32_t)&CRYP->DR, Size/4);
+
+ /* Enable In DMA request */
+ CRYP->DMACR = CRYP_DMACR_DIEN;
+
+ /* Enable the DMA Out DMA Stream */
+ HAL_DMA_Start_IT(hcryp->hdmaout, (uint32_t)&CRYP->DOUT, outputaddr, Size/4);
+
+ /* Enable Out DMA request */
+ CRYP->DMACR |= CRYP_DMACR_DOEN;
+}
+
+/**
+ * @}
+ */
+#endif /* STM32F437xx || STM32F439xx */
+
+#endif /* HAL_CRYP_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac.c
new file mode 100644
index 0000000..598e1e0
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac.c
@@ -0,0 +1,916 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_dac.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief DAC HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Digital to Analog Converter (DAC) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State and Errors functions
+ *
+ *
+ @verbatim
+ ==============================================================================
+ ##### DAC Peripheral features #####
+ ==============================================================================
+ [..]
+ *** DAC Channels ***
+ ====================
+ [..]
+ The device integrates two 12-bit Digital Analog Converters that can
+ be used independently or simultaneously (dual mode):
+ (#) DAC channel1 with DAC_OUT1 (PA4) as output
+ (#) DAC channel2 with DAC_OUT2 (PA5) as output
+
+ *** DAC Triggers ***
+ ====================
+ [..]
+ Digital to Analog conversion can be non-triggered using DAC_Trigger_None
+ and DAC_OUT1/DAC_OUT2 is available once writing to DHRx register.
+ [..]
+ Digital to Analog conversion can be triggered by:
+ (#) External event: EXTI Line 9 (any GPIOx_Pin9) using DAC_Trigger_Ext_IT9.
+ The used pin (GPIOx_Pin9) must be configured in input mode.
+
+ (#) Timers TRGO: TIM2, TIM4, TIM5, TIM6, TIM7 and TIM8
+ (DAC_Trigger_T2_TRGO, DAC_Trigger_T4_TRGO...)
+
+ (#) Software using DAC_Trigger_Software
+
+ *** DAC Buffer mode feature ***
+ ===============================
+ [..]
+ Each DAC channel integrates an output buffer that can be used to
+ reduce the output impedance, and to drive external loads directly
+ without having to add an external operational amplifier.
+ To enable, the output buffer use
+ sConfig.DAC_OutputBuffer = DAC_OutputBuffer_Enable;
+ [..]
+ (@) Refer to the device datasheet for more details about output
+ impedance value with and without output buffer.
+
+ *** DAC wave generation feature ***
+ ===================================
+ [..]
+ Both DAC channels can be used to generate
+ (#) Noise wave
+ (#) Triangle wave
+
+ *** DAC data format ***
+ =======================
+ [..]
+ The DAC data format can be:
+ (#) 8-bit right alignment using DAC_ALIGN_8B_R
+ (#) 12-bit left alignment using DAC_ALIGN_12B_L
+ (#) 12-bit right alignment using DAC_ALIGN_12B_R
+
+ *** DAC data value to voltage correspondence ***
+ ================================================
+ [..]
+ The analog output voltage on each DAC channel pin is determined
+ by the following equation:
+ DAC_OUTx = VREF+ * DOR / 4095
+ with DOR is the Data Output Register
+ VEF+ is the input voltage reference (refer to the device datasheet)
+ e.g. To set DAC_OUT1 to 0.7V, use
+ Assuming that VREF+ = 3.3V, DAC_OUT1 = (3.3 * 868) / 4095 = 0.7V
+
+ *** DMA requests ***
+ =====================
+ [..]
+ A DMA1 request can be generated when an external trigger (but not
+ a software trigger) occurs if DMA1 requests are enabled using
+ HAL_DAC_Start_DMA()
+ [..]
+ DMA1 requests are mapped as following:
+ (#) DAC channel1 : mapped on DMA1 Stream5 channel7 which must be
+ already configured
+ (#) DAC channel2 : mapped on DMA1 Stream6 channel7 which must be
+ already configured
+
+ -@- For Dual mode and specific signal (Triangle and noise) generation please
+ refer to Extension Features Driver description
+
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (+) DAC APB clock must be enabled to get write access to DAC
+ registers using HAL_DAC_Init()
+ (+) Configure DAC_OUTx (DAC_OUT1: PA4, DAC_OUT2: PA5) in analog mode.
+ (+) Configure the DAC channel using HAL_DAC_ConfigChannel() function.
+ (+) Enable the DAC channel using HAL_DAC_Start() or HAL_DAC_Start_DMA functions
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Start the DAC peripheral using HAL_DAC_Start()
+ (+) To read the DAC last data output value value, use the HAL_DAC_GetValue() function.
+ (+) Stop the DAC peripheral using HAL_DAC_Stop()
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Start the DAC peripheral using HAL_DAC_Start_DMA(), at this stage the user specify the length
+ of data to be transfered at each end of conversion
+ (+) At The end of data transfer HAL_DAC_ConvCpltCallbackCh1()or HAL_DAC_ConvCpltCallbackCh2()
+ function is executed and user can add his own code by customization of function pointer
+ HAL_DAC_ConvCpltCallbackCh1 or HAL_DAC_ConvCpltCallbackCh2
+ (+) In case of transfer Error, HAL_DAC_ErrorCallbackCh1() function is executed and user can
+ add his own code by customization of function pointer HAL_DAC_ErrorCallbackCh1
+ (+) Stop the DAC peripheral using HAL_DAC_Stop_DMA()
+
+ *** DAC HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in DAC HAL driver.
+
+ (+) __HAL_DAC_ENABLE : Enable the DAC peripheral
+ (+) __HAL_DAC_DISABLE : Disable the DAC peripheral
+ (+) __HAL_DAC_CLEAR_FLAG: Clear the DAC's pending flags
+ (+) __HAL_DAC_GET_FLAG: Get the selected DAC's flag status
+
+ [..]
+ (@) You can refer to the DAC HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup DAC
+ * @brief DAC driver modules
+ * @{
+ */
+
+#ifdef HAL_DAC_MODULE_ENABLED
+
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void DAC_DMAConvCpltCh1(DMA_HandleTypeDef *hdma);
+static void DAC_DMAErrorCh1(DMA_HandleTypeDef *hdma);
+static void DAC_DMAHalfConvCpltCh1(DMA_HandleTypeDef *hdma);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup DAC_Private_Functions
+ * @{
+ */
+
+/** @defgroup DAC_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de-initialization functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize and configure the DAC.
+ (+) De-initialize the DAC.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the DAC peripheral according to the specified parameters
+ * in the DAC_InitStruct.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac)
+{
+ /* Check DAC handle */
+ if(hdac == NULL)
+ {
+ return HAL_ERROR;
+ }
+ /* Check the parameters */
+ assert_param(IS_DAC_ALL_INSTANCE(hdac->Instance));
+
+ if(hdac->State == HAL_DAC_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_DAC_MspInit(hdac);
+ }
+
+ /* Initialize the DAC state*/
+ hdac->State = HAL_DAC_STATE_BUSY;
+
+ /* Set DAC error code to none */
+ hdac->ErrorCode = HAL_DAC_ERROR_NONE;
+
+ /* Initialize the DAC state*/
+ hdac->State = HAL_DAC_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Deinitializes the DAC peripheral registers to their default reset values.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef* hdac)
+{
+ /* Check DAC handle */
+ if(hdac == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_DAC_ALL_INSTANCE(hdac->Instance));
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_DAC_MspDeInit(hdac);
+
+ /* Set DAC error code to none */
+ hdac->ErrorCode = HAL_DAC_ERROR_NONE;
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hdac);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the DAC MSP.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the DAC MSP.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DAC_Group2 IO operation functions
+ * @brief IO operation functions
+ *
+@verbatim
+ ==============================================================================
+ ##### IO operation functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Start conversion.
+ (+) Stop conversion.
+ (+) Start conversion and enable DMA transfer.
+ (+) Stop conversion and disable DMA transfer.
+ (+) Get result of conversion.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables DAC and starts conversion of channel.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param Channel: The selected DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_CHANNEL_1: DAC Channel1 selected
+ * @arg DAC_CHANNEL_2: DAC Channel2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ /* Check the parameters */
+ assert_param(IS_DAC_CHANNEL(Channel));
+
+ /* Process locked */
+ __HAL_LOCK(hdac);
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_BUSY;
+
+ /* Enable the Peripharal */
+ __HAL_DAC_ENABLE(hdac, Channel);
+
+ if(Channel == DAC_CHANNEL_1)
+ {
+ tmp1 = hdac->Instance->CR & DAC_CR_TEN1;
+ tmp2 = hdac->Instance->CR & DAC_CR_TSEL1;
+ /* Check if software trigger enabled */
+ if((tmp1 == DAC_CR_TEN1) && (tmp2 == DAC_CR_TSEL1))
+ {
+ /* Enable the selected DAC software conversion */
+ hdac->Instance->SWTRIGR |= (uint32_t)DAC_SWTRIGR_SWTRIG1;
+ }
+ }
+ else
+ {
+ tmp1 = hdac->Instance->CR & DAC_CR_TEN2;
+ tmp2 = hdac->Instance->CR & DAC_CR_TSEL2;
+ /* Check if software trigger enabled */
+ if((tmp1 == DAC_CR_TEN2) && (tmp2 == DAC_CR_TSEL2))
+ {
+ /* Enable the selected DAC software conversion*/
+ hdac->Instance->SWTRIGR |= (uint32_t)DAC_SWTRIGR_SWTRIG2;
+ }
+ }
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hdac);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables DAC and stop conversion of channel.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param Channel: The selected DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_CHANNEL_1: DAC Channel1 selected
+ * @arg DAC_CHANNEL_2: DAC Channel2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_DAC_CHANNEL(Channel));
+
+ /* Disable the Peripheral */
+ __HAL_DAC_DISABLE(hdac, Channel);
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Enables DAC and starts conversion of channel.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param Channel: The selected DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_CHANNEL_1: DAC Channel1 selected
+ * @arg DAC_CHANNEL_2: DAC Channel2 selected
+ * @param pData: The destination peripheral Buffer address.
+ * @param Length: The length of data to be transferred from memory to DAC peripheral
+ * @param Alignment: Specifies the data alignment for DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_Align_8b_R: 8bit right data alignment selected
+ * @arg DAC_Align_12b_L: 12bit left data alignment selected
+ * @arg DAC_Align_12b_R: 12bit right data alignment selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_DAC_CHANNEL(Channel));
+ assert_param(IS_DAC_ALIGN(Alignment));
+
+ /* Process locked */
+ __HAL_LOCK(hdac);
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_BUSY;
+
+ /* Set the DMA transfer complete callback for channel1 */
+ hdac->DMA_Handle1->XferCpltCallback = DAC_DMAConvCpltCh1;
+
+ /* Set the DMA half transfer complete callback for channel1 */
+ hdac->DMA_Handle1->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh1;
+
+ /* Set the DMA error callback for channel1 */
+ hdac->DMA_Handle1->XferErrorCallback = DAC_DMAErrorCh1;
+
+ /* Set the DMA transfer complete callback for channel2 */
+ hdac->DMA_Handle2->XferCpltCallback = DAC_DMAConvCpltCh2;
+
+ /* Set the DMA half transfer complete callback for channel2 */
+ hdac->DMA_Handle2->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh2;
+
+ /* Set the DMA error callback for channel2 */
+ hdac->DMA_Handle2->XferErrorCallback = DAC_DMAErrorCh2;
+
+ if(Channel == DAC_CHANNEL_1)
+ {
+ /* Enable the selected DAC channel1 DMA request */
+ hdac->Instance->CR |= DAC_CR_DMAEN1;
+
+ /* Case of use of channel 1 */
+ switch(Alignment)
+ {
+ case DAC_ALIGN_12B_R:
+ /* Get DHR12R1 address */
+ tmpreg = (uint32_t)&hdac->Instance->DHR12R1;
+ break;
+ case DAC_ALIGN_12B_L:
+ /* Get DHR12L1 address */
+ tmpreg = (uint32_t)&hdac->Instance->DHR12L1;
+ break;
+ case DAC_ALIGN_8B_R:
+ /* Get DHR8R1 address */
+ tmpreg = (uint32_t)&hdac->Instance->DHR8R1;
+ break;
+ default:
+ break;
+ }
+ }
+ else
+ {
+ /* Enable the selected DAC channel2 DMA request */
+ hdac->Instance->CR |= DAC_CR_DMAEN2;
+
+ /* Case of use of channel 2 */
+ switch(Alignment)
+ {
+ case DAC_ALIGN_12B_R:
+ /* Get DHR12R2 address */
+ tmpreg = (uint32_t)&hdac->Instance->DHR12R2;
+ break;
+ case DAC_ALIGN_12B_L:
+ /* Get DHR12L2 address */
+ tmpreg = (uint32_t)&hdac->Instance->DHR12L2;
+ break;
+ case DAC_ALIGN_8B_R:
+ /* Get DHR8R2 address */
+ tmpreg = (uint32_t)&hdac->Instance->DHR8R2;
+ break;
+ default:
+ break;
+ }
+ }
+
+ /* Enable the DMA Stream */
+ if(Channel == DAC_CHANNEL_1)
+ {
+ /* Enable the DAC DMA underrun interrupt */
+ __HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR1);
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hdac->DMA_Handle1, (uint32_t)pData, tmpreg, Length);
+ }
+ else
+ {
+ /* Enable the DAC DMA underrun interrupt */
+ __HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR2);
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hdac->DMA_Handle2, (uint32_t)pData, tmpreg, Length);
+ }
+
+ /* Enable the Peripharal */
+ __HAL_DAC_ENABLE(hdac, Channel);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdac);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables DAC and stop conversion of channel.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param Channel: The selected DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_CHANNEL_1: DAC Channel1 selected
+ * @arg DAC_CHANNEL_2: DAC Channel2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_DAC_CHANNEL(Channel));
+
+ /* Disable the selected DAC channel DMA request */
+ hdac->Instance->CR &= ~(DAC_CR_DMAEN1 << Channel);
+
+ /* Disable the Peripharal */
+ __HAL_DAC_DISABLE(hdac, Channel);
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Returns the last data output value of the selected DAC channel.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param Channel: The selected DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_CHANNEL_1: DAC Channel1 selected
+ * @arg DAC_CHANNEL_2: DAC Channel2 selected
+ * @retval The selected DAC channel data output value.
+ */
+uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_DAC_CHANNEL(Channel));
+
+ /* Returns the DAC channel data output register value */
+ if(Channel == DAC_CHANNEL_1)
+ {
+ return hdac->Instance->DOR1;
+ }
+ else
+ {
+ return hdac->Instance->DOR2;
+ }
+}
+
+/**
+ * @brief Handles DAC interrupt request
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac)
+{
+ /* Check Overrun flag */
+ if(__HAL_DAC_GET_FLAG(hdac, DAC_FLAG_DMAUDR1))
+ {
+ /* Change DAC state to error state */
+ hdac->State = HAL_DAC_STATE_ERROR;
+
+ /* Set DAC error code to chanel1 DMA underrun error */
+ hdac->ErrorCode |= HAL_DAC_ERROR_DMAUNDERRUNCH1;
+
+ /* Clear the underrun flag */
+ __HAL_DAC_CLEAR_FLAG(hdac,DAC_FLAG_DMAUDR1);
+
+ /* Disable the selected DAC channel1 DMA request */
+ hdac->Instance->CR &= ~DAC_CR_DMAEN1;
+
+ /* Error callback */
+ HAL_DAC_DMAUnderrunCallbackCh1(hdac);
+ }
+ else
+ {
+ /* Change DAC state to error state */
+ hdac->State = HAL_DAC_STATE_ERROR;
+
+ /* Set DAC error code to channel2 DMA underrun error */
+ hdac->ErrorCode |= HAL_DAC_ERROR_DMAUNDERRUNCH2;
+
+ /* Clear the underrun flag */
+ __HAL_DAC_CLEAR_FLAG(hdac,DAC_FLAG_DMAUDR2);
+
+ /* Disable the selected DAC channel1 DMA request */
+ hdac->Instance->CR &= ~DAC_CR_DMAEN2;
+
+ /* Error callback */
+ HAL_DACEx_DMAUnderrunCallbackCh2(hdac);
+ }
+}
+
+/**
+ * @brief Conversion complete callback in non blocking mode for Channel1
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_ConvCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Conversion half DMA transfer callback in non blocking mode for Channel1
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_ConvHalfCpltCallbackCh1 could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Error DAC callback for Channel1.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DMA underrun DAC callback for channel1.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_DMAUnderrunCallbackCh1 could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DAC_Group3 Peripheral Control functions
+ * @brief Peripheral Control functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral Control functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Configure channels.
+ (+) Set the specified data holding register value for DAC channel.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Configures the selected DAC channel.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param sConfig: DAC configuration structure.
+ * @param Channel: The selected DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_CHANNEL_1: DAC Channel1 selected
+ * @arg DAC_CHANNEL_2: DAC Channel2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel)
+{
+ uint32_t tmpreg1 = 0, tmpreg2 = 0;
+
+ /* Check the DAC parameters */
+ assert_param(IS_DAC_TRIGGER(sConfig->DAC_Trigger));
+ assert_param(IS_DAC_OUTPUT_BUFFER_STATE(sConfig->DAC_OutputBuffer));
+ assert_param(IS_DAC_TRIGGER(sConfig->DAC_Trigger));
+ assert_param(IS_DAC_CHANNEL(Channel));
+
+ /* Process locked */
+ __HAL_LOCK(hdac);
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_BUSY;
+
+ /* Get the DAC CR value */
+ tmpreg1 = DAC->CR;
+ /* Clear BOFFx, TENx, TSELx, WAVEx and MAMPx bits */
+ tmpreg1 &= ~(((uint32_t)(DAC_CR_MAMP1 | DAC_CR_WAVE1 | DAC_CR_TSEL1 | DAC_CR_TEN1 | DAC_CR_BOFF1)) << Channel);
+ /* Configure for the selected DAC channel: buffer output, trigger */
+ /* Set TSELx and TENx bits according to DAC_Trigger value */
+ /* Set BOFFx bit according to DAC_OutputBuffer value */
+ tmpreg2 = (sConfig->DAC_Trigger | sConfig->DAC_OutputBuffer);
+ /* Calculate CR register value depending on DAC_Channel */
+ tmpreg1 |= tmpreg2 << Channel;
+ /* Write to DAC CR */
+ DAC->CR = tmpreg1;
+ /* Disable wave generation */
+ DAC->CR &= ~(DAC_CR_WAVE1 << Channel);
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hdac);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Set the specified data holding register value for DAC channel.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param Channel: The selected DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_CHANNEL_1: DAC Channel1 selected
+ * @arg DAC_CHANNEL_2: DAC Channel2 selected
+ * @param Alignment: Specifies the data alignment.
+ * This parameter can be one of the following values:
+ * @arg DAC_Align_8b_R: 8bit right data alignment selected
+ * @arg DAC_Align_12b_L: 12bit left data alignment selected
+ * @arg DAC_Align_12b_R: 12bit right data alignment selected
+ * @param Data: Data to be loaded in the selected data holding register.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data)
+{
+ __IO uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_DAC_CHANNEL(Channel));
+ assert_param(IS_DAC_ALIGN(Alignment));
+ assert_param(IS_DAC_DATA(Data));
+
+ tmp = (uint32_t)hdac->Instance;
+ if(Channel == DAC_CHANNEL_1)
+ {
+ tmp += __HAL_DHR12R1_ALIGNEMENT(Alignment);
+ }
+ else
+ {
+ tmp += __HAL_DHR12R2_ALIGNEMENT(Alignment);
+ }
+
+ /* Set the DAC channel1 selected data holding register */
+ *(__IO uint32_t *) tmp = Data;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DAC_Group4 Peripheral State and Errors functions
+ * @brief Peripheral State and Errors functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State and Errors functions #####
+ ==============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Check the DAC state.
+ (+) Check the DAC Errors.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief return the DAC state
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval HAL state
+ */
+HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef* hdac)
+{
+ /* Return DAC state */
+ return hdac->State;
+}
+
+
+/**
+ * @brief Return the DAC error code
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval DAC Error Code
+ */
+uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac)
+{
+ return hdac->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief DMA conversion complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void DAC_DMAConvCpltCh1(DMA_HandleTypeDef *hdma)
+{
+ DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ HAL_DAC_ConvCpltCallbackCh1(hdac);
+
+ hdac->State= HAL_DAC_STATE_READY;
+}
+
+/**
+ * @brief DMA half transfer complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void DAC_DMAHalfConvCpltCh1(DMA_HandleTypeDef *hdma)
+{
+ DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ /* Conversion complete callback */
+ HAL_DAC_ConvHalfCpltCallbackCh1(hdac);
+}
+
+/**
+ * @brief DMA error callback
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void DAC_DMAErrorCh1(DMA_HandleTypeDef *hdma)
+{
+ DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ /* Set DAC error code to DMA error */
+ hdac->ErrorCode |= HAL_DAC_ERROR_DMA;
+
+ HAL_DAC_ErrorCallbackCh1(hdac);
+
+ hdac->State= HAL_DAC_STATE_READY;
+}
+
+/**
+ * @}
+ */
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_DAC_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac_ex.c
new file mode 100644
index 0000000..1ddea46
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac_ex.c
@@ -0,0 +1,377 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_dac_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief DAC HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of DAC extension peripheral:
+ * + Extended features functions
+ *
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (+) When Dual mode is enabled (i.e DAC Channel1 and Channel2 are used simultaneously) :
+ Use HAL_DACEx_DualGetValue() to get digital data to be converted and use
+ HAL_DACEx_DualSetValue() to set digital value to converted simultaneously in Channel 1 and Channel 2.
+ (+) Use HAL_DACEx_TriangleWaveGenerate() to generate Triangle signal.
+ (+) Use HAL_DACEx_NoiseWaveGenerate() to generate Noise signal.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup DACEx
+ * @brief DAC driver modules
+ * @{
+ */
+
+#ifdef HAL_DAC_MODULE_ENABLED
+
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup DACEx_Private_Functions
+ * @{
+ */
+
+/** @defgroup DACEx_Group1 Extended features functions
+ * @brief Extended features functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Extended features functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Start conversion.
+ (+) Stop conversion.
+ (+) Start conversion and enable DMA transfer.
+ (+) Stop conversion and disable DMA transfer.
+ (+) Get result of conversion.
+ (+) Get result of dual mode conversion.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the last data output value of the selected DAC channel.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval The selected DAC channel data output value.
+ */
+uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef* hdac)
+{
+ uint32_t tmp = 0;
+
+ tmp |= hdac->Instance->DOR1;
+
+ tmp |= hdac->Instance->DOR2 << 16;
+
+ /* Returns the DAC channel data output register value */
+ return tmp;
+}
+
+/**
+ * @brief Enables or disables the selected DAC channel wave generation.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param Channel: The selected DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_CHANNEL_1: DAC Channel1 selected
+ * @arg DAC_CHANNEL_2: DAC Channel2 selected
+ * @param Amplitude: Select max triangle amplitude.
+ * This parameter can be one of the following values:
+ * @arg DAC_TRIANGLEAMPLITUDE_1: Select max triangle amplitude of 1
+ * @arg DAC_TRIANGLEAMPLITUDE_3: Select max triangle amplitude of 3
+ * @arg DAC_TRIANGLEAMPLITUDE_7: Select max triangle amplitude of 7
+ * @arg DAC_TRIANGLEAMPLITUDE_15: Select max triangle amplitude of 15
+ * @arg DAC_TRIANGLEAMPLITUDE_31: Select max triangle amplitude of 31
+ * @arg DAC_TRIANGLEAMPLITUDE_63: Select max triangle amplitude of 63
+ * @arg DAC_TRIANGLEAMPLITUDE_127: Select max triangle amplitude of 127
+ * @arg DAC_TRIANGLEAMPLITUDE_255: Select max triangle amplitude of 255
+ * @arg DAC_TRIANGLEAMPLITUDE_511: Select max triangle amplitude of 511
+ * @arg DAC_TRIANGLEAMPLITUDE_1023: Select max triangle amplitude of 1023
+ * @arg DAC_TRIANGLEAMPLITUDE_2047: Select max triangle amplitude of 2047
+ * @arg DAC_TRIANGLEAMPLITUDE_4095: Select max triangle amplitude of 4095
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude)
+{
+ /* Check the parameters */
+ assert_param(IS_DAC_CHANNEL(Channel));
+ assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude));
+
+ /* Process locked */
+ __HAL_LOCK(hdac);
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_BUSY;
+
+ /* Enable the selected wave generation for the selected DAC channel */
+ hdac->Instance->CR |= (DAC_WAVE_TRIANGLE | Amplitude) << Channel;
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hdac);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Enables or disables the selected DAC channel wave generation.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param Channel: The selected DAC channel.
+ * This parameter can be one of the following values:
+ * @arg DAC_CHANNEL_1: DAC Channel1 selected
+ * @arg DAC_CHANNEL_2: DAC Channel2 selected
+ * @param Amplitude: Unmask DAC channel LFSR for noise wave generation.
+ * This parameter can be one of the following values:
+ * @arg DAC_LFSRUNMASK_BIT0: Unmask DAC channel LFSR bit0 for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS1_0: Unmask DAC channel LFSR bit[1:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS2_0: Unmask DAC channel LFSR bit[2:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS3_0: Unmask DAC channel LFSR bit[3:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS4_0: Unmask DAC channel LFSR bit[4:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS5_0: Unmask DAC channel LFSR bit[5:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS6_0: Unmask DAC channel LFSR bit[6:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS7_0: Unmask DAC channel LFSR bit[7:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS8_0: Unmask DAC channel LFSR bit[8:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS9_0: Unmask DAC channel LFSR bit[9:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS10_0: Unmask DAC channel LFSR bit[10:0] for noise wave generation
+ * @arg DAC_LFSRUNMASK_BITS11_0: Unmask DAC channel LFSR bit[11:0] for noise wave generation
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude)
+{
+ /* Check the parameters */
+ assert_param(IS_DAC_CHANNEL(Channel));
+ assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude));
+
+ /* Process locked */
+ __HAL_LOCK(hdac);
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_BUSY;
+
+ /* Enable the selected wave generation for the selected DAC channel */
+ hdac->Instance->CR |= (DAC_WAVE_NOISE | Amplitude) << Channel;
+
+ /* Change DAC state */
+ hdac->State = HAL_DAC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hdac);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Set the specified data holding register value for dual DAC channel.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @param Alignment: Specifies the data alignment for dual channel DAC.
+ * This parameter can be one of the following values:
+ * @arg DAC_Align_8b_R: 8bit right data alignment selected
+ * @arg DAC_Align_12b_L: 12bit left data alignment selected
+ * @arg DAC_Align_12b_R: 12bit right data alignment selected
+ * @param Data1: Data for DAC Channel2 to be loaded in the selected data holding register.
+ * @param Data2: Data for DAC Channel1 to be loaded in the selected data holding register.
+ * @note In dual mode, a unique register access is required to write in both
+ * DAC channels at the same time.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef* hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2)
+{
+ uint32_t data = 0, tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_DAC_ALIGN(Alignment));
+ assert_param(IS_DAC_DATA(Data1));
+ assert_param(IS_DAC_DATA(Data2));
+
+ /* Calculate and set dual DAC data holding register value */
+ if (Alignment == DAC_ALIGN_8B_R)
+ {
+ data = ((uint32_t)Data2 << 8) | Data1;
+ }
+ else
+ {
+ data = ((uint32_t)Data2 << 16) | Data1;
+ }
+
+ tmp = (uint32_t)hdac->Instance;
+ tmp += __HAL_DHR12RD_ALIGNEMENT(Alignment);
+
+ /* Set the dual DAC selected data holding register */
+ *(__IO uint32_t *)tmp = data;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Conversion complete callback in non blocking mode for Channel2
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef* hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_ConvCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Conversion half DMA transfer callback in non blocking mode for Channel2
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef* hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_ConvHalfCpltCallbackCh2 could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Error DAC callback for Channel2.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef *hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DMA underrun DAC callback for channel2.
+ * @param hdac: pointer to a DAC_HandleTypeDef structure that contains
+ * the configuration information for the specified DAC.
+ * @retval None
+ */
+__weak void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef *hdac)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DAC_DMAUnderrunCallbackCh2 could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DMA conversion complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+void DAC_DMAConvCpltCh2(DMA_HandleTypeDef *hdma)
+{
+ DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ HAL_DACEx_ConvCpltCallbackCh2(hdac);
+
+ hdac->State= HAL_DAC_STATE_READY;
+}
+
+/**
+ * @brief DMA half transfer complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+void DAC_DMAHalfConvCpltCh2(DMA_HandleTypeDef *hdma)
+{
+ DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ /* Conversion complete callback */
+ HAL_DACEx_ConvHalfCpltCallbackCh2(hdac);
+}
+
+/**
+ * @brief DMA error callback
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+void DAC_DMAErrorCh2(DMA_HandleTypeDef *hdma)
+{
+ DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ /* Set DAC error code to DMA error */
+ hdac->ErrorCode |= HAL_DAC_ERROR_DMA;
+
+ HAL_DACEx_ErrorCallbackCh2(hdac);
+
+ hdac->State= HAL_DAC_STATE_READY;
+}
+
+/**
+ * @}
+ */
+
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+
+#endif /* HAL_DAC_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dcmi.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dcmi.c
new file mode 100644
index 0000000..f21e7f7
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dcmi.c
@@ -0,0 +1,815 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_dcmi.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief DCMI HAL module driver
+ * This file provides firmware functions to manage the following
+ * functionalities of the Digital Camera Interface (DCMI) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State and Error functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The sequence below describes how to use this driver to capture image
+ from a camera module connected to the DCMI Interface.
+ This sequence does not take into account the configuration of the
+ camera module, which should be made before to configure and enable
+ the DCMI to capture images.
+
+ (#) Program the required configuration through following parameters:
+ horizontal and vertical polarity, pixel clock polarity, Capture Rate,
+ Synchronization Mode, code of the frame delimiter and data width
+ using HAL_DCMI_Init() function.
+
+ (#) Configure the DMA2_Stream1 channel1 to transfer Data from DCMI DR
+ register to the destination memory buffer.
+
+ (#) Program the required configuration through following parameters:
+ DCMI mode, destination memory Buffer address and the data length
+ and enable capture using HAL_DCMI_Start_DMA() function.
+
+ (#) Optionally, configure and Enable the CROP feature to select a rectangular
+ window from the received image using HAL_DCMI_ConfigCrop()
+ and HAL_DCMI_EnableCROP() functions
+
+ (#) The capture can be stopped using the following HAL_DCMI_Stop() function.
+
+ (#) To control DCMI state you can use the following function : HAL_DCMI_GetState()
+
+ *** DCMI HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in DCMI HAL driver.
+
+ (+) __HAL_DCMI_ENABLE: Enable the DCMI peripheral.
+ (+) __HAL_DCMI_DISABLE: Disable the DCMI peripheral.
+ (+) __HAL_DCMI_GET_FLAG: Get the DCMI pending flags.
+ (+) __HAL_DCMI_CLEAR_FLAG: Clear the DCMI pending flags.
+ (+) __HAL_DCMI_ENABLE_IT: Enable the specified DCMI interrupts.
+ (+) __HAL_DCMI_DISABLE_IT: Disable the specified DCMI interrupts.
+ (+) __HAL_DCMI_GET_IT_SOURCE: Check whether the specified DCMI interrupt has occurred or not.
+
+ [..]
+ (@) You can refer to the DCMI HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+/** @defgroup DCMI
+ * @brief DCMI HAL module driver
+ * @{
+ */
+
+#ifdef HAL_DCMI_MODULE_ENABLED
+
+#if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define HAL_TIMEOUT_DCMI_STOP ((uint32_t)1000) /* 1s */
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void DCMI_DMAConvCplt(DMA_HandleTypeDef *hdma);
+static void DCMI_DMAError(DMA_HandleTypeDef *hdma);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup DCMI_Private_Functions
+ * @{
+ */
+
+/** @defgroup DCMI_Group1 Initialization and Configuration functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and Configuration functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize and configure the DCMI
+ (+) De-initialize the DCMI
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the DCMI according to the specified
+ * parameters in the DCMI_InitTypeDef and create the associated handle.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DCMI_Init(DCMI_HandleTypeDef *hdcmi)
+{
+ /* Check the DCMI peripheral state */
+ if(hdcmi == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check function parameters */
+ assert_param(IS_DCMI_ALL_INSTANCE(hdcmi->Instance));
+ assert_param(IS_DCMI_PCKPOLARITY(hdcmi->Init.PCKPolarity));
+ assert_param(IS_DCMI_VSPOLARITY(hdcmi->Init.VSPolarity));
+ assert_param(IS_DCMI_HSPOLARITY(hdcmi->Init.HSPolarity));
+ assert_param(IS_DCMI_SYNCHRO(hdcmi->Init.SynchroMode));
+ assert_param(IS_DCMI_CAPTURE_RATE(hdcmi->Init.CaptureRate));
+ assert_param(IS_DCMI_EXTENDED_DATA(hdcmi->Init.ExtendedDataMode));
+ assert_param(IS_DCMI_MODE_JPEG(hdcmi->Init.JPEGMode));
+
+ if(hdcmi->State == HAL_DCMI_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_DCMI_MspInit(hdcmi);
+ }
+
+ /* Change the DCMI state */
+ hdcmi->State = HAL_DCMI_STATE_BUSY;
+
+ /* Configures the HS, VS, DE and PC polarity */
+ hdcmi->Instance->CR &= ~(DCMI_CR_PCKPOL | DCMI_CR_HSPOL | DCMI_CR_VSPOL | DCMI_CR_EDM_0 |
+ DCMI_CR_EDM_1 | DCMI_CR_FCRC_0 | DCMI_CR_FCRC_1 | DCMI_CR_JPEG |
+ DCMI_CR_ESS);
+ hdcmi->Instance->CR |= (uint32_t)(hdcmi->Init.SynchroMode | hdcmi->Init.CaptureRate | \
+ hdcmi->Init.VSPolarity | hdcmi->Init.HSPolarity | \
+ hdcmi->Init.PCKPolarity | hdcmi->Init.ExtendedDataMode | \
+ hdcmi->Init.JPEGMode);
+
+ if(hdcmi->Init.SynchroMode == DCMI_SYNCHRO_EMBEDDED)
+ {
+ DCMI->ESCR = (((uint32_t)hdcmi->Init.SyncroCode.FrameStartCode) |
+ ((uint32_t)hdcmi->Init.SyncroCode.LineStartCode << 8)|
+ ((uint32_t)hdcmi->Init.SyncroCode.LineEndCode << 16) |
+ ((uint32_t)hdcmi->Init.SyncroCode.FrameEndCode << 24));
+ }
+
+ /* Enable the Line interrupt */
+ __HAL_DCMI_ENABLE_IT(hdcmi, DCMI_IT_LINE);
+
+ /* Enable the VSYNC interrupt */
+ __HAL_DCMI_ENABLE_IT(hdcmi, DCMI_IT_VSYNC);
+
+ /* Enable the Frame capture complete interrupt */
+ __HAL_DCMI_ENABLE_IT(hdcmi, DCMI_IT_FRAME);
+
+ /* Enable the Synchronization error interrupt */
+ __HAL_DCMI_ENABLE_IT(hdcmi, DCMI_IT_ERR);
+
+ /* Enable the Overflow interrupt */
+ __HAL_DCMI_ENABLE_IT(hdcmi, DCMI_IT_OVF);
+
+ /* Enable DCMI by setting DCMIEN bit */
+ __HAL_DCMI_ENABLE(hdcmi);
+
+ /* Update error code */
+ hdcmi->ErrorCode = HAL_DCMI_ERROR_NONE;
+
+ /* Initialize the DCMI state*/
+ hdcmi->State = HAL_DCMI_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Deinitializes the DCMI peripheral registers to their default reset
+ * values.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval None
+ */
+
+HAL_StatusTypeDef HAL_DCMI_DeInit(DCMI_HandleTypeDef *hdcmi)
+{
+ /* DeInit the low level hardware */
+ HAL_DCMI_MspDeInit(hdcmi);
+
+ /* Update error code */
+ hdcmi->ErrorCode = HAL_DCMI_ERROR_NONE;
+
+ /* Initialize the DCMI state*/
+ hdcmi->State = HAL_DCMI_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hdcmi);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the DCMI MSP.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval None
+ */
+__weak void HAL_DCMI_MspInit(DCMI_HandleTypeDef* hdcmi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DCMI_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the DCMI MSP.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval None
+ */
+__weak void HAL_DCMI_MspDeInit(DCMI_HandleTypeDef* hdcmi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DCMI_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+/** @defgroup DCMI_Group2 IO operation functions
+ * @brief IO operation functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Configure destination address and data length and
+ Enables DCMI DMA request and enables DCMI capture
+ (+) Stop the DCMI capture.
+ (+) Handles DCMI interrupt request.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables DCMI DMA request and enables DCMI capture
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @param DCMI_Mode: DCMI capture mode snapshot or continuous grab.
+ * @param pData: The destination memory Buffer address (LCD Frame buffer).
+ * @param Length: The length of capture to be transferred.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef* hdcmi, uint32_t DCMI_Mode, uint32_t pData, uint32_t Length)
+{
+ /* Initialise the second memory address */
+ uint32_t SecondMemAddress = 0;
+
+ /* Check function parameters */
+ assert_param(IS_DCMI_CAPTURE_MODE(DCMI_Mode));
+
+ /* Process Locked */
+ __HAL_LOCK(hdcmi);
+
+ /* Lock the DCMI peripheral state */
+ hdcmi->State = HAL_DCMI_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DCMI_CAPTURE_MODE(DCMI_Mode));
+
+ /* Configure the DCMI Mode */
+ hdcmi->Instance->CR &= ~(DCMI_CR_CM);
+ hdcmi->Instance->CR |= (uint32_t)(DCMI_Mode);
+
+ /* Set the DMA memory0 conversion complete callback */
+ hdcmi->DMA_Handle->XferCpltCallback = DCMI_DMAConvCplt;
+
+ /* Set the DMA error callback */
+ hdcmi->DMA_Handle->XferErrorCallback = DCMI_DMAError;
+
+ if(Length <= 0xFFFF)
+ {
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hdcmi->DMA_Handle, (uint32_t)&hdcmi->Instance->DR, (uint32_t)pData, Length);
+ }
+ else /* DCMI_DOUBLE_BUFFER Mode */
+ {
+ /* Set the DMA memory1 conversion complete callback */
+ hdcmi->DMA_Handle->XferM1CpltCallback = DCMI_DMAConvCplt;
+
+ /* Initialise transfer parameters */
+ hdcmi->XferCount = 1;
+ hdcmi->XferSize = Length;
+ hdcmi->pBuffPtr = pData;
+
+ /* Get the number of buffer */
+ while(hdcmi->XferSize > 0xFFFF)
+ {
+ hdcmi->XferSize = (hdcmi->XferSize/2);
+ hdcmi->XferCount = hdcmi->XferCount*2;
+ }
+
+ /* Update DCMI counter and transfer number*/
+ hdcmi->XferCount = (hdcmi->XferCount - 2);
+ hdcmi->XferTransferNumber = hdcmi->XferCount;
+
+ /* Update second memory address */
+ SecondMemAddress = (uint32_t)(pData + (4*hdcmi->XferSize));
+
+ /* Start DMA multi buffer transfer */
+ HAL_DMAEx_MultiBufferStart_IT(hdcmi->DMA_Handle, (uint32_t)&hdcmi->Instance->DR, (uint32_t)pData, SecondMemAddress, hdcmi->XferSize);
+ }
+
+ /* Enable Capture */
+ DCMI->CR |= DCMI_CR_CAPTURE;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Disable DCMI DMA request and Disable DCMI capture
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ */
+HAL_StatusTypeDef HAL_DCMI_Stop(DCMI_HandleTypeDef* hdcmi)
+{
+ uint32_t timeout = 0x00;
+
+ /* Lock the DCMI peripheral state */
+ hdcmi->State = HAL_DCMI_STATE_BUSY;
+
+ __HAL_DCMI_DISABLE(hdcmi);
+
+ /* Disable Capture */
+ DCMI->CR &= ~(DCMI_CR_CAPTURE);
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + HAL_TIMEOUT_DCMI_STOP;
+
+ /* Check if the DCMI capture effectively disabled */
+ while((hdcmi->Instance->CR & DCMI_CR_CAPTURE) != 0)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ /* Update error code */
+ hdcmi->ErrorCode |= HAL_DCMI_ERROR_TIMEOUT;
+
+ /* Change DCMI state */
+ hdcmi->State = HAL_DCMI_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Disable the DMA */
+ HAL_DMA_Abort(hdcmi->DMA_Handle);
+
+ /* Update error code */
+ hdcmi->ErrorCode |= HAL_DCMI_ERROR_NONE;
+
+ /* Change DCMI state */
+ hdcmi->State = HAL_DCMI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Handles DCMI interrupt request.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for the DCMI.
+ * @retval HAL status
+ */
+void HAL_DCMI_IRQHandler(DCMI_HandleTypeDef *hdcmi)
+{
+ /* Synchronization error interrupt management *******************************/
+ if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_ERRRI) != RESET)
+ {
+ if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_ERR) != RESET)
+ {
+ /* Disable the Synchronization error interrupt */
+ __HAL_DCMI_DISABLE_IT(hdcmi, DCMI_IT_ERR);
+
+ /* Clear the Synchronization error flag */
+ __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_ERRRI);
+
+ /* Update error code */
+ hdcmi->ErrorCode |= HAL_DCMI_ERROR_SYNC;
+
+ /* Change DCMI state */
+ hdcmi->State = HAL_DCMI_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ /* Abort the DMA Transfer */
+ HAL_DMA_Abort(hdcmi->DMA_Handle);
+
+ /* Synchronization error Callback */
+ HAL_DCMI_ErrorCallback(hdcmi);
+ }
+ }
+ /* Overflow interrupt management ********************************************/
+ if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_OVFRI) != RESET)
+ {
+ if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_OVF) != RESET)
+ {
+ /* Disable the Overflow interrupt */
+ __HAL_DCMI_DISABLE_IT(hdcmi, DCMI_IT_OVF);
+
+ /* Clear the Overflow flag */
+ __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_OVFRI);
+
+ /* Update error code */
+ hdcmi->ErrorCode |= HAL_DCMI_ERROR_OVF;
+
+ /* Change DCMI state */
+ hdcmi->State = HAL_DCMI_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ /* Abort the DMA Transfer */
+ HAL_DMA_Abort(hdcmi->DMA_Handle);
+
+ /* Overflow Callback */
+ HAL_DCMI_ErrorCallback(hdcmi);
+ }
+ }
+ /* Line Interrupt management ************************************************/
+ if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_LINERI) != RESET)
+ {
+ if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_LINE) != RESET)
+ {
+ /* Clear the Line interrupt flag */
+ __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_LINERI);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ /* Line interrupt Callback */
+ HAL_DCMI_LineEventCallback(hdcmi);
+ }
+ }
+ /* VSYNC interrupt management ***********************************************/
+ if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_VSYNCRI) != RESET)
+ {
+ if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_VSYNC) != RESET)
+ {
+ /* Disable the VSYNC interrupt */
+ __HAL_DCMI_DISABLE_IT(hdcmi, DCMI_IT_VSYNC);
+
+ /* Clear the VSYNC flag */
+ __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_VSYNCRI);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ /* VSYNC Callback */
+ HAL_DCMI_VsyncEventCallback(hdcmi);
+ }
+ }
+ /* End of Frame interrupt management ****************************************/
+ if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_FRAMERI) != RESET)
+ {
+ if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_FRAME) != RESET)
+ {
+ /* Disable the End of Frame interrupt */
+ __HAL_DCMI_DISABLE_IT(hdcmi, DCMI_IT_FRAME);
+
+ /* Clear the End of Frame flag */
+ __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_FRAMERI);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ /* End of Frame Callback */
+ HAL_DCMI_FrameEventCallback(hdcmi);
+ }
+ }
+}
+
+/**
+ * @brief Error DCMI callback.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval None
+ */
+__weak void HAL_DCMI_ErrorCallback(DCMI_HandleTypeDef *hdcmi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DCMI_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Line Event callback.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval None
+ */
+__weak void HAL_DCMI_LineEventCallback(DCMI_HandleTypeDef *hdcmi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DCMI_LineEventCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief VSYNC Event callback.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval None
+ */
+__weak void HAL_DCMI_VsyncEventCallback(DCMI_HandleTypeDef *hdcmi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DCMI_VsyncEventCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Frame Event callback.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval None
+ */
+__weak void HAL_DCMI_FrameEventCallback(DCMI_HandleTypeDef *hdcmi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DCMI_FrameEventCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DCMI_Group3 Peripheral Control functions
+ * @brief Peripheral Control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+[..] This section provides functions allowing to:
+ (+) Configure the CROP feature.
+ (+) ENABLE/DISABLE the CROP feature.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Configure the DCMI CROP coordinate.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @param YSize: DCMI Line number
+ * @param XSize: DCMI Pixel per line
+ * @param X0: DCMI window X offset
+ * @param Y0: DCMI window Y offset
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DCMI_ConfigCROP(DCMI_HandleTypeDef *hdcmi, uint32_t X0, uint32_t Y0, uint32_t XSize, uint32_t YSize)
+{
+ /* Process Locked */
+ __HAL_LOCK(hdcmi);
+
+ /* Lock the DCMI peripheral state */
+ hdcmi->State = HAL_DCMI_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DCMI_WINDOW_COORDINATE(X0));
+ assert_param(IS_DCMI_WINDOW_COORDINATE(Y0));
+ assert_param(IS_DCMI_WINDOW_COORDINATE(XSize));
+ assert_param(IS_DCMI_WINDOW_HEIGHT(YSize));
+
+ /* Configure CROP */
+ DCMI->CWSIZER = (XSize | (YSize << 16));
+ DCMI->CWSTRTR = (X0 | (Y0 << 16));
+
+ /* Initialize the DCMI state*/
+ hdcmi->State = HAL_DCMI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disable the Crop feature.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_DCMI_DisableCROP(DCMI_HandleTypeDef *hdcmi)
+{
+ /* Process Locked */
+ __HAL_LOCK(hdcmi);
+
+ /* Lock the DCMI peripheral state */
+ hdcmi->State = HAL_DCMI_STATE_BUSY;
+
+ /* Disable DCMI Crop feature */
+ DCMI->CR &= ~(uint32_t)DCMI_CR_CROP;
+
+ /* Change the DCMI state*/
+ hdcmi->State = HAL_DCMI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enable the Crop feature.
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_DCMI_EnableCROP(DCMI_HandleTypeDef *hdcmi)
+{
+ /* Process Locked */
+ __HAL_LOCK(hdcmi);
+
+ /* Lock the DCMI peripheral state */
+ hdcmi->State = HAL_DCMI_STATE_BUSY;
+
+ /* Enable DCMI Crop feature */
+ DCMI->CR |= (uint32_t)DCMI_CR_CROP;
+
+ /* Change the DCMI state*/
+ hdcmi->State = HAL_DCMI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DCMI_Group4 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State and Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Check the DCMI state.
+ (+) Get the specific DCMI error flag.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the DCMI state
+ * @param hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+ * @retval HAL state
+ */
+HAL_DCMI_StateTypeDef HAL_DCMI_GetState(DCMI_HandleTypeDef *hdcmi)
+{
+ return hdcmi->State;
+}
+
+/**
+* @brief Return the DCMI error code
+* @param hdcmi : pointer to a DCMI_HandleTypeDef structure that contains
+ * the configuration information for DCMI.
+* @retval DCMI Error Code
+*/
+uint32_t HAL_DCMI_GetError(DCMI_HandleTypeDef *hdcmi)
+{
+ return hdcmi->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+ /**
+ * @brief DMA conversion complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void DCMI_DMAConvCplt(DMA_HandleTypeDef *hdma)
+{
+ uint32_t tmp = 0;
+
+ DCMI_HandleTypeDef* hdcmi = ( DCMI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ hdcmi->State= HAL_DCMI_STATE_READY;
+
+ if(hdcmi->XferCount != 0)
+ {
+ /* Update memory 0 address location */
+ tmp = ((hdcmi->DMA_Handle->Instance->CR) & DMA_SxCR_CT);
+ if(((hdcmi->XferCount % 2) == 0) && (tmp != 0))
+ {
+ tmp = hdcmi->DMA_Handle->Instance->M0AR;
+ HAL_DMAEx_ChangeMemory(hdcmi->DMA_Handle, (tmp + (8*hdcmi->XferSize)), MEMORY0);
+ hdcmi->XferCount--;
+ }
+ /* Update memory 1 address location */
+ else if((hdcmi->DMA_Handle->Instance->CR & DMA_SxCR_CT) == 0)
+ {
+ tmp = hdcmi->DMA_Handle->Instance->M1AR;
+ HAL_DMAEx_ChangeMemory(hdcmi->DMA_Handle, (tmp + (8*hdcmi->XferSize)), MEMORY1);
+ hdcmi->XferCount--;
+ }
+ }
+ /* Update memory 0 address location */
+ else if((hdcmi->DMA_Handle->Instance->CR & DMA_SxCR_CT) != 0)
+ {
+ hdcmi->DMA_Handle->Instance->M0AR = hdcmi->pBuffPtr;
+ }
+ /* Update memory 1 address location */
+ else if((hdcmi->DMA_Handle->Instance->CR & DMA_SxCR_CT) == 0)
+ {
+ tmp = hdcmi->pBuffPtr;
+ hdcmi->DMA_Handle->Instance->M1AR = (tmp + (4*hdcmi->XferSize));
+ hdcmi->XferCount = hdcmi->XferTransferNumber;
+ }
+
+ if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_FRAMERI) != RESET)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdcmi);
+
+ /* FRAME Callback */
+ HAL_DCMI_FrameEventCallback(hdcmi);
+ }
+}
+
+/**
+ * @brief DMA error callback
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+static void DCMI_DMAError(DMA_HandleTypeDef *hdma)
+{
+ DCMI_HandleTypeDef* hdcmi = ( DCMI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ hdcmi->State= HAL_DCMI_STATE_READY;
+ HAL_DCMI_ErrorCallback(hdcmi);
+}
+
+/**
+ * @}
+ */
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_DCMI_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma.c
new file mode 100644
index 0000000..40e1bbc
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma.c
@@ -0,0 +1,888 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_dma.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief DMA HAL module driver.
+ *
+ * This file provides firmware functions to manage the following
+ * functionalities of the Direct Memory Access (DMA) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral State and errors functions
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#) Enable and configure the peripheral to be connected to the DMA Stream
+ (except for internal SRAM/FLASH memories: no initialization is
+ necessary) please refer to Reference manual for connection between peripherals
+ and DMA requests .
+
+ (#) For a given Stream, program the required configuration through the following parameters:
+ Transfer Direction, Source and Destination data formats,
+ Circular, Normal or peripheral flow control mode, Stream Priority level,
+ Source and Destination Increment mode, FIFO mode and its Threshold (if needed),
+ Burst mode for Source and/or Destination (if needed) using HAL_DMA_Init() function.
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Use HAL_DMA_Start() to start DMA transfer after the configuration of Source
+ address and destination address and the Length of data to be transferred
+ (+) Use HAL_DMA_PollForTransfer() to poll for the end of current transfer, in this
+ case a fixed Timeout can be configured by User depending from his application.
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Configure the DMA interrupt priority using HAL_NVIC_SetPriority()
+ (+) Enable the DMA IRQ handler using HAL_NVIC_EnableIRQ()
+ (+) Use HAL_DMA_Start_IT() to start DMA transfer after the configuration of
+ Source address and destination address and the Length of data to be transferred. In this
+ case the DMA interrupt is configured
+ (+) Use HAL_DMA_IRQHandler() called under DMA_IRQHandler() Interrupt subroutine
+ (+) At the end of data transfer HAL_DMA_IRQHandler() function is executed and user can
+ add his own function by customization of function pointer XferCpltCallback and
+ XferErrorCallback (i.e a member of DMA handle structure).
+
+ (#) Use HAL_DMA_GetState() function to return the DMA state and HAL_DMA_GetError() in case of error
+ detection.
+
+ (#) Use HAL_DMA_Abort() function to abort the current transfer
+
+ -@- In Memory-to-Memory transfer mode, Circular mode is not allowed.
+
+ -@- The FIFO is used mainly to reduce bus usage and to allow data packing/unpacking: it is
+ possible to set different Data Sizes for the Peripheral and the Memory (ie. you can set
+ Half-Word data size for the peripheral to access its data register and set Word data size
+ for the Memory to gain in access time. Each two half words will be packed and written in
+ a single access to a Word in the Memory).
+
+ -@- When FIFO is disabled, it is not allowed to configure different Data Sizes for Source
+ and Destination. In this case the Peripheral Data Size will be applied to both Source
+ and Destination.
+
+ *** DMA HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in DMA HAL driver.
+
+ (+) __HAL_DMA_ENABLE: Enable the specified DMA Stream.
+ (+) __HAL_DMA_DISABLE: Disable the specified DMA Stream.
+ (+) __HAL_DMA_GET_FS: Return the current DMA Stream FIFO filled level.
+ (+) __HAL_DMA_GET_FLAG: Get the DMA Stream pending flags.
+ (+) __HAL_DMA_CLEAR_FLAG: Clear the DMA Stream pending flags.
+ (+) __HAL_DMA_ENABLE_IT: Enable the specified DMA Stream interrupts.
+ (+) __HAL_DMA_DISABLE_IT: Disable the specified DMA Stream interrupts.
+ (+) __HAL_DMA_GET_IT_SOURCE: Check whether the specified DMA Stream interrupt has occurred or not.
+
+ [..]
+ (@) You can refer to the DMA HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup DMA
+ * @brief DMA HAL module driver
+ * @{
+ */
+
+#ifdef HAL_DMA_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define HAL_TIMEOUT_DMA_ABORT ((uint32_t)1000) /* 1s */
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup DMA_Private_Functions
+ * @{
+ */
+
+/** @defgroup DMA_Group1 Initialization and de-initialization functions
+ * @brief Initialization and de-initialization functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..]
+ This section provides functions allowing to initialize the DMA Stream source
+ and destination addresses, incrementation and data sizes, transfer direction,
+ circular/normal mode selection, memory-to-memory mode selection and Stream priority value.
+ [..]
+ The HAL_DMA_Init() function follows the DMA configuration procedures as described in
+ reference manual.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the DMA according to the specified
+ * parameters in the DMA_InitTypeDef and create the associated handle.
+ * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma)
+{
+ uint32_t tmp = 0;
+
+ /* Check the DMA peripheral state */
+ if(hdma == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_DMA_STREAM_ALL_INSTANCE(hdma->Instance));
+ assert_param(IS_DMA_CHANNEL(hdma->Init.Channel));
+ assert_param(IS_DMA_DIRECTION(hdma->Init.Direction));
+ assert_param(IS_DMA_PERIPHERAL_INC_STATE(hdma->Init.PeriphInc));
+ assert_param(IS_DMA_MEMORY_INC_STATE(hdma->Init.MemInc));
+ assert_param(IS_DMA_PERIPHERAL_DATA_SIZE(hdma->Init.PeriphDataAlignment));
+ assert_param(IS_DMA_MEMORY_DATA_SIZE(hdma->Init.MemDataAlignment));
+ assert_param(IS_DMA_MODE(hdma->Init.Mode));
+ assert_param(IS_DMA_PRIORITY(hdma->Init.Priority));
+ assert_param(IS_DMA_FIFO_MODE_STATE(hdma->Init.FIFOMode));
+ /* Check the memory burst, peripheral burst and FIFO threshold parameters only
+ when FIFO mode is enabled */
+ if(hdma->Init.FIFOMode != DMA_FIFOMODE_DISABLE)
+ {
+ assert_param(IS_DMA_FIFO_THRESHOLD(hdma->Init.FIFOThreshold));
+ assert_param(IS_DMA_MEMORY_BURST(hdma->Init.MemBurst));
+ assert_param(IS_DMA_PERIPHERAL_BURST(hdma->Init.PeriphBurst));
+ }
+
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_BUSY;
+
+ /* Get the CR register value */
+ tmp = hdma->Instance->CR;
+
+ /* Clear CHSEL, MBURST, PBURST, PL, MSIZE, PSIZE, MINC, PINC, CIRC, DIR and CT bits */
+ tmp &= ((uint32_t)~(DMA_SxCR_CHSEL | DMA_SxCR_MBURST | DMA_SxCR_PBURST | \
+ DMA_SxCR_PL | DMA_SxCR_MSIZE | DMA_SxCR_PSIZE | \
+ DMA_SxCR_MINC | DMA_SxCR_PINC | DMA_SxCR_CIRC | \
+ DMA_SxCR_DIR | DMA_SxCR_CT ));
+
+ /* Prepare the DMA Stream configuration */
+ tmp |= hdma->Init.Channel | hdma->Init.Direction |
+ hdma->Init.PeriphInc | hdma->Init.MemInc |
+ hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment |
+ hdma->Init.Mode | hdma->Init.Priority;
+
+ /* the Memory burst and peripheral burst are not used when the FIFO is disabled */
+ if(hdma->Init.FIFOMode == DMA_FIFOMODE_ENABLE)
+ {
+ /* Get memory burst and peripheral burst */
+ tmp |= hdma->Init.MemBurst | hdma->Init.PeriphBurst;
+ }
+
+ /* Write to DMA Stream CR register */
+ hdma->Instance->CR = tmp;
+
+ /* Get the FCR register value */
+ tmp = hdma->Instance->FCR;
+
+ /* Clear Direct mode and FIFO threshold bits */
+ tmp &= (uint32_t)~(DMA_SxFCR_DMDIS | DMA_SxFCR_FTH);
+
+ /* Prepare the DMA Stream FIFO configuration */
+ tmp |= hdma->Init.FIFOMode;
+
+ /* the FIFO threshold is not used when the FIFO mode is disabled */
+ if(hdma->Init.FIFOMode == DMA_FIFOMODE_ENABLE)
+ {
+ /* Get the FIFO threshold */
+ tmp |= hdma->Init.FIFOThreshold;
+ }
+
+ /* Write to DMA Stream FCR */
+ hdma->Instance->FCR = tmp;
+
+ /* Initialise the error code */
+ hdma->ErrorCode = HAL_DMA_ERROR_NONE;
+
+ /* Initialize the DMA state */
+ hdma->State = HAL_DMA_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the DMA peripheral
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma)
+{
+ /* Check the DMA peripheral state */
+ if(hdma->State == HAL_DMA_STATE_BUSY)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Disable the selected DMA Streamx */
+ __HAL_DMA_DISABLE(hdma);
+
+ /* Reset DMA Streamx control register */
+ hdma->Instance->CR = 0;
+
+ /* Reset DMA Streamx number of data to transfer register */
+ hdma->Instance->NDTR = 0;
+
+ /* Reset DMA Streamx peripheral address register */
+ hdma->Instance->PAR = 0;
+
+ /* Reset DMA Streamx memory 0 address register */
+ hdma->Instance->M0AR = 0;
+
+ /* Reset DMA Streamx memory 1 address register */
+ hdma->Instance->M1AR = 0;
+
+ /* Reset DMA Streamx FIFO control register */
+ hdma->Instance->FCR = (uint32_t)0x00000021;
+
+ /* Clear all flags */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma));
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma));
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma));
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
+
+ /* Initialise the error code */
+ hdma->ErrorCode = HAL_DMA_ERROR_NONE;
+
+ /* Initialize the DMA state */
+ hdma->State = HAL_DMA_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hdma);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DMA_Group2 I/O operation functions
+ * @brief I/O operation functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Configure the source, destination address and data length and Start DMA transfer
+ (+) Configure the source, destination address and data length and
+ Start DMA transfer with interrupt
+ (+) Abort DMA transfer
+ (+) Poll for transfer complete
+ (+) Handle DMA interrupt request
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Starts the DMA Transfer.
+ * @param hdma : pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @param SrcAddress: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param DataLength: The length of data to be transferred from source to destination
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
+{
+ /* Process locked */
+ __HAL_LOCK(hdma);
+
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DMA_BUFFER_SIZE(DataLength));
+
+ /* Disable the peripheral */
+ __HAL_DMA_DISABLE(hdma);
+
+ /* Configure the source, destination address and the data length */
+ DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength);
+
+ /* Enable the Peripheral */
+ __HAL_DMA_ENABLE(hdma);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Start the DMA Transfer with interrupt enabled.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @param SrcAddress: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param DataLength: The length of data to be transferred from source to destination
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
+{
+ /* Process locked */
+ __HAL_LOCK(hdma);
+
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DMA_BUFFER_SIZE(DataLength));
+
+ /* Disable the peripheral */
+ __HAL_DMA_DISABLE(hdma);
+
+ /* Configure the source, destination address and the data length */
+ DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength);
+
+ /* Enable the transfer complete interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TC);
+
+ /* Enable the Half transfer complete interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_HT);
+
+ /* Enable the transfer Error interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TE);
+
+ /* Enable the FIFO Error interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_FE);
+
+ /* Enable the direct mode Error interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_DME);
+
+ /* Enable the Peripheral */
+ __HAL_DMA_ENABLE(hdma);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Aborts the DMA Transfer.
+ * @param hdma : pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ *
+ * @note After disabling a DMA Stream, a check for wait until the DMA Stream is
+ * effectively disabled is added. If a Stream is disabled
+ * while a data transfer is ongoing, the current data will be transferred
+ * and the Stream will be effectively disabled only after the transfer of
+ * this single data is finished.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma)
+{
+ uint32_t timeout = 0x00;
+
+ /* Disable the stream */
+ __HAL_DMA_DISABLE(hdma);
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + HAL_TIMEOUT_DMA_ABORT;
+
+ /* Check if the DMA Stream is effectively disabled */
+ while((hdma->Instance->CR & DMA_SxCR_EN) != 0)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Update error code */
+ hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+
+ /* Change the DMA state */
+ hdma->State = HAL_DMA_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+
+ /* Change the DMA state*/
+ hdma->State = HAL_DMA_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Polling for transfer complete.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @param CompleteLevel: Specifies the DMA level complete.
+ * @param Timeout: Timeout duration.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout)
+{
+ uint32_t temp, tmp, tmp1, tmp2;
+ uint32_t timeout = 0x00;
+
+ /* Get the level transfer complete flag */
+ if(CompleteLevel == HAL_DMA_FULL_TRANSFER)
+ {
+ /* Transfer Complete flag */
+ temp = __HAL_DMA_GET_TC_FLAG_INDEX(hdma);
+ }
+ else
+ {
+ /* Half Transfer Complete flag */
+ temp = __HAL_DMA_GET_HT_FLAG_INDEX(hdma);
+ }
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_DMA_GET_FLAG(hdma, temp) == RESET)
+ {
+ tmp = __HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma));
+ tmp1 = __HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma));
+ tmp2 = __HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma));
+ if((tmp != RESET) || (tmp1 != RESET) || (tmp2 != RESET))
+ {
+ /* Clear the transfer error flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma));
+ /* Clear the FIFO error flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma));
+ /* Clear the DIrect Mode error flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma));
+
+ /* Change the DMA state */
+ hdma->State= HAL_DMA_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+
+ return HAL_ERROR;
+ }
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Update error code */
+ hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+
+ /* Change the DMA state */
+ hdma->State = HAL_DMA_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Clear the half transfer complete flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
+
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_READY_HALF_MEM0;
+
+ if(CompleteLevel == HAL_DMA_FULL_TRANSFER)
+ {
+ /* Multi_Buffering mode enabled */
+ if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0)
+ {
+ /* Clear the transfer complete flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
+
+ /* Current memory buffer used is Memory 0 */
+ if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
+ {
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_READY_MEM0;
+ }
+ /* Current memory buffer used is Memory 1 */
+ else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
+ {
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_READY_MEM1;
+ }
+ }
+ else
+ {
+ /* Clear the transfer complete flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
+
+ /* The selected Streamx EN bit is cleared (DMA is disabled and all transfers
+ are complete) */
+ hdma->State = HAL_DMA_STATE_READY_MEM0;
+ }
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+ }
+ else
+ {
+ /* Multi_Buffering mode enabled */
+ if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0)
+ {
+ /* Clear the half transfer complete flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
+
+ /* Current memory buffer used is Memory 0 */
+ if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
+ {
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_READY_HALF_MEM0;
+ }
+ /* Current memory buffer used is Memory 1 */
+ else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
+ {
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_READY_HALF_MEM1;
+ }
+ }
+ else
+ {
+ /* Clear the half transfer complete flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
+
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_READY_HALF_MEM0;
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Handles DMA interrupt request.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @retval None
+ */
+void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma)
+{
+ /* Transfer Error Interrupt management ***************************************/
+ if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET)
+ {
+ if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TE) != RESET)
+ {
+ /* Disable the transfer error interrupt */
+ __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TE);
+
+ /* Clear the transfer error flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma));
+
+ /* Update error code */
+ hdma->ErrorCode |= HAL_DMA_ERROR_TE;
+
+ /* Change the DMA state */
+ hdma->State = HAL_DMA_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+
+ if(hdma->XferErrorCallback != NULL)
+ {
+ /* Transfer error callback */
+ hdma->XferErrorCallback(hdma);
+ }
+ }
+ }
+ /* FIFO Error Interrupt management ******************************************/
+ if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma)) != RESET)
+ {
+ if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_FE) != RESET)
+ {
+ /* Disable the FIFO Error interrupt */
+ __HAL_DMA_DISABLE_IT(hdma, DMA_IT_FE);
+
+ /* Clear the FIFO error flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma));
+
+ /* Update error code */
+ hdma->ErrorCode |= HAL_DMA_ERROR_FE;
+
+ /* Change the DMA state */
+ hdma->State = HAL_DMA_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+
+ if(hdma->XferErrorCallback != NULL)
+ {
+ /* Transfer error callback */
+ hdma->XferErrorCallback(hdma);
+ }
+ }
+ }
+ /* Direct Mode Error Interrupt management ***********************************/
+ if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma)) != RESET)
+ {
+ if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_DME) != RESET)
+ {
+ /* Disable the direct mode Error interrupt */
+ __HAL_DMA_DISABLE_IT(hdma, DMA_IT_DME);
+
+ /* Clear the direct mode error flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma));
+
+ /* Update error code */
+ hdma->ErrorCode |= HAL_DMA_ERROR_DME;
+
+ /* Change the DMA state */
+ hdma->State = HAL_DMA_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+
+ if(hdma->XferErrorCallback != NULL)
+ {
+ /* Transfer error callback */
+ hdma->XferErrorCallback(hdma);
+ }
+ }
+ }
+ /* Half Transfer Complete Interrupt management ******************************/
+ if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)) != RESET)
+ {
+ if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_HT) != RESET)
+ {
+ /* Multi_Buffering mode enabled */
+ if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0)
+ {
+ /* Clear the half transfer complete flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
+
+ /* Current memory buffer used is Memory 0 */
+ if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
+ {
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_READY_HALF_MEM0;
+ }
+ /* Current memory buffer used is Memory 1 */
+ else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
+ {
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_READY_HALF_MEM1;
+ }
+ }
+ else
+ {
+ /* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */
+ if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
+ {
+ /* Disable the half transfer interrupt */
+ __HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT);
+ }
+ /* Clear the half transfer complete flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
+
+ /* Change DMA peripheral state */
+ hdma->State = HAL_DMA_STATE_READY_HALF_MEM0;
+ }
+
+ if(hdma->XferHalfCpltCallback != NULL)
+ {
+ /* Half transfer callback */
+ hdma->XferHalfCpltCallback(hdma);
+ }
+ }
+ }
+ /* Transfer Complete Interrupt management ***********************************/
+ if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)) != RESET)
+ {
+ if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TC) != RESET)
+ {
+ if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0)
+ {
+ /* Clear the transfer complete flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
+
+ /* Current memory buffer used is Memory 1 */
+ if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
+ {
+ if(hdma->XferM1CpltCallback != NULL)
+ {
+ /* Transfer complete Callback for memory1 */
+ hdma->XferM1CpltCallback(hdma);
+ }
+ }
+ /* Current memory buffer used is Memory 0 */
+ else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
+ {
+ if(hdma->XferCpltCallback != NULL)
+ {
+ /* Transfer complete Callback for memory0 */
+ hdma->XferCpltCallback(hdma);
+ }
+ }
+ }
+ /* Disable the transfer complete interrupt if the DMA mode is not CIRCULAR */
+ else
+ {
+ if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
+ {
+ /* Disable the transfer complete interrupt */
+ __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TC);
+ }
+ /* Clear the transfer complete flag */
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
+
+ /* Update error code */
+ hdma->ErrorCode |= HAL_DMA_ERROR_NONE;
+
+ /* Change the DMA state */
+ hdma->State = HAL_DMA_STATE_READY_MEM0;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+
+ if(hdma->XferCpltCallback != NULL)
+ {
+ /* Transfer complete callback */
+ hdma->XferCpltCallback(hdma);
+ }
+ }
+ }
+ }
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DMA_Group3 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### State and Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Check the DMA state
+ (+) Get error code
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the DMA state.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @retval HAL state
+ */
+HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma)
+{
+ return hdma->State;
+}
+
+/**
+ * @brief Return the DMA error code
+ * @param hdma : pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @retval DMA Error Code
+ */
+uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma)
+{
+ return hdma->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Sets the DMA Transfer parameter.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @param SrcAddress: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param DataLength: The length of data to be transferred from source to destination
+ * @retval HAL status
+ */
+static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
+{
+ /* Configure DMA Stream data length */
+ hdma->Instance->NDTR = DataLength;
+
+ /* Peripheral to Memory */
+ if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH)
+ {
+ /* Configure DMA Stream destination address */
+ hdma->Instance->PAR = DstAddress;
+
+ /* Configure DMA Stream source address */
+ hdma->Instance->M0AR = SrcAddress;
+ }
+ /* Memory to Peripheral */
+ else
+ {
+ /* Configure DMA Stream source address */
+ hdma->Instance->PAR = SrcAddress;
+
+ /* Configure DMA Stream destination address */
+ hdma->Instance->M0AR = DstAddress;
+ }
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_DMA_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma2d.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma2d.c
new file mode 100644
index 0000000..f090102
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma2d.c
@@ -0,0 +1,1239 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_dma2d.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief DMA2D HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the DMA2D peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State and Errors functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#) Program the required configuration through following parameters:
+ the Transfer Mode, the output color mode and the output offset using
+ HAL_DMA2D_Init() function.
+
+ (#) Program the required configuration through following parameters:
+ the input color mode, the input color, input alpha value, alpha mode
+ and the input offset using HAL_DMA2D_ConfigLayer() function for foreground
+ or/and background layer.
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Configure the pdata, Destination and data length and Enable
+ the transfer using HAL_DMA2D_Start()
+ (+) Wait for end of transfer using HAL_DMA2D_PollForTransfer(), at this stage
+ user can specify the value of timeout according to his end application.
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (#) Configure the pdata, Destination and data length and Enable
+ the transfer using HAL_DMA2D_Start_IT()
+ (#) Use HAL_DMA2D_IRQHandler() called under DMA2D_IRQHandler() Interrupt subroutine
+ (#) At the end of data transfer HAL_DMA2D_IRQHandler() function is executed and user can
+ add his own function by customization of function pointer XferCpltCallback and
+ XferErrorCallback (i.e a member of DMA2D handle structure).
+
+ -@- In Register-to-Memory transfer mode, the pdata parameter is the register
+ color, in Memory-to-memory or memory-to-memory with pixel format
+ conversion the pdata is the source address and it is the color value
+ for the A4 or A8 mode.
+
+ -@- Configure the foreground source address, the background source address,
+ the Destination and data length and Enable the transfer using
+ HAL_DMA2D_BlendingStart() in polling mode and HAL_DMA2D_BlendingStart_IT()
+ in interrupt mode.
+
+ -@- HAL_DMA2D_BlendingStart() and HAL_DMA2D_BlendingStart_IT() functions
+ are used if the memory to memory with blending transfer mode is selected.
+
+ (#) Optionally, configure and enable the CLUT using HAL_DMA2D_ConfigCLUT()
+ HAL_DMA2D_EnableCLUT() functions.
+
+ (#) Optionally, configure and enable LineInterrupt using the following function:
+ HAL_DMA2D_ProgramLineEvent().
+
+ (#) The transfer can be suspended, continued and aborted using the following
+ functions: HAL_DMA2D_Suspend(), HAL_DMA2D_Resume(), HAL_DMA2D_Abort().
+
+ (#) To control DMA2D state you can use the following function: HAL_DMA2D_GetState()
+
+ *** DMA2D HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in DMA2D HAL driver.
+
+ (+) __HAL_DMA2D_ENABLE: Enable the DMA2D peripheral.
+ (+) __HAL_DMA2D_DISABLE: Disable the DMA2D peripheral.
+ (+) __HAL_DMA2D_GET_FLAG: Get the DMA2D pending flags.
+ (+) __HAL_DMA2D_CLEAR_FLAG: Clears the DMA2D pending flags.
+ (+) __HAL_DMA2D_ENABLE_IT: Enables the specified DMA2D interrupts.
+ (+) __HAL_DMA2D_DISABLE_IT: Disables the specified DMA2D interrupts.
+ (+) __HAL_DMA2D_GET_IT_SOURCE: Checks whether the specified DMA2D interrupt has occurred or not.
+
+ [..]
+ (@) You can refer to the DMA2D HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+/** @defgroup DMA2D
+ * @brief DMA2D HAL module driver
+ * @{
+ */
+
+#ifdef HAL_DMA2D_MODULE_ENABLED
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define HAL_TIMEOUT_DMA2D_ABORT ((uint32_t)1000) /* 1s */
+#define HAL_TIMEOUT_DMA2D_SUSPEND ((uint32_t)1000) /* 1s */
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void DMA2D_SetConfig(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Heigh);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup DMA2D_Private_Functions
+ * @{
+ */
+
+/** @defgroup DMA2D_Group1 Initialization and Configuration functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and Configuration functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize and configure the DMA2D
+ (+) De-initialize the DMA2D
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the DMA2D according to the specified
+ * parameters in the DMA2D_InitTypeDef and create the associated handle.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_Init(DMA2D_HandleTypeDef *hdma2d)
+{
+ uint32_t tmp = 0;
+
+ /* Check the DMA2D peripheral state */
+ if(hdma2d == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_DMA2D_ALL_INSTANCE(hdma2d->Instance));
+ assert_param(IS_DMA2D_MODE(hdma2d->Init.Mode));
+ assert_param(IS_DMA2D_CMODE(hdma2d->Init.ColorMode));
+ assert_param(IS_DMA2D_OFFSET(hdma2d->Init.OutputOffset));
+
+ if(hdma2d->State == HAL_DMA2D_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_DMA2D_MspInit(hdma2d);
+ }
+
+ /* Change DMA2D peripheral state */
+ hdma2d->State = HAL_DMA2D_STATE_BUSY;
+
+/* DMA2D CR register configuration -------------------------------------------*/
+ /* Get the CR register value */
+ tmp = hdma2d->Instance->CR;
+
+ /* Clear Mode bits */
+ tmp &= (uint32_t)~DMA2D_CR_MODE;
+
+ /* Prepare the value to be wrote to the CR register */
+ tmp |= hdma2d->Init.Mode;
+
+ /* Write to DMA2D CR register */
+ hdma2d->Instance->CR = tmp;
+
+/* DMA2D OPFCCR register configuration ---------------------------------------*/
+ /* Get the OPFCCR register value */
+ tmp = hdma2d->Instance->OPFCCR;
+
+ /* Clear Color Mode bits */
+ tmp &= (uint32_t)~DMA2D_OPFCCR_CM;
+
+ /* Prepare the value to be wrote to the OPFCCR register */
+ tmp |= hdma2d->Init.ColorMode;
+
+ /* Write to DMA2D OPFCCR register */
+ hdma2d->Instance->OPFCCR = tmp;
+
+/* DMA2D OOR register configuration ------------------------------------------*/
+ /* Get the OOR register value */
+ tmp = hdma2d->Instance->OOR;
+
+ /* Clear Offset bits */
+ tmp &= (uint32_t)~DMA2D_OOR_LO;
+
+ /* Prepare the value to be wrote to the OOR register */
+ tmp |= hdma2d->Init.OutputOffset;
+
+ /* Write to DMA2D OOR register */
+ hdma2d->Instance->OOR = tmp;
+
+ /* Update error code */
+ hdma2d->ErrorCode = HAL_DMA2D_ERROR_NONE;
+
+ /* Initialize the DMA2D state*/
+ hdma2d->State = HAL_DMA2D_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Deinitializes the DMA2D peripheral registers to their default reset
+ * values.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @retval None
+ */
+
+HAL_StatusTypeDef HAL_DMA2D_DeInit(DMA2D_HandleTypeDef *hdma2d)
+{
+ /* Check the DMA2D peripheral state */
+ if(hdma2d == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* DeInit the low level hardware */
+ HAL_DMA2D_MspDeInit(hdma2d);
+
+ /* Update error code */
+ hdma2d->ErrorCode = HAL_DMA2D_ERROR_NONE;
+
+ /* Initialize the DMA2D state*/
+ hdma2d->State = HAL_DMA2D_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hdma2d);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the DMA2D MSP.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @retval None
+ */
+__weak void HAL_DMA2D_MspInit(DMA2D_HandleTypeDef* hdma2d)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DMA2D_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the DMA2D MSP.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @retval None
+ */
+__weak void HAL_DMA2D_MspDeInit(DMA2D_HandleTypeDef* hdma2d)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_DMA2D_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DMA2D_Group2 IO operation functions
+ * @brief IO operation functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Configure the pdata, destination address and data size and
+ Start DMA2D transfer.
+ (+) Configure the source for foreground and background, destination address
+ and data size and Start MultiBuffer DMA2D transfer.
+ (+) Configure the pdata, destination address and data size and
+ Start DMA2D transfer with interrupt.
+ (+) Configure the source for foreground and background, destination address
+ and data size and Start MultiBuffer DMA2D transfer with interrupt.
+ (+) Abort DMA2D transfer.
+ (+) Suspend DMA2D transfer.
+ (+) Continue DMA2D transfer.
+ (+) polling for transfer complete.
+ (+) handles DMA2D interrupt request.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Start the DMA2D Transfer.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @param pdata: Configure the source memory Buffer address if
+ * the memory to memory or memory to memory with pixel format
+ * conversion DMA2D mode is selected, and configure
+ * the color value if register to memory DMA2D mode is selected
+ * or the color value for the A4 or A8 mode.
+ * @param DstAddress: The destination memory Buffer address.
+ * @param Width: The width of data to be transferred from source to destination.
+ * @param Heigh: The heigh of data to be transferred from source to destination.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_Start(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Heigh)
+{
+ /* Process locked */
+ __HAL_LOCK(hdma2d);
+
+ /* Change DMA2D peripheral state */
+ hdma2d->State = HAL_DMA2D_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DMA2D_LINE(Heigh));
+ assert_param(IS_DMA2D_PIXEL(Width));
+
+ /* Disable the Peripheral */
+ __HAL_DMA2D_DISABLE(hdma2d);
+
+ /* Configure the source, destination address and the data size */
+ DMA2D_SetConfig(hdma2d, pdata, DstAddress, Width, Heigh);
+
+ /* Enable the Peripheral */
+ __HAL_DMA2D_ENABLE(hdma2d);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Start the DMA2D Transfer with interrupt enabled.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @param pdata: Configure the source memory Buffer address if
+ * the memory to memory or memory to memory with pixel format
+ * conversion DMA2D mode is selected, and configure
+ * the color value if register to memory DMA2D mode is selected
+ * or the color value for the A4 or A8 mode.
+ * @param DstAddress: The destination memory Buffer address.
+ * @param Width: The width of data to be transferred from source to destination.
+ * @param Heigh: The heigh of data to be transferred from source to destination.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_Start_IT(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Heigh)
+{
+ /* Process locked */
+ __HAL_LOCK(hdma2d);
+
+ /* Change DMA2D peripheral state */
+ hdma2d->State = HAL_DMA2D_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DMA2D_LINE(Heigh));
+ assert_param(IS_DMA2D_PIXEL(Width));
+
+ /* Disable the Peripheral */
+ __HAL_DMA2D_DISABLE(hdma2d);
+
+ /* Configure the source, destination address and the data size */
+ DMA2D_SetConfig(hdma2d, pdata, DstAddress, Width, Heigh);
+
+ /* Enable the transfer complete interrupt */
+ __HAL_DMA2D_ENABLE_IT(hdma2d, DMA2D_IT_TC);
+
+ /* Enable the transfer Error interrupt */
+ __HAL_DMA2D_ENABLE_IT(hdma2d, DMA2D_IT_TE);
+
+ /* Enable the Peripheral */
+ __HAL_DMA2D_ENABLE(hdma2d);
+
+ /* Enable the configuration error interrupt */
+ __HAL_DMA2D_ENABLE_IT(hdma2d, DMA2D_IT_CE);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Start the multi-source DMA2D Transfer.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @param SrcAddress1: The source memory Buffer address of the foreground layer.
+ * @param SrcAddress2: The source memory Buffer address of the background layer
+ * or the color value for the A4 or A8 mode.
+ * @param DstAddress: The destination memory Buffer address
+ * @param Width: The width of data to be transferred from source to destination.
+ * @param Heigh: The heigh of data to be transferred from source to destination.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_BlendingStart(DMA2D_HandleTypeDef *hdma2d, uint32_t SrcAddress1, uint32_t SrcAddress2, uint32_t DstAddress, uint32_t Width, uint32_t Heigh)
+{
+ /* Process locked */
+ __HAL_LOCK(hdma2d);
+
+ /* Change DMA2D peripheral state */
+ hdma2d->State = HAL_DMA2D_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DMA2D_LINE(Heigh));
+ assert_param(IS_DMA2D_PIXEL(Width));
+
+ /* Disable the Peripheral */
+ __HAL_DMA2D_DISABLE(hdma2d);
+
+ if((hdma2d->LayerCfg[0].InputColorMode == CM_A4) || (hdma2d->LayerCfg[0].InputColorMode == CM_A8))
+ {
+ hdma2d->Instance->BGCOLR = SrcAddress2;
+ }
+ else
+ {
+ /* Configure DMA2D Stream source2 address */
+ hdma2d->Instance->BGMAR = SrcAddress2;
+ }
+
+ /* Configure the source, destination address and the data size */
+ DMA2D_SetConfig(hdma2d, SrcAddress1, DstAddress, Width, Heigh);
+
+ /* Enable the Peripheral */
+ __HAL_DMA2D_ENABLE(hdma2d);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Start the multi-source DMA2D Transfer with interrupt enabled.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @param SrcAddress1: The source memory Buffer address of the foreground layer.
+ * @param SrcAddress2: The source memory Buffer address of the background layer
+ * or the color value for the A4 or A8 mode.
+ * @param DstAddress: The destination memory Buffer address.
+ * @param Width: The width of data to be transferred from source to destination.
+ * @param Heigh: The heigh of data to be transferred from source to destination.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_BlendingStart_IT(DMA2D_HandleTypeDef *hdma2d, uint32_t SrcAddress1, uint32_t SrcAddress2, uint32_t DstAddress, uint32_t Width, uint32_t Heigh)
+{
+ /* Process locked */
+ __HAL_LOCK(hdma2d);
+
+ /* Change DMA2D peripheral state */
+ hdma2d->State = HAL_DMA2D_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DMA2D_LINE(Heigh));
+ assert_param(IS_DMA2D_PIXEL(Width));
+
+ /* Disable the Peripheral */
+ __HAL_DMA2D_DISABLE(hdma2d);
+
+ if ((hdma2d->LayerCfg[0].InputColorMode == CM_A4) || (hdma2d->LayerCfg[0].InputColorMode == CM_A8))
+ {
+ hdma2d->Instance->BGCOLR = SrcAddress2;
+ }
+ else
+ {
+ /* Configure DMA2D Stream source2 address */
+ hdma2d->Instance->BGMAR = SrcAddress2;
+ }
+
+ /* Configure the source, destination address and the data size */
+ DMA2D_SetConfig(hdma2d, SrcAddress1, DstAddress, Width, Heigh);
+
+ /* Enable the configuration error interrupt */
+ __HAL_DMA2D_ENABLE_IT(hdma2d, DMA2D_IT_CE);
+
+ /* Enable the transfer complete interrupt */
+ __HAL_DMA2D_ENABLE_IT(hdma2d, DMA2D_IT_TC);
+
+ /* Enable the transfer Error interrupt */
+ __HAL_DMA2D_ENABLE_IT(hdma2d, DMA2D_IT_TE);
+
+ /* Enable the Peripheral */
+ __HAL_DMA2D_ENABLE(hdma2d);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Abort the DMA2D Transfer.
+ * @param hdma2d : pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_Abort(DMA2D_HandleTypeDef *hdma2d)
+{
+ uint32_t timeout = 0x00;
+
+ /* Disable the DMA2D */
+ __HAL_DMA2D_DISABLE(hdma2d);
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + HAL_TIMEOUT_DMA2D_ABORT;
+
+ /* Check if the DMA2D is effectively disabled */
+ while((hdma2d->Instance->CR & DMA2D_CR_START) != 0)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Update error code */
+ hdma2d->ErrorCode |= HAL_DMA2D_ERROR_TIMEOUT;
+
+ /* Change the DMA2D state */
+ hdma2d->State= HAL_DMA2D_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ /* Change the DMA2D state*/
+ hdma2d->State = HAL_DMA2D_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Suspend the DMA2D Transfer.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_Suspend(DMA2D_HandleTypeDef *hdma2d)
+{
+ uint32_t timeout = 0x00;
+
+ /* Suspend the DMA2D transfer */
+ hdma2d->Instance->CR |= DMA2D_CR_SUSP;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + HAL_TIMEOUT_DMA2D_SUSPEND;
+
+ /* Check if the DMA2D is effectively suspended */
+ while((hdma2d->Instance->CR & DMA2D_CR_SUSP) != DMA2D_CR_SUSP)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Update error code */
+ hdma2d->ErrorCode |= HAL_DMA2D_ERROR_TIMEOUT;
+
+ /* Change the DMA2D state */
+ hdma2d->State= HAL_DMA2D_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Change the DMA2D state*/
+ hdma2d->State = HAL_DMA2D_STATE_SUSPEND;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Resume the DMA2D Transfer.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_Resume(DMA2D_HandleTypeDef *hdma2d)
+{
+ /* Resume the DMA2D transfer */
+ hdma2d->Instance->CR &= ~DMA2D_CR_SUSP;
+
+ /* Change the DMA2D state*/
+ hdma2d->State = HAL_DMA2D_STATE_BUSY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Polling for transfer complete or CLUT loading.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_PollForTransfer(DMA2D_HandleTypeDef *hdma2d, uint32_t Timeout)
+{
+ uint32_t tmp, tmp1;
+ uint32_t timeout = 0x00;
+
+ /* Polling for DMA2D transfer */
+ if((hdma2d->Instance->CR & DMA2D_CR_START) != 0)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_DMA2D_GET_FLAG(hdma2d, DMA2D_FLAG_TC) == RESET)
+ {
+ tmp = __HAL_DMA2D_GET_FLAG(hdma2d, DMA2D_FLAG_CE);
+ tmp1 = __HAL_DMA2D_GET_FLAG(hdma2d, DMA2D_FLAG_TE);
+
+ if((tmp != RESET) || (tmp1 != RESET))
+ {
+ /* Clear the transfer and configuration error flags */
+ __HAL_DMA2D_CLEAR_FLAG(hdma2d, DMA2D_FLAG_CE);
+ __HAL_DMA2D_CLEAR_FLAG(hdma2d, DMA2D_FLAG_TE);
+
+ /* Change DMA2D state */
+ hdma2d->State= HAL_DMA2D_STATE_ERROR;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ return HAL_ERROR;
+ }
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Process unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ /* Update error code */
+ hdma2d->ErrorCode |= HAL_DMA2D_ERROR_TIMEOUT;
+
+ /* Change the DMA2D state */
+ hdma2d->State= HAL_DMA2D_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ /* Polling for CLUT loading */
+ if((hdma2d->Instance->FGPFCCR & DMA2D_FGPFCCR_START) != 0)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_DMA2D_GET_FLAG(hdma2d, DMA2D_FLAG_CTC) == RESET)
+ {
+ if((__HAL_DMA2D_GET_FLAG(hdma2d, DMA2D_FLAG_CAE) != RESET))
+ {
+ /* Clear the transfer and configuration error flags */
+ __HAL_DMA2D_CLEAR_FLAG(hdma2d, DMA2D_FLAG_CAE);
+
+ /* Change DMA2D state */
+ hdma2d->State= HAL_DMA2D_STATE_ERROR;
+
+ return HAL_ERROR;
+ }
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Update error code */
+ hdma2d->ErrorCode |= HAL_DMA2D_ERROR_TIMEOUT;
+
+ /* Change the DMA2D state */
+ hdma2d->State= HAL_DMA2D_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ /* Clear the transfer complete flag */
+ __HAL_DMA2D_CLEAR_FLAG(hdma2d, DMA2D_FLAG_TC);
+
+ /* Clear the CLUT loading flag */
+ __HAL_DMA2D_CLEAR_FLAG(hdma2d, DMA2D_FLAG_CTC);
+
+ /* Change DMA2D state */
+ hdma2d->State = HAL_DMA2D_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ return HAL_OK;
+}
+/**
+ * @brief Handles DMA2D interrupt request.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @retval HAL status
+ */
+void HAL_DMA2D_IRQHandler(DMA2D_HandleTypeDef *hdma2d)
+{
+ /* Transfer Error Interrupt management ***************************************/
+ if(__HAL_DMA2D_GET_FLAG(hdma2d, DMA2D_FLAG_TE) != RESET)
+ {
+ if(__HAL_DMA2D_GET_IT_SOURCE(hdma2d, DMA2D_IT_TE) != RESET)
+ {
+ /* Disable the transfer Error interrupt */
+ __HAL_DMA2D_DISABLE_IT(hdma2d, DMA2D_IT_TE);
+
+ /* Update error code */
+ hdma2d->ErrorCode |= HAL_DMA2D_ERROR_TE;
+
+ /* Clear the transfer error flag */
+ __HAL_DMA2D_CLEAR_FLAG(hdma2d, DMA2D_FLAG_TE);
+
+ /* Change DMA2D state */
+ hdma2d->State = HAL_DMA2D_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ if(hdma2d->XferErrorCallback != NULL)
+ {
+ /* Transfer error Callback */
+ hdma2d->XferErrorCallback(hdma2d);
+ }
+ }
+ }
+ /* Configuration Error Interrupt management **********************************/
+ if(__HAL_DMA2D_GET_FLAG(hdma2d, DMA2D_FLAG_CE) != RESET)
+ {
+ if(__HAL_DMA2D_GET_IT_SOURCE(hdma2d, DMA2D_IT_CE) != RESET)
+ {
+ /* Disable the Configuration Error interrupt */
+ __HAL_DMA2D_DISABLE_IT(hdma2d, DMA2D_IT_CE);
+
+ /* Clear the Configuration error flag */
+ __HAL_DMA2D_CLEAR_FLAG(hdma2d, DMA2D_FLAG_CE);
+
+ /* Update error code */
+ hdma2d->ErrorCode |= HAL_DMA2D_ERROR_CE;
+
+ /* Change DMA2D state */
+ hdma2d->State = HAL_DMA2D_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ if(hdma2d->XferErrorCallback != NULL)
+ {
+ /* Transfer error Callback */
+ hdma2d->XferErrorCallback(hdma2d);
+ }
+ }
+ }
+ /* Transfer Complete Interrupt management ************************************/
+ if(__HAL_DMA2D_GET_FLAG(hdma2d, DMA2D_FLAG_TC) != RESET)
+ {
+ if(__HAL_DMA2D_GET_IT_SOURCE(hdma2d, DMA2D_IT_TC) != RESET)
+ {
+ /* Disable the transfer complete interrupt */
+ __HAL_DMA2D_DISABLE_IT(hdma2d, DMA2D_IT_TC);
+
+ /* Clear the transfer complete flag */
+ __HAL_DMA2D_CLEAR_FLAG(hdma2d, DMA2D_FLAG_TC);
+
+ /* Update error code */
+ hdma2d->ErrorCode |= HAL_DMA2D_ERROR_NONE;
+
+ /* Change DMA2D state */
+ hdma2d->State = HAL_DMA2D_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ if(hdma2d->XferCpltCallback != NULL)
+ {
+ /* Transfer complete Callback */
+ hdma2d->XferCpltCallback(hdma2d);
+ }
+ }
+ }
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DMA2D_Group3 Peripheral Control functions
+ * @brief Peripheral Control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Configure the DMA2D foreground or/and background parameters.
+ (+) Configure the DMA2D CLUT transfer.
+ (+) Enable DMA2D CLUT.
+ (+) Disable DMA2D CLUT.
+ (+) Configure the line watermark
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Configure the DMA2D Layer according to the specified
+ * parameters in the DMA2D_InitTypeDef and create the associated handle.
+ * @param hdma2d: DMA2D handle
+ * @param LayerIdx: DMA2D Layer index
+ * This parameter can be one of the following values:
+ * 0(background) / 1(foreground)
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_ConfigLayer(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx)
+{
+ DMA2D_LayerCfgTypeDef *pLayerCfg = &hdma2d->LayerCfg[LayerIdx];
+
+ uint32_t tmp = 0;
+
+ /* Process locked */
+ __HAL_LOCK(hdma2d);
+
+ /* Change DMA2D peripheral state */
+ hdma2d->State = HAL_DMA2D_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DMA2D_LAYER(LayerIdx));
+ assert_param(IS_DMA2D_OFFSET(pLayerCfg->InputOffset));
+ if(hdma2d->Init.Mode != DMA2D_R2M)
+ {
+ assert_param(IS_DMA2D_INPUT_COLOR_MODE(pLayerCfg->InputColorMode));
+ if(hdma2d->Init.Mode != DMA2D_M2M)
+ {
+ assert_param(IS_DMA2D_ALPHA_MODE(pLayerCfg->AlphaMode));
+ assert_param(IS_DMA2D_ALPHA_VALUE(pLayerCfg->InputAlpha));
+ }
+ }
+
+ /* Configure the background DMA2D layer */
+ if(LayerIdx == 0)
+ {
+ /* DMA2D BGPFCR register configuration -----------------------------------*/
+ /* Get the BGPFCCR register value */
+ tmp = hdma2d->Instance->BGPFCCR;
+
+ /* Clear Input color mode, alpha value and alpha mode bits */
+ tmp &= (uint32_t)~(DMA2D_BGPFCCR_CM | DMA2D_BGPFCCR_AM | DMA2D_BGPFCCR_ALPHA);
+
+ /* Prepare the value to be wrote to the BGPFCCR register */
+ tmp |= (pLayerCfg->InputColorMode | (pLayerCfg->AlphaMode << 16) | (pLayerCfg->InputAlpha << 24));
+
+ /* Write to DMA2D BGPFCCR register */
+ hdma2d->Instance->BGPFCCR = tmp;
+
+ /* DMA2D BGOR register configuration -------------------------------------*/
+ /* Get the BGOR register value */
+ tmp = hdma2d->Instance->BGOR;
+
+ /* Clear colors bits */
+ tmp &= (uint32_t)~DMA2D_BGOR_LO;
+
+ /* Prepare the value to be wrote to the BGOR register */
+ tmp |= pLayerCfg->InputOffset;
+
+ /* Write to DMA2D BGOR register */
+ hdma2d->Instance->BGOR = tmp;
+ }
+ /* Configure the foreground DMA2D layer */
+ else
+ {
+ /* DMA2D FGPFCR register configuration -----------------------------------*/
+ /* Get the FGPFCCR register value */
+ tmp = hdma2d->Instance->FGPFCCR;
+
+ /* Clear Input color mode, alpha value and alpha mode bits */
+ tmp &= (uint32_t)~(DMA2D_FGPFCCR_CM | DMA2D_FGPFCCR_AM | DMA2D_FGPFCCR_ALPHA);
+
+ /* Prepare the value to be wrote to the FGPFCCR register */
+ tmp |= (pLayerCfg->InputColorMode | (pLayerCfg->AlphaMode << 16) | (pLayerCfg->InputAlpha << 24));
+
+ /* Write to DMA2D FGPFCCR register */
+ hdma2d->Instance->FGPFCCR = tmp;
+
+ /* DMA2D FGOR register configuration -------------------------------------*/
+ /* Get the FGOR register value */
+ tmp = hdma2d->Instance->FGOR;
+
+ /* Clear colors bits */
+ tmp &= (uint32_t)~DMA2D_FGOR_LO;
+
+ /* Prepare the value to be wrote to the FGOR register */
+ tmp |= pLayerCfg->InputOffset;
+
+ /* Write to DMA2D FGOR register */
+ hdma2d->Instance->FGOR = tmp;
+ }
+ /* Initialize the DMA2D state*/
+ hdma2d->State = HAL_DMA2D_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configure the DMA2D CLUT Transfer.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @param CLUTCfg: pointer to a DMA2D_CLUTCfgTypeDef structure that contains
+ * the configuration information for the color look up table.
+ * @param LayerIdx: DMA2D Layer index
+ * This parameter can be one of the following values:
+ * 0(background) / 1(foreground)
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_ConfigCLUT(DMA2D_HandleTypeDef *hdma2d, DMA2D_CLUTCfgTypeDef CLUTCfg, uint32_t LayerIdx)
+{
+ uint32_t tmp = 0, tmp1 = 0;
+
+ /* Check the parameters */
+ assert_param(IS_DMA2D_LAYER(LayerIdx));
+ assert_param(IS_DMA2D_CLUT_CM(CLUTCfg.CLUTColorMode));
+ assert_param(IS_DMA2D_CLUT_SIZE(CLUTCfg.Size));
+
+ /* Configure the CLUT of the background DMA2D layer */
+ if(LayerIdx == 0)
+ {
+ /* Get the BGCMAR register value */
+ tmp = hdma2d->Instance->BGCMAR;
+
+ /* Clear CLUT address bits */
+ tmp &= (uint32_t)~DMA2D_BGCMAR_MA;
+
+ /* Prepare the value to be wrote to the BGCMAR register */
+ tmp |= (uint32_t)CLUTCfg.pCLUT;
+
+ /* Write to DMA2D BGCMAR register */
+ hdma2d->Instance->BGCMAR = tmp;
+
+ /* Get the BGPFCCR register value */
+ tmp = hdma2d->Instance->BGPFCCR;
+
+ /* Clear CLUT size and CLUT address bits */
+ tmp &= (uint32_t)~(DMA2D_BGPFCCR_CS | DMA2D_BGPFCCR_CCM);
+
+ /* Get the CLUT size */
+ tmp1 = CLUTCfg.Size << 16;
+
+ /* Prepare the value to be wrote to the BGPFCCR register */
+ tmp |= (CLUTCfg.CLUTColorMode | tmp1);
+
+ /* Write to DMA2D BGPFCCR register */
+ hdma2d->Instance->BGPFCCR = tmp;
+ }
+ /* Configure the CLUT of the foreground DMA2D layer */
+ else
+ {
+ /* Get the FGCMAR register value */
+ tmp = hdma2d->Instance->FGCMAR;
+
+ /* Clear CLUT address bits */
+ tmp &= (uint32_t)~DMA2D_FGCMAR_MA;
+
+ /* Prepare the value to be wrote to the FGCMAR register */
+ tmp |= (uint32_t)CLUTCfg.pCLUT;
+
+ /* Write to DMA2D FGCMAR register */
+ hdma2d->Instance->FGCMAR = tmp;
+
+ /* Get the FGPFCCR register value */
+ tmp = hdma2d->Instance->FGPFCCR;
+
+ /* Clear CLUT size and CLUT address bits */
+ tmp &= (uint32_t)~(DMA2D_FGPFCCR_CS | DMA2D_FGPFCCR_CCM);
+
+ /* Get the CLUT size */
+ tmp1 = CLUTCfg.Size << 8;
+
+ /* Prepare the value to be wrote to the FGPFCCR register */
+ tmp |= (CLUTCfg.CLUTColorMode | tmp1);
+
+ /* Write to DMA2D FGPFCCR register */
+ hdma2d->Instance->FGPFCCR = tmp;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enable the DMA2D CLUT Transfer.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @param LayerIdx: DMA2D Layer index
+ * This parameter can be one of the following values:
+ * 0(background) / 1(foreground)
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_EnableCLUT(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx)
+{
+ /* Check the parameters */
+ assert_param(IS_DMA2D_LAYER(LayerIdx));
+
+ if(LayerIdx == 0)
+ {
+ /* Enable the CLUT loading for the background */
+ hdma2d->Instance->BGPFCCR |= DMA2D_BGPFCCR_START;
+ }
+ else
+ {
+ /* Enable the CLUT loading for the foreground */
+ hdma2d->Instance->FGPFCCR |= DMA2D_FGPFCCR_START;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disable the DMA2D CLUT Transfer.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @param LayerIdx: DMA2D Layer index
+ * This parameter can be one of the following values:
+ * 0(background) / 1(foreground)
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA2D_DisableCLUT(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx)
+{
+ /* Check the parameters */
+ assert_param(IS_DMA2D_LAYER(LayerIdx));
+
+ if(LayerIdx == 0)
+ {
+ /* Disable the CLUT loading for the background */
+ hdma2d->Instance->BGPFCCR &= ~DMA2D_BGPFCCR_START;
+ }
+ else
+ {
+ /* Disable the CLUT loading for the foreground */
+ hdma2d->Instance->FGPFCCR &= ~DMA2D_FGPFCCR_START;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Define the configuration of the line watermark .
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @param Line: Line Watermark configuration.
+ * @retval None
+ */
+
+HAL_StatusTypeDef HAL_DMA2D_ProgramLineEvent(DMA2D_HandleTypeDef *hdma2d, uint32_t Line)
+{
+ /* Process locked */
+ __HAL_LOCK(hdma2d);
+
+ /* Change DMA2D peripheral state */
+ hdma2d->State = HAL_DMA2D_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_DMA2D_LineWatermark(Line));
+
+ /* Sets the Line watermark configuration */
+ DMA2D->LWR = (uint32_t)Line;
+
+ /* Initialize the DMA2D state*/
+ hdma2d->State = HAL_DMA2D_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hdma2d);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup DMA2D_Group4 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State and Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Check the DMA2D state
+ (+) Get error code
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the DMA2D state
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the DMA2D.
+ * @retval HAL state
+ */
+HAL_DMA2D_StateTypeDef HAL_DMA2D_GetState(DMA2D_HandleTypeDef *hdma2d)
+{
+ return hdma2d->State;
+}
+
+/**
+ * @brief Return the DMA2D error code
+ * @param hdma2d : pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for DMA2D.
+ * @retval DMA2D Error Code
+ */
+uint32_t HAL_DMA2D_GetError(DMA2D_HandleTypeDef *hdma2d)
+{
+ return hdma2d->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+
+/**
+ * @brief Set the DMA2D Transfer parameter.
+ * @param hdma2d: pointer to a DMA2D_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA2D.
+ * @param pdata: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param Width: The width of data to be transferred from source to destination.
+ * @param Heigh: The heigh of data to be transferred from source to destination.
+ * @retval HAL status
+ */
+static void DMA2D_SetConfig(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Heigh)
+{
+ uint32_t tmp = 0;
+ uint32_t tmp1 = 0;
+ uint32_t tmp2 = 0;
+ uint32_t tmp3 = 0;
+ uint32_t tmp4 = 0;
+
+ tmp = Width << 16;
+
+ /* Configure DMA2D data size */
+ hdma2d->Instance->NLR = (Heigh | tmp);
+
+ /* Configure DMA2D destination address */
+ hdma2d->Instance->OMAR = DstAddress;
+
+ /* Register to memory DMA2D mode selected */
+ if (hdma2d->Init.Mode == DMA2D_R2M)
+ {
+ tmp1 = pdata & DMA2D_OCOLR_ALPHA_1;
+ tmp2 = pdata & DMA2D_OCOLR_RED_1;
+ tmp3 = pdata & DMA2D_OCOLR_GREEN_1;
+ tmp4 = pdata & DMA2D_OCOLR_BLUE_1;
+
+ /* Prepare the value to be wrote to the OCOLR register according to the color mode */
+ if (hdma2d->Init.ColorMode == DMA2D_ARGB8888)
+ {
+ tmp = (tmp3 | tmp2 | tmp1| tmp4);
+ }
+ else if (hdma2d->Init.ColorMode == DMA2D_RGB888)
+ {
+ tmp = (tmp3 | tmp2 | tmp4);
+ }
+ else if (hdma2d->Init.ColorMode == DMA2D_RGB565)
+ {
+ tmp2 = (tmp2 >> 19);
+ tmp3 = (tmp3 >> 10);
+ tmp4 = (tmp4 >> 3 );
+ tmp = ((tmp3 << 5) | (tmp2 << 11) | tmp4);
+ }
+ else if (hdma2d->Init.ColorMode == DMA2D_ARGB1555)
+ {
+ tmp1 = (tmp1 >> 31);
+ tmp2 = (tmp2 >> 19);
+ tmp3 = (tmp3 >> 11);
+ tmp4 = (tmp4 >> 3 );
+ tmp = ((tmp3 << 5) | (tmp2 << 10) | (tmp1 << 15) | tmp4);
+ }
+ else /* DMA2D_CMode = DMA2D_ARGB4444 */
+ {
+ tmp1 = (tmp1 >> 28);
+ tmp2 = (tmp2 >> 20);
+ tmp3 = (tmp3 >> 12);
+ tmp4 = (tmp4 >> 4 );
+ tmp = ((tmp3 << 4) | (tmp2 << 8) | (tmp1 << 12) | tmp4);
+ }
+ /* Write to DMA2D OCOLR register */
+ hdma2d->Instance->OCOLR = tmp;
+ }
+ else if ((hdma2d->LayerCfg[1].InputColorMode == CM_A4) || (hdma2d->LayerCfg[1].InputColorMode == CM_A8))
+ {
+ hdma2d->Instance->FGCOLR = pdata;
+ }
+ else /* M2M, M2M_PFC or M2M_Blending DMA2D Mode */
+ {
+ /* Configure DMA2D source address */
+ hdma2d->Instance->FGMAR = pdata;
+ }
+}
+
+/**
+ * @}
+ */
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_DMA2D_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma_ex.c
new file mode 100644
index 0000000..91a7751
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma_ex.c
@@ -0,0 +1,294 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_dma_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief DMA Extension HAL module driver
+ * This file provides firmware functions to manage the following
+ * functionalities of the DMA Extension peripheral:
+ * + Extended features functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The DMA Extension HAL driver can be used as follows:
+ (#) Start a multi buffer transfer using the HAL_DMA_MultiBufferStart() function
+ for polling mode or HAL_DMA_MultiBufferStart_IT() for interrupt mode.
+
+ -@- In Memory-to-Memory transfer mode, Multi (Double) Buffer mode is not allowed.
+ -@- When Multi (Double) Buffer mode is enabled the, transfer is circular by default.
+ -@- In Multi (Double) buffer mode, it is possible to update the base address for
+ the AHB memory port on-the-fly (DMA_SxM0AR or DMA_SxM1AR) when the stream is enabled.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup DMAEx
+ * @brief DMA Extended HAL module driver
+ * @{
+ */
+
+#ifdef HAL_DMA_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void DMA_MultiBufferSetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup DMAEx_Private_Functions
+ * @{
+ */
+
+
+/** @defgroup DMAEx_Group1 Extended features functions
+ * @brief Extended features functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Extended features functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Configure the source, destination address and data length and
+ Start MultiBuffer DMA transfer
+ (+) Configure the source, destination address and data length and
+ Start MultiBuffer DMA transfer with interrupt
+ (+) Change on the fly the memory0 or memory1 address.
+
+@endverbatim
+ * @{
+ */
+
+
+/**
+ * @brief Starts the multi_buffer DMA Transfer.
+ * @param hdma : pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @param SrcAddress: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param SecondMemAddress: The second memory Buffer address in case of multi buffer Transfer
+ * @param DataLength: The length of data to be transferred from source to destination
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMAEx_MultiBufferStart(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength)
+{
+ /* Process Locked */
+ __HAL_LOCK(hdma);
+
+ /* Current memory buffer used is Memory 0 */
+ if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
+ {
+ hdma->State = HAL_DMA_STATE_BUSY_MEM0;
+ }
+ /* Current memory buffer used is Memory 1 */
+ else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
+ {
+ hdma->State = HAL_DMA_STATE_BUSY_MEM1;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_DMA_BUFFER_SIZE(DataLength));
+
+ /* Disable the peripheral */
+ __HAL_DMA_DISABLE(hdma);
+
+ /* Enable the double buffer mode */
+ hdma->Instance->CR |= (uint32_t)DMA_SxCR_DBM;
+
+ /* Configure DMA Stream destination address */
+ hdma->Instance->M1AR = SecondMemAddress;
+
+ /* Configure the source, destination address and the data length */
+ DMA_MultiBufferSetConfig(hdma, SrcAddress, DstAddress, DataLength);
+
+ /* Enable the peripheral */
+ __HAL_DMA_ENABLE(hdma);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the multi_buffer DMA Transfer with interrupt enabled.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @param SrcAddress: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param SecondMemAddress: The second memory Buffer address in case of multi buffer Transfer
+ * @param DataLength: The length of data to be transferred from source to destination
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMAEx_MultiBufferStart_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength)
+{
+ /* Process Locked */
+ __HAL_LOCK(hdma);
+
+ /* Current memory buffer used is Memory 0 */
+ if((hdma->Instance->CR & DMA_SxCR_CT) == 0)
+ {
+ hdma->State = HAL_DMA_STATE_BUSY_MEM0;
+ }
+ /* Current memory buffer used is Memory 1 */
+ else if((hdma->Instance->CR & DMA_SxCR_CT) != 0)
+ {
+ hdma->State = HAL_DMA_STATE_BUSY_MEM1;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_DMA_BUFFER_SIZE(DataLength));
+
+ /* Disable the peripheral */
+ __HAL_DMA_DISABLE(hdma);
+
+ /* Enable the Double buffer mode */
+ hdma->Instance->CR |= (uint32_t)DMA_SxCR_DBM;
+
+ /* Configure DMA Stream destination address */
+ hdma->Instance->M1AR = SecondMemAddress;
+
+ /* Configure the source, destination address and the data length */
+ DMA_MultiBufferSetConfig(hdma, SrcAddress, DstAddress, DataLength);
+
+ /* Enable the transfer complete interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TC);
+
+ /* Enable the Half transfer interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_HT);
+
+ /* Enable the transfer Error interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TE);
+
+ /* Enable the fifo Error interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_FE);
+
+ /* Enable the direct mode Error interrupt */
+ __HAL_DMA_ENABLE_IT(hdma, DMA_IT_DME);
+
+ /* Enable the peripheral */
+ __HAL_DMA_ENABLE(hdma);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Change the memory0 or memory1 address on the fly.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @param Address: The new address
+ * @param memory: the memory to be changed, This parameter can be one of
+ * the following values:
+ * @arg MEMORY0
+ * @arg MEMORY1
+ * @note The MEMORY0 address can be changed only when the current transfer use
+ * MEMORY1 and the MEMORY1 address can be changed only when the current
+ * transfer use MEMORY0.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMAEx_ChangeMemory(DMA_HandleTypeDef *hdma, uint32_t Address, HAL_DMA_MemoryTypeDef memory)
+{
+ if(memory == MEMORY0)
+ {
+ /* change the memory0 address */
+ hdma->Instance->M0AR = Address;
+ }
+ else
+ {
+ /* change the memory1 address */
+ hdma->Instance->M1AR = Address;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Set the DMA Transfer parameter.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Stream.
+ * @param SrcAddress: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param DataLength: The length of data to be transferred from source to destination
+ * @retval HAL status
+ */
+static void DMA_MultiBufferSetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
+{
+ /* Configure DMA Stream data length */
+ hdma->Instance->NDTR = DataLength;
+
+ /* Peripheral to Memory */
+ if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH)
+ {
+ /* Configure DMA Stream destination address */
+ hdma->Instance->PAR = DstAddress;
+
+ /* Configure DMA Stream source address */
+ hdma->Instance->M0AR = SrcAddress;
+ }
+ /* Memory to Peripheral */
+ else
+ {
+ /* Configure DMA Stream source address */
+ hdma->Instance->PAR = SrcAddress;
+
+ /* Configure DMA Stream destination address */
+ hdma->Instance->M0AR = DstAddress;
+ }
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_DMA_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_eth.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_eth.c
new file mode 100644
index 0000000..eaf2b15
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_eth.c
@@ -0,0 +1,1933 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_eth.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief ETH HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Ethernet (ETH) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State and Errors functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#)Declare a ETH_HandleTypeDef handle structure, for example:
+ ETH_HandleTypeDef heth;
+
+ (#)Fill parameters of Init structure in heth handle
+
+ (#)Call HAL_ETH_Init() API to initialize the Ethernet peripheral (MAC, DMA, ...)
+
+ (#)Initialize the ETH low level resources through the HAL_ETH_MspInit() API:
+ (##) Enable the Ethernet interface clock using
+ (+++) __ETHMAC_CLK_ENABLE();
+ (+++) __ETHMACTX_CLK_ENABLE();
+ (+++) __ETHMACRX_CLK_ENABLE();
+
+ (##) Initialize the related GPIO clocks
+ (##) Configure Ethernet pin-out
+ (##) Configure Ethernet NVIC interrupt (IT mode)
+
+ (#)Initialize Ethernet DMA Descriptors in chain mode and point to allocated buffers:
+ (##) HAL_ETH_DMATxDescListInit(); for Transmission process
+ (##) HAL_ETH_DMARxDescListInit(); for Reception process
+
+ (#)Enable MAC and DMA transmission and reception:
+ (##) HAL_ETH_Start();
+
+ (#)Prepare ETH DMA TX Descriptors and give the hand to ETH DMA to transfer
+ the frame to MAC TX FIFO:
+ (##) HAL_ETH_TransmitFrame();
+
+ (#)Poll for a received frame in ETH RX DMA Descriptors and get received
+ frame parameters
+ (##) HAL_ETH_GetReceivedFrame(); (should be called into an infinite loop)
+
+ (#) Get a received frame when an ETH RX interrupt occurs:
+ (##) HAL_ETH_GetReceivedFrame_IT(); (called in IT mode only)
+
+ (#) Communicate with external PHY device:
+ (##) Read a specific register from the PHY
+ HAL_ETH_ReadPHYRegister();
+ (##) Write data to a specific RHY register:
+ HAL_ETH_WritePHYRegister();
+
+ (#) Configure the Ethernet MAC after ETH peripheral initialization
+ HAL_ETH_ConfigMAC(); all MAC parameters should be filled.
+
+ (#) Configure the Ethernet DMA after ETH peripheral initialization
+ HAL_ETH_ConfigDMA(); all DMA parameters should be filled.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup ETH
+ * @brief ETH HAL module driver
+ * @{
+ */
+
+#ifdef HAL_ETH_MODULE_ENABLED
+
+#if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err);
+static void ETH_MACAddressConfig(ETH_HandleTypeDef *heth, uint32_t MacAddr, uint8_t *Addr);
+static void ETH_MACReceptionEnable(ETH_HandleTypeDef *heth);
+static void ETH_MACReceptionDisable(ETH_HandleTypeDef *heth);
+static void ETH_MACTransmissionEnable(ETH_HandleTypeDef *heth);
+static void ETH_MACTransmissionDisable(ETH_HandleTypeDef *heth);
+static void ETH_DMATransmissionEnable(ETH_HandleTypeDef *heth);
+static void ETH_DMATransmissionDisable(ETH_HandleTypeDef *heth);
+static void ETH_DMAReceptionEnable(ETH_HandleTypeDef *heth);
+static void ETH_DMAReceptionDisable(ETH_HandleTypeDef *heth);
+static void ETH_FlushTransmitFIFO(ETH_HandleTypeDef *heth);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup ETH_Private_Functions
+ * @{
+ */
+
+/** @defgroup ETH_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+ @verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize and configure the Ethernet peripheral
+ (+) De-initialize the Ethernet peripheral
+
+ @endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the Ethernet MAC and DMA according to default
+ * parameters.
+ * @param heth: ETH handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth)
+{
+ uint32_t tmpreg = 0, phyreg = 0;
+ uint32_t hclk = 60000000;
+ uint32_t timeout = 0;
+ uint32_t err = ETH_SUCCESS;
+
+ /* Check the ETH peripheral state */
+ if(heth == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check parameters */
+ assert_param(IS_ETH_AUTONEGOTIATION(heth->Init.AutoNegotiation));
+ assert_param(IS_ETH_RX_MODE(heth->Init.RxMode));
+ assert_param(IS_ETH_CHECKSUM_MODE(heth->Init.ChecksumMode));
+ assert_param(IS_ETH_MEDIA_INTERFACE(heth->Init.MediaInterface));
+
+ if(heth->State == HAL_ETH_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC. */
+ HAL_ETH_MspInit(heth);
+ }
+
+ /* Enable SYSCFG Clock */
+ __SYSCFG_CLK_ENABLE();
+
+ /* Select MII or RMII Mode*/
+ SYSCFG->PMC &= ~(SYSCFG_PMC_MII_RMII_SEL);
+ SYSCFG->PMC |= (uint32_t)heth->Init.MediaInterface;
+
+ /* Ethernet Software reset */
+ /* Set the SWR bit: resets all MAC subsystem internal registers and logic */
+ /* After reset all the registers holds their respective reset values */
+ (heth->Instance)->DMABMR |= ETH_DMABMR_SR;
+
+ /* Wait for software reset */
+ while (((heth->Instance)->DMABMR & ETH_DMABMR_SR) != (uint32_t)RESET)
+ {
+ }
+
+ /*-------------------------------- MAC Initialization ----------------------*/
+ /* Get the ETHERNET MACMIIAR value */
+ tmpreg = (heth->Instance)->MACMIIAR;
+ /* Clear CSR Clock Range CR[2:0] bits */
+ tmpreg &= MACMIIAR_CR_MASK;
+
+ /* Get hclk frequency value */
+ hclk = HAL_RCC_GetHCLKFreq();
+
+ /* Set CR bits depending on hclk value */
+ if((hclk >= 20000000)&&(hclk < 35000000))
+ {
+ /* CSR Clock Range between 20-35 MHz */
+ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div16;
+ }
+ else if((hclk >= 35000000)&&(hclk < 60000000))
+ {
+ /* CSR Clock Range between 35-60 MHz */
+ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div26;
+ }
+ else if((hclk >= 60000000)&&(hclk < 100000000))
+ {
+ /* CSR Clock Range between 60-100 MHz */
+ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div42;
+ }
+ else if((hclk >= 100000000)&&(hclk < 150000000))
+ {
+ /* CSR Clock Range between 100-150 MHz */
+ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div62;
+ }
+ else /* ((hclk >= 150000000)&&(hclk <= 168000000)) */
+ {
+ /* CSR Clock Range between 150-168 MHz */
+ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div102;
+ }
+
+ /* Write to ETHERNET MAC MIIAR: Configure the ETHERNET CSR Clock Range */
+ (heth->Instance)->MACMIIAR = (uint32_t)tmpreg;
+
+ /*-------------------- PHY initialization and configuration ----------------*/
+ /* Put the PHY in reset mode */
+ if((HAL_ETH_WritePHYRegister(heth, PHY_BCR, PHY_RESET)) != HAL_OK)
+ {
+ /* In case of write timeout */
+ err = ETH_ERROR;
+
+ /* Config MAC and DMA */
+ ETH_MACDMAConfig(heth, err);
+
+ /* Set the ETH peripheral state to READY */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Return HAL_ERROR */
+ return HAL_ERROR;
+ }
+
+ /* Delay to assure PHY reset */
+ HAL_Delay(PHY_RESET_DELAY);
+
+ if((heth->Init).AutoNegotiation != ETH_AUTONEGOTIATION_DISABLE)
+ {
+ /* We wait for linked status */
+ do
+ {
+ timeout++;
+ HAL_ETH_ReadPHYRegister(heth, PHY_BSR, &phyreg);
+ } while (((phyreg & PHY_LINKED_STATUS) != PHY_LINKED_STATUS) && (timeout < PHY_READ_TO));
+
+ if(timeout == PHY_READ_TO)
+ {
+ /* In case of write timeout */
+ err = ETH_ERROR;
+
+ /* Config MAC and DMA */
+ ETH_MACDMAConfig(heth, err);
+
+ /* Set the ETH peripheral state to READY */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Return HAL_ERROR */
+ return HAL_ERROR;
+ }
+
+ /* Reset Timeout counter */
+ timeout = 0;
+
+ /* Enable Auto-Negotiation */
+ if((HAL_ETH_WritePHYRegister(heth, PHY_BCR, PHY_AUTONEGOTIATION)) != HAL_OK)
+ {
+ /* In case of write timeout */
+ err = ETH_ERROR;
+
+ /* Config MAC and DMA */
+ ETH_MACDMAConfig(heth, err);
+
+ /* Set the ETH peripheral state to READY */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Return HAL_ERROR */
+ return HAL_ERROR;
+ }
+
+ /* Wait until the auto-negotiation will be completed */
+ do
+ {
+ timeout++;
+ HAL_ETH_ReadPHYRegister(heth, PHY_BSR, &phyreg);
+ } while (((phyreg & PHY_AUTONEGO_COMPLETE) != PHY_AUTONEGO_COMPLETE) && (timeout < PHY_READ_TO));
+
+ if(timeout == PHY_READ_TO)
+ {
+ /* In case of timeout */
+ err = ETH_ERROR;
+
+ /* Config MAC and DMA */
+ ETH_MACDMAConfig(heth, err);
+
+ /* Set the ETH peripheral state to READY */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Return HAL_ERROR */
+ return HAL_ERROR;
+ }
+
+ /* Reset Timeout counter */
+ timeout = 0;
+
+ /* Read the result of the auto-negotiation */
+ HAL_ETH_ReadPHYRegister(heth, PHY_SR, &phyreg);
+
+ /* Configure the MAC with the Duplex Mode fixed by the auto-negotiation process */
+ if((phyreg & PHY_DUPLEX_STATUS) != (uint32_t)RESET)
+ {
+ /* Set Ethernet duplex mode to Full-duplex following the auto-negotiation */
+ (heth->Init).DuplexMode = ETH_MODE_FULLDUPLEX;
+ }
+ else
+ {
+ /* Set Ethernet duplex mode to Half-duplex following the auto-negotiation */
+ (heth->Init).DuplexMode = ETH_MODE_HALFDUPLEX;
+ }
+ /* Configure the MAC with the speed fixed by the auto-negotiation process */
+ if((phyreg & PHY_SPEED_STATUS) == PHY_SPEED_STATUS)
+ {
+ /* Set Ethernet speed to 10M following the auto-negotiation */
+ (heth->Init).Speed = ETH_SPEED_10M;
+ }
+ else
+ {
+ /* Set Ethernet speed to 100M following the auto-negotiation */
+ (heth->Init).Speed = ETH_SPEED_100M;
+ }
+ }
+ else /* AutoNegotiation Disable */
+ {
+ /* Check parameters */
+ assert_param(IS_ETH_SPEED(heth->Init.Speed));
+ assert_param(IS_ETH_DUPLEX_MODE(heth->Init.DuplexMode));
+
+ /* Set MAC Speed and Duplex Mode */
+ if(HAL_ETH_WritePHYRegister(heth, PHY_BCR, ((uint16_t)((heth->Init).DuplexMode >> 3) |
+ (uint16_t)((heth->Init).Speed >> 1))) != HAL_OK)
+ {
+ /* In case of write timeout */
+ err = ETH_ERROR;
+
+ /* Config MAC and DMA */
+ ETH_MACDMAConfig(heth, err);
+
+ /* Set the ETH peripheral state to READY */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Return HAL_ERROR */
+ return HAL_ERROR;
+ }
+
+ /* Delay to assure PHY configuration */
+ HAL_Delay(PHY_CONFIG_DELAY);
+ }
+
+ /* Config MAC and DMA */
+ ETH_MACDMAConfig(heth, err);
+
+ /* Set ETH HAL State to Ready */
+ heth->State= HAL_ETH_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief De-Initializes the ETH peripheral.
+ * @param heth: ETH handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_DeInit(ETH_HandleTypeDef *heth)
+{
+ /* Set the ETH peripheral state to BUSY */
+ heth->State = HAL_ETH_STATE_BUSY;
+
+ /* De-Init the low level hardware : GPIO, CLOCK, NVIC. */
+ HAL_ETH_MspDeInit(heth);
+
+ /* Set ETH HAL state to Disabled */
+ heth->State= HAL_ETH_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the DMA Tx descriptors in chain mode.
+ * @param heth: ETH handle
+ * @param DMATxDescTab: Pointer to the first Tx desc list
+ * @param TxBuff: Pointer to the first TxBuffer list
+ * @param TxBuffCount: Number of the used Tx desc in the list
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_DMATxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMATxDescTab, uint8_t *TxBuff, uint32_t TxBuffCount)
+{
+ uint32_t i = 0;
+ ETH_DMADescTypeDef *dmatxdesc;
+
+ /* Process Locked */
+ __HAL_LOCK(heth);
+
+ /* Set the ETH peripheral state to BUSY */
+ heth->State = HAL_ETH_STATE_BUSY;
+
+ /* Set the DMATxDescToSet pointer with the first one of the DMATxDescTab list */
+ heth->TxDesc = DMATxDescTab;
+
+ /* Fill each DMATxDesc descriptor with the right values */
+ for(i=0; i < TxBuffCount; i++)
+ {
+ /* Get the pointer on the ith member of the Tx Desc list */
+ dmatxdesc = DMATxDescTab + i;
+
+ /* Set Second Address Chained bit */
+ dmatxdesc->Status = ETH_DMATXDESC_TCH;
+
+ /* Set Buffer1 address pointer */
+ dmatxdesc->Buffer1Addr = (uint32_t)(&TxBuff[i*ETH_TX_BUF_SIZE]);
+
+ if ((heth->Init).ChecksumMode == ETH_CHECKSUM_BY_HARDWARE)
+ {
+ /* Set the DMA Tx descriptors checksum insertion */
+ dmatxdesc->Status |= ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL;
+ }
+
+ /* Initialize the next descriptor with the Next Descriptor Polling Enable */
+ if(i < (TxBuffCount-1))
+ {
+ /* Set next descriptor address register with next descriptor base address */
+ dmatxdesc->Buffer2NextDescAddr = (uint32_t)(DMATxDescTab+i+1);
+ }
+ else
+ {
+ /* For last descriptor, set next descriptor address register equal to the first descriptor base address */
+ dmatxdesc->Buffer2NextDescAddr = (uint32_t) DMATxDescTab;
+ }
+ }
+
+ /* Set Transmit Descriptor List Address Register */
+ (heth->Instance)->DMATDLAR = (uint32_t) DMATxDescTab;
+
+ /* Set ETH HAL State to Ready */
+ heth->State= HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the DMA Rx descriptors in chain mode.
+ * @param heth: ETH handle
+ * @param DMARxDescTab: Pointer to the first Rx desc list
+ * @param RxBuff: Pointer to the first RxBuffer list
+ * @param RxBuffCount: Number of the used Rx desc in the list
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_DMARxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMARxDescTab, uint8_t *RxBuff, uint32_t RxBuffCount)
+{
+ uint32_t i = 0;
+ ETH_DMADescTypeDef *DMARxDesc;
+
+ /* Process Locked */
+ __HAL_LOCK(heth);
+
+ /* Set the ETH peripheral state to BUSY */
+ heth->State = HAL_ETH_STATE_BUSY;
+
+ /* Set the Ethernet RxDesc pointer with the first one of the DMARxDescTab list */
+ heth->RxDesc = DMARxDescTab;
+
+ /* Fill each DMARxDesc descriptor with the right values */
+ for(i=0; i < RxBuffCount; i++)
+ {
+ /* Get the pointer on the ith member of the Rx Desc list */
+ DMARxDesc = DMARxDescTab+i;
+
+ /* Set Own bit of the Rx descriptor Status */
+ DMARxDesc->Status = ETH_DMARXDESC_OWN;
+
+ /* Set Buffer1 size and Second Address Chained bit */
+ DMARxDesc->ControlBufferSize = ETH_DMARXDESC_RCH | ETH_RX_BUF_SIZE;
+
+ /* Set Buffer1 address pointer */
+ DMARxDesc->Buffer1Addr = (uint32_t)(&RxBuff[i*ETH_RX_BUF_SIZE]);
+
+ if((heth->Init).RxMode == ETH_RXINTERRUPT_MODE)
+ {
+ /* Enable Ethernet DMA Rx Descriptor interrupt */
+ DMARxDesc->ControlBufferSize &= ~ETH_DMARXDESC_DIC;
+ }
+
+ /* Initialize the next descriptor with the Next Descriptor Polling Enable */
+ if(i < (RxBuffCount-1))
+ {
+ /* Set next descriptor address register with next descriptor base address */
+ DMARxDesc->Buffer2NextDescAddr = (uint32_t)(DMARxDescTab+i+1);
+ }
+ else
+ {
+ /* For last descriptor, set next descriptor address register equal to the first descriptor base address */
+ DMARxDesc->Buffer2NextDescAddr = (uint32_t)(DMARxDescTab);
+ }
+ }
+
+ /* Set Receive Descriptor List Address Register */
+ (heth->Instance)->DMARDLAR = (uint32_t) DMARxDescTab;
+
+ /* Set ETH HAL State to Ready */
+ heth->State= HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the ETH MSP.
+ * @param heth: ETH handle
+ * @retval None
+ */
+__weak void HAL_ETH_MspInit(ETH_HandleTypeDef *heth)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ETH_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes ETH MSP.
+ * @param heth: ETH handle
+ * @retval None
+ */
+__weak void HAL_ETH_MspDeInit(ETH_HandleTypeDef *heth)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ETH_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup ETH_Group2 IO operation functions
+ * @brief Data transfers functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### IO operation functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to:
+ (+) Transmit a frame
+ HAL_ETH_TransmitFrame();
+ (+) Receive a frame
+ HAL_ETH_GetReceivedFrame();
+ HAL_ETH_GetReceivedFrame_IT();
+ (+) Read from an External PHY register
+ HAL_ETH_ReadPHYRegister();
+ (+) Writo to an External PHY register
+ HAL_ETH_WritePHYRegister();
+
+ @endverbatim
+
+ * @{
+ */
+
+/**
+ * @brief Sends an Ethernet frame.
+ * @param heth: ETH handle
+ * @param FrameLength: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameLength)
+{
+ uint32_t bufcount = 0, size = 0, i = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(heth);
+
+ /* Set the ETH peripheral state to BUSY */
+ heth->State = HAL_ETH_STATE_BUSY;
+
+ if (FrameLength == 0)
+ {
+ /* Set ETH HAL state to READY */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ return HAL_ERROR;
+ }
+
+ /* Check if the descriptor is owned by the ETHERNET DMA (when set) or CPU (when reset) */
+ if(((heth->TxDesc)->Status & ETH_DMATXDESC_OWN) != (uint32_t)RESET)
+ {
+ /* OWN bit set */
+ heth->State = HAL_ETH_STATE_BUSY_TX;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ return HAL_ERROR;
+ }
+
+ /* Get the number of needed Tx buffers for the current frame */
+ if (FrameLength > ETH_TX_BUF_SIZE)
+ {
+ bufcount = FrameLength/ETH_TX_BUF_SIZE;
+ if (FrameLength % ETH_TX_BUF_SIZE)
+ {
+ bufcount++;
+ }
+ }
+ else
+ {
+ bufcount = 1;
+ }
+ if (bufcount == 1)
+ {
+ /* Set LAST and FIRST segment */
+ heth->TxDesc->Status |=ETH_DMATXDESC_FS|ETH_DMATXDESC_LS;
+ /* Set frame size */
+ heth->TxDesc->ControlBufferSize = (FrameLength & ETH_DMATXDESC_TBS1);
+ /* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */
+ heth->TxDesc->Status |= ETH_DMATXDESC_OWN;
+ /* Point to next descriptor */
+ heth->TxDesc= (ETH_DMADescTypeDef *)(heth->TxDesc->Buffer2NextDescAddr);
+ }
+ else
+ {
+ for (i=0; i< bufcount; i++)
+ {
+ /* Clear FIRST and LAST segment bits */
+ heth->TxDesc->Status &= ~(ETH_DMATXDESC_FS | ETH_DMATXDESC_LS);
+
+ if (i == 0)
+ {
+ /* Setting the first segment bit */
+ heth->TxDesc->Status |= ETH_DMATXDESC_FS;
+ }
+
+ /* Program size */
+ heth->TxDesc->ControlBufferSize = (ETH_TX_BUF_SIZE & ETH_DMATXDESC_TBS1);
+
+ if (i == (bufcount-1))
+ {
+ /* Setting the last segment bit */
+ heth->TxDesc->Status |= ETH_DMATXDESC_LS;
+ size = FrameLength - (bufcount-1)*ETH_TX_BUF_SIZE;
+ heth->TxDesc->ControlBufferSize = (size & ETH_DMATXDESC_TBS1);
+ }
+
+ /* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */
+ heth->TxDesc->Status |= ETH_DMATXDESC_OWN;
+ /* point to next descriptor */
+ heth->TxDesc = (ETH_DMADescTypeDef *)(heth->TxDesc->Buffer2NextDescAddr);
+ }
+ }
+
+ /* When Tx Buffer unavailable flag is set: clear it and resume transmission */
+ if (((heth->Instance)->DMASR & ETH_DMASR_TBUS) != (uint32_t)RESET)
+ {
+ /* Clear TBUS ETHERNET DMA flag */
+ (heth->Instance)->DMASR = ETH_DMASR_TBUS;
+ /* Resume DMA transmission*/
+ (heth->Instance)->DMATPDR = 0;
+ }
+
+ /* Set ETH HAL State to Ready */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Checks for received frames.
+ * @param heth: ETH handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth)
+{
+ uint32_t framelength = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(heth);
+
+ /* Check the ETH state to BUSY */
+ heth->State = HAL_ETH_STATE_BUSY;
+
+ /* Check if segment is not owned by DMA */
+ /* (((heth->RxDesc->Status & ETH_DMARXDESC_OWN) == (uint32_t)RESET) && ((heth->RxDesc->Status & ETH_DMARXDESC_LS) != (uint32_t)RESET)) */
+ if(((heth->RxDesc->Status & ETH_DMARXDESC_OWN) == (uint32_t)RESET))
+ {
+ /* Check if last segment */
+ if(((heth->RxDesc->Status & ETH_DMARXDESC_LS) != (uint32_t)RESET))
+ {
+ /* increment segment count */
+ (heth->RxFrameInfos).SegCount++;
+
+ /* Check if last segment is first segment: one segment contains the frame */
+ if ((heth->RxFrameInfos).SegCount == 1)
+ {
+ (heth->RxFrameInfos).FSRxDesc =heth->RxDesc;
+ }
+
+ heth->RxFrameInfos.LSRxDesc = heth->RxDesc;
+
+ /* Get the Frame Length of the received packet: substruct 4 bytes of the CRC */
+ framelength = (((heth->RxDesc)->Status & ETH_DMARXDESC_FL) >> ETH_DMARXDESC_FRAMELENGTHSHIFT) - 4;
+ heth->RxFrameInfos.length = framelength;
+
+ /* Get the address of the buffer start address */
+ heth->RxFrameInfos.buffer = ((heth->RxFrameInfos).FSRxDesc)->Buffer1Addr;
+ /* point to next descriptor */
+ heth->RxDesc = (ETH_DMADescTypeDef*) ((heth->RxDesc)->Buffer2NextDescAddr);
+
+ /* Set HAL State to Ready */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ /* Check if first segment */
+ else if((heth->RxDesc->Status & ETH_DMARXDESC_FS) != (uint32_t)RESET)
+ {
+ (heth->RxFrameInfos).FSRxDesc = heth->RxDesc;
+ (heth->RxFrameInfos).LSRxDesc = NULL;
+ (heth->RxFrameInfos).SegCount = 1;
+ /* Point to next descriptor */
+ heth->RxDesc = (ETH_DMADescTypeDef*) (heth->RxDesc->Buffer2NextDescAddr);
+ }
+ /* Check if intermediate segment */
+ else
+ {
+ (heth->RxFrameInfos).SegCount++;
+ /* Point to next descriptor */
+ heth->RxDesc = (ETH_DMADescTypeDef*) (heth->RxDesc->Buffer2NextDescAddr);
+ }
+ }
+
+ /* Set ETH HAL State to Ready */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ return HAL_ERROR;
+}
+
+/**
+ * @brief Gets the Received frame in interrupt mode.
+ * @param heth: ETH handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_GetReceivedFrame_IT(ETH_HandleTypeDef *heth)
+{
+ uint32_t descriptorscancounter = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(heth);
+
+ /* Set ETH HAL State to BUSY */
+ heth->State = HAL_ETH_STATE_BUSY;
+
+ /* Scan descriptors owned by CPU */
+ while (((heth->RxDesc->Status & ETH_DMARXDESC_OWN) == (uint32_t)RESET) && (descriptorscancounter < ETH_RXBUFNB))
+ {
+ /* Just for security */
+ descriptorscancounter++;
+
+ /* Check if first segment in frame */
+ /* ((heth->RxDesc->Status & ETH_DMARXDESC_FS) != (uint32_t)RESET) && ((heth->RxDesc->Status & ETH_DMARXDESC_LS) == (uint32_t)RESET)) */
+ if((heth->RxDesc->Status & (ETH_DMARXDESC_FS | ETH_DMARXDESC_LS)) == (uint32_t)ETH_DMARXDESC_FS)
+ {
+ heth->RxFrameInfos.FSRxDesc = heth->RxDesc;
+ heth->RxFrameInfos.SegCount = 1;
+ /* Point to next descriptor */
+ heth->RxDesc = (ETH_DMADescTypeDef*) (heth->RxDesc->Buffer2NextDescAddr);
+ }
+ /* Check if intermediate segment */
+ /* ((heth->RxDesc->Status & ETH_DMARXDESC_LS) == (uint32_t)RESET)&& ((heth->RxDesc->Status & ETH_DMARXDESC_FS) == (uint32_t)RESET)) */
+ else if ((heth->RxDesc->Status & (ETH_DMARXDESC_LS | ETH_DMARXDESC_FS)) == (uint32_t)RESET)
+ {
+ /* Increment segment count */
+ (heth->RxFrameInfos.SegCount)++;
+ /* Point to next descriptor */
+ heth->RxDesc = (ETH_DMADescTypeDef*)(heth->RxDesc->Buffer2NextDescAddr);
+ }
+ /* Should be last segment */
+ else
+ {
+ /* Last segment */
+ heth->RxFrameInfos.LSRxDesc = heth->RxDesc;
+
+ /* Increment segment count */
+ (heth->RxFrameInfos.SegCount)++;
+
+ /* Check if last segment is first segment: one segment contains the frame */
+ if ((heth->RxFrameInfos.SegCount) == 1)
+ {
+ heth->RxFrameInfos.FSRxDesc = heth->RxDesc;
+ }
+
+ /* Get the Frame Length of the received packet: substruct 4 bytes of the CRC */
+ heth->RxFrameInfos.length = (((heth->RxDesc)->Status & ETH_DMARXDESC_FL) >> ETH_DMARXDESC_FRAMELENGTHSHIFT) - 4;
+
+ /* Get the address of the buffer start address */
+ heth->RxFrameInfos.buffer =((heth->RxFrameInfos).FSRxDesc)->Buffer1Addr;
+
+ /* Point to next descriptor */
+ heth->RxDesc = (ETH_DMADescTypeDef*) (heth->RxDesc->Buffer2NextDescAddr);
+
+ /* Set HAL State to Ready */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ }
+
+ /* Set HAL State to Ready */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles ETH interrupt request.
+ * @param heth: ETH handle
+ * @retval HAL status
+ */
+void HAL_ETH_IRQHandler(ETH_HandleTypeDef *heth)
+{
+ /* Frame received */
+ if (__HAL_ETH_DMA_GET_FLAG(heth, ETH_DMA_FLAG_R))
+ {
+ /* Receive complete callback */
+ HAL_ETH_RxCpltCallback(heth);
+
+ /* Clear the Eth DMA Rx IT pending bits */
+ __HAL_ETH_DMA_CLEAR_IT(heth, ETH_DMA_IT_R);
+
+ /* Set HAL State to Ready */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ }
+ /* Frame transmitted */
+ else if (__HAL_ETH_DMA_GET_FLAG(heth, ETH_DMA_FLAG_T))
+ {
+ /* Transfer complete callback */
+ HAL_ETH_TxCpltCallback(heth);
+
+ /* Clear the Eth DMA Tx IT pending bits */
+ __HAL_ETH_DMA_CLEAR_IT(heth, ETH_DMA_IT_T);
+
+ /* Set HAL State to Ready */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+ }
+
+ /* Clear the interrupt flags */
+ __HAL_ETH_DMA_CLEAR_IT(heth, ETH_DMA_IT_NIS);
+
+ /* ETH DMA Error */
+ if(__HAL_ETH_DMA_GET_FLAG(heth, ETH_DMA_FLAG_AIS))
+ {
+ /* Ethernet Error callback */
+ HAL_ETH_ErrorCallback(heth);
+
+ /* Clear the interrupt flags */
+ __HAL_ETH_DMA_CLEAR_IT(heth, ETH_DMA_FLAG_AIS);
+
+ /* Set HAL State to Ready */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+ }
+}
+
+/**
+ * @brief Tx Transfer completed callbacks.
+ * @param heth: ETH handle
+ * @retval None
+ */
+__weak void HAL_ETH_TxCpltCallback(ETH_HandleTypeDef *heth)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ETH_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer completed callbacks.
+ * @param heth: ETH handle
+ * @retval None
+ */
+__weak void HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ETH_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Ethernet transfer error callbacks
+ * @param heth: ETH handle
+ * @retval None
+ */
+__weak void HAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_ETH_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Reads a PHY register
+ * @param heth: ETH handle
+ * @param PHYReg: PHY register address, is the index of one of the 32 PHY register.
+ * This parameter can be one of the following values:
+ * @arg PHY_BCR: Transceiver Basic Control Register
+ * @arg PHY_BSR: Transceiver Basic Status Register
+ * @arg More PHY register could be read depending on the used PHY
+ * @param RegValue: PHY register value
+ * @retval HAL_TIMEOUT: in case of timeout
+ * MACMIIDR register value: Data read from the selected PHY register (correct read )
+ */
+HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t *RegValue)
+{
+ uint32_t tmpreg = 0;
+ uint32_t timeout = 0;
+
+ /* Check parameters */
+ assert_param(IS_ETH_PHY_ADDRESS(heth->Init.PhyAddress));
+
+ /* Check the ETH peripheral state */
+ if(heth->State == HAL_ETH_STATE_BUSY_RD)
+ {
+ return HAL_BUSY;
+ }
+ /* Set ETH HAL State to BUSY_RD */
+ heth->State = HAL_ETH_STATE_BUSY_RD;
+
+ /* Get the ETHERNET MACMIIAR value */
+ tmpreg = heth->Instance->MACMIIAR;
+
+ /* Keep only the CSR Clock Range CR[2:0] bits value */
+ tmpreg &= ~MACMIIAR_CR_MASK;
+
+ /* Prepare the MII address register value */
+ tmpreg |=(((uint32_t)heth->Init.PhyAddress << 11) & ETH_MACMIIAR_PA); /* Set the PHY device address */
+ tmpreg |=(((uint32_t)PHYReg<<6) & ETH_MACMIIAR_MR); /* Set the PHY register address */
+ tmpreg &= ~ETH_MACMIIAR_MW; /* Set the read mode */
+ tmpreg |= ETH_MACMIIAR_MB; /* Set the MII Busy bit */
+
+ /* Write the result value into the MII Address register */
+ heth->Instance->MACMIIAR = tmpreg;
+
+ /* Check for the Busy flag */
+ do
+ {
+ timeout++;
+ tmpreg = heth->Instance->MACMIIAR;
+ } while (((tmpreg & ETH_MACMIIAR_MB) == ETH_MACMIIAR_MB) && (timeout < PHY_READ_TO));
+
+ /* Return ERROR in case of timeout */
+ if(timeout == PHY_READ_TO)
+ {
+ /* Set ETH HAL State to READY */
+ heth->State = HAL_ETH_STATE_READY;
+ /* Return HAL_TIMEOUT */
+ return HAL_TIMEOUT;
+ }
+
+ /* Get MACMIIDR value */
+ *RegValue = (uint16_t)(heth->Instance->MACMIIDR);
+
+ /* Set ETH HAL State to READY */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Writes to a PHY register.
+ * @param heth: ETH handle
+ * @param PHYReg: PHY register address, is the index of one of the 32 PHY register.
+ * This parameter can be one of the following values:
+ * @arg PHY_BCR: Transceiver Control Register
+ * @arg More PHY register could be written depending on the used PHY
+ * @param RegValue: the value to write
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t RegValue)
+{
+ uint32_t tmpreg = 0;
+ uint32_t timeout = 0;
+
+ /* Check parameters */
+ assert_param(IS_ETH_PHY_ADDRESS(heth->Init.PhyAddress));
+
+ /* Check the ETH peripheral state */
+ if(heth->State == HAL_ETH_STATE_BUSY_WR)
+ {
+ return HAL_BUSY;
+ }
+ /* Set ETH HAL State to BUSY_WR */
+ heth->State = HAL_ETH_STATE_BUSY_WR;
+
+ /* Get the ETHERNET MACMIIAR value */
+ tmpreg = heth->Instance->MACMIIAR;
+
+ /* Keep only the CSR Clock Range CR[2:0] bits value */
+ tmpreg &= ~MACMIIAR_CR_MASK;
+
+ /* Prepare the MII register address value */
+ tmpreg |=(((uint32_t)heth->Init.PhyAddress<<11) & ETH_MACMIIAR_PA); /* Set the PHY device address */
+ tmpreg |=(((uint32_t)PHYReg<<6) & ETH_MACMIIAR_MR); /* Set the PHY register address */
+ tmpreg |= ETH_MACMIIAR_MW; /* Set the write mode */
+ tmpreg |= ETH_MACMIIAR_MB; /* Set the MII Busy bit */
+
+ /* Give the value to the MII data register */
+ heth->Instance->MACMIIDR = (uint16_t)RegValue;
+
+ /* Write the result value into the MII Address register */
+ heth->Instance->MACMIIAR = tmpreg;
+
+ /* Check for the Busy flag */
+ do
+ {
+ timeout++;
+ tmpreg = heth->Instance->MACMIIAR;
+ } while (((tmpreg & ETH_MACMIIAR_MB) == ETH_MACMIIAR_MB) && (timeout < PHY_WRITE_TO));
+
+ /* Return TIMETOUT in case of timeout */
+ if(timeout == PHY_WRITE_TO)
+ {
+ /* Set ETH HAL State to READY */
+ heth->State = HAL_ETH_STATE_READY;
+
+ return HAL_TIMEOUT;
+ }
+
+ /* Set ETH HAL State to READY */
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup ETH_Group3 Peripheral Control functions
+ * @brief Peripheral Control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Enable MAC and DMA transmission and reception.
+ HAL_ETH_Start();
+ (+) Disable MAC and DMA transmission and reception.
+ HAL_ETH_Stop();
+ (+) Set the MAC configuration in runtime mode
+ HAL_ETH_ConfigMAC();
+ (+) Set the DMA configuration in runtime mode
+ HAL_ETH_ConfigDMA();
+
+@endverbatim
+ * @{
+ */
+
+ /**
+ * @brief Enables Ethernet MAC and DMA reception/transmission
+ * @param heth: ETH handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_Start(ETH_HandleTypeDef *heth)
+{
+ /* Process Locked */
+ __HAL_LOCK(heth);
+
+ /* Set the ETH peripheral state to BUSY */
+ heth->State = HAL_ETH_STATE_BUSY;
+
+ /* Enable transmit state machine of the MAC for transmission on the MII */
+ ETH_MACTransmissionEnable(heth);
+
+ /* Enable receive state machine of the MAC for reception from the MII */
+ ETH_MACReceptionEnable(heth);
+
+ /* Flush Transmit FIFO */
+ ETH_FlushTransmitFIFO(heth);
+
+ /* Start DMA transmission */
+ ETH_DMATransmissionEnable(heth);
+
+ /* Start DMA reception */
+ ETH_DMAReceptionEnable(heth);
+
+ /* Set the ETH state to READY*/
+ heth->State= HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stop Ethernet MAC and DMA reception/transmission
+ * @param heth: ETH handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_Stop(ETH_HandleTypeDef *heth)
+{
+ /* Process Locked */
+ __HAL_LOCK(heth);
+
+ /* Set the ETH peripheral state to BUSY */
+ heth->State = HAL_ETH_STATE_BUSY;
+
+ /* Stop DMA transmission */
+ ETH_DMATransmissionDisable(heth);
+
+ /* Stop DMA reception */
+ ETH_DMAReceptionDisable(heth);
+
+ /* Disable receive state machine of the MAC for reception from the MII */
+ ETH_MACReceptionDisable(heth);
+
+ /* Flush Transmit FIFO */
+ ETH_FlushTransmitFIFO(heth);
+
+ /* Disable transmit state machine of the MAC for transmission on the MII */
+ ETH_MACTransmissionDisable(heth);
+
+ /* Set the ETH state*/
+ heth->State = HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Set ETH MAC Configuration.
+ * @param heth: ETH handle
+ * @param macconf: MAC Configuration structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef *macconf)
+{
+ uint32_t tmpreg = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(heth);
+
+ /* Set the ETH peripheral state to BUSY */
+ heth->State= HAL_ETH_STATE_BUSY;
+
+ assert_param(IS_ETH_SPEED(heth->Init.Speed));
+ assert_param(IS_ETH_DUPLEX_MODE(heth->Init.DuplexMode));
+
+ if (macconf != NULL)
+ {
+ /* Check the parameters */
+ assert_param(IS_ETH_WATCHDOG(macconf->Watchdog));
+ assert_param(IS_ETH_JABBER(macconf->Jabber));
+ assert_param(IS_ETH_INTER_FRAME_GAP(macconf->InterFrameGap));
+ assert_param(IS_ETH_CARRIER_SENSE(macconf->CarrierSense));
+ assert_param(IS_ETH_RECEIVE_OWN(macconf->ReceiveOwn));
+ assert_param(IS_ETH_LOOPBACK_MODE(macconf->LoopbackMode));
+ assert_param(IS_ETH_CHECKSUM_OFFLOAD(macconf->ChecksumOffload));
+ assert_param(IS_ETH_RETRY_TRANSMISSION(macconf->RetryTransmission));
+ assert_param(IS_ETH_AUTOMATIC_PADCRC_STRIP(macconf->AutomaticPadCRCStrip));
+ assert_param(IS_ETH_BACKOFF_LIMIT(macconf->BackOffLimit));
+ assert_param(IS_ETH_DEFERRAL_CHECK(macconf->DeferralCheck));
+ assert_param(IS_ETH_RECEIVE_ALL(macconf->ReceiveAll));
+ assert_param(IS_ETH_SOURCE_ADDR_FILTER(macconf->SourceAddrFilter));
+ assert_param(IS_ETH_CONTROL_FRAMES(macconf->PassControlFrames));
+ assert_param(IS_ETH_BROADCAST_FRAMES_RECEPTION(macconf->BroadcastFramesReception));
+ assert_param(IS_ETH_DESTINATION_ADDR_FILTER(macconf->DestinationAddrFilter));
+ assert_param(IS_ETH_PROMISCIOUS_MODE(macconf->PromiscuousMode));
+ assert_param(IS_ETH_MULTICAST_FRAMES_FILTER(macconf->MulticastFramesFilter));
+ assert_param(IS_ETH_UNICAST_FRAMES_FILTER(macconf->UnicastFramesFilter));
+ assert_param(IS_ETH_PAUSE_TIME(macconf->PauseTime));
+ assert_param(IS_ETH_ZEROQUANTA_PAUSE(macconf->ZeroQuantaPause));
+ assert_param(IS_ETH_PAUSE_LOW_THRESHOLD(macconf->PauseLowThreshold));
+ assert_param(IS_ETH_UNICAST_PAUSE_FRAME_DETECT(macconf->UnicastPauseFrameDetect));
+ assert_param(IS_ETH_RECEIVE_FLOWCONTROL(macconf->ReceiveFlowControl));
+ assert_param(IS_ETH_TRANSMIT_FLOWCONTROL(macconf->TransmitFlowControl));
+ assert_param(IS_ETH_VLAN_TAG_COMPARISON(macconf->VLANTagComparison));
+ assert_param(IS_ETH_VLAN_TAG_IDENTIFIER(macconf->VLANTagIdentifier));
+
+ /*------------------------ ETHERNET MACCR Configuration --------------------*/
+ /* Get the ETHERNET MACCR value */
+ tmpreg = (heth->Instance)->MACCR;
+ /* Clear WD, PCE, PS, TE and RE bits */
+ tmpreg &= MACCR_CLEAR_MASK;
+
+ tmpreg |= (uint32_t)(macconf->Watchdog |
+ macconf->Jabber |
+ macconf->InterFrameGap |
+ macconf->CarrierSense |
+ (heth->Init).Speed |
+ macconf->ReceiveOwn |
+ macconf->LoopbackMode |
+ (heth->Init).DuplexMode |
+ macconf->ChecksumOffload |
+ macconf->RetryTransmission |
+ macconf->AutomaticPadCRCStrip |
+ macconf->BackOffLimit |
+ macconf->DeferralCheck);
+
+ /* Write to ETHERNET MACCR */
+ (heth->Instance)->MACCR = (uint32_t)tmpreg;
+
+ /* Wait until the write operation will be taken into account :
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACCR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACCR = tmpreg;
+
+ /*----------------------- ETHERNET MACFFR Configuration --------------------*/
+ /* Write to ETHERNET MACFFR */
+ (heth->Instance)->MACFFR = (uint32_t)(macconf->ReceiveAll |
+ macconf->SourceAddrFilter |
+ macconf->PassControlFrames |
+ macconf->BroadcastFramesReception |
+ macconf->DestinationAddrFilter |
+ macconf->PromiscuousMode |
+ macconf->MulticastFramesFilter |
+ macconf->UnicastFramesFilter);
+
+ /* Wait until the write operation will be taken into account :
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACFFR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACFFR = tmpreg;
+
+ /*--------------- ETHERNET MACHTHR and MACHTLR Configuration ---------------*/
+ /* Write to ETHERNET MACHTHR */
+ (heth->Instance)->MACHTHR = (uint32_t)macconf->HashTableHigh;
+
+ /* Write to ETHERNET MACHTLR */
+ (heth->Instance)->MACHTLR = (uint32_t)macconf->HashTableLow;
+ /*----------------------- ETHERNET MACFCR Configuration --------------------*/
+
+ /* Get the ETHERNET MACFCR value */
+ tmpreg = (heth->Instance)->MACFCR;
+ /* Clear xx bits */
+ tmpreg &= MACFCR_CLEAR_MASK;
+
+ tmpreg |= (uint32_t)((macconf->PauseTime << 16) |
+ macconf->ZeroQuantaPause |
+ macconf->PauseLowThreshold |
+ macconf->UnicastPauseFrameDetect |
+ macconf->ReceiveFlowControl |
+ macconf->TransmitFlowControl);
+
+ /* Write to ETHERNET MACFCR */
+ (heth->Instance)->MACFCR = (uint32_t)tmpreg;
+
+ /* Wait until the write operation will be taken into account :
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACFCR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACFCR = tmpreg;
+
+ /*----------------------- ETHERNET MACVLANTR Configuration -----------------*/
+ (heth->Instance)->MACVLANTR = (uint32_t)(macconf->VLANTagComparison |
+ macconf->VLANTagIdentifier);
+
+ /* Wait until the write operation will be taken into account :
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACVLANTR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACVLANTR = tmpreg;
+ }
+ else /* macconf == NULL : here we just configure Speed and Duplex mode */
+ {
+ /*------------------------ ETHERNET MACCR Configuration --------------------*/
+ /* Get the ETHERNET MACCR value */
+ tmpreg = (heth->Instance)->MACCR;
+
+ /* Clear FES and DM bits */
+ tmpreg &= ~((uint32_t)0x00004800);
+
+ tmpreg |= (uint32_t)(heth->Init.Speed | heth->Init.DuplexMode);
+
+ /* Write to ETHERNET MACCR */
+ (heth->Instance)->MACCR = (uint32_t)tmpreg;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACCR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACCR = tmpreg;
+ }
+
+ /* Set the ETH state to Ready */
+ heth->State= HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets ETH DMA Configuration.
+ * @param heth: ETH handle
+ * @param dmaconf: DMA Configuration structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ETH_ConfigDMA(ETH_HandleTypeDef *heth, ETH_DMAInitTypeDef *dmaconf)
+{
+ uint32_t tmpreg = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(heth);
+
+ /* Set the ETH peripheral state to BUSY */
+ heth->State= HAL_ETH_STATE_BUSY;
+
+ /* Check parameters */
+ assert_param(IS_ETH_DROP_TCPIP_CHECKSUM_FRAME(dmaconf->DropTCPIPChecksumErrorFrame));
+ assert_param(IS_ETH_RECEIVE_STORE_FORWARD(dmaconf->ReceiveStoreForward));
+ assert_param(IS_ETH_FLUSH_RECEIVE_FRAME(dmaconf->FlushReceivedFrame));
+ assert_param(IS_ETH_TRANSMIT_STORE_FORWARD(dmaconf->TransmitStoreForward));
+ assert_param(IS_ETH_TRANSMIT_THRESHOLD_CONTROL(dmaconf->TransmitThresholdControl));
+ assert_param(IS_ETH_FORWARD_ERROR_FRAMES(dmaconf->ForwardErrorFrames));
+ assert_param(IS_ETH_FORWARD_UNDERSIZED_GOOD_FRAMES(dmaconf->ForwardUndersizedGoodFrames));
+ assert_param(IS_ETH_RECEIVE_THRESHOLD_CONTROL(dmaconf->ReceiveThresholdControl));
+ assert_param(IS_ETH_SECOND_FRAME_OPERATE(dmaconf->SecondFrameOperate));
+ assert_param(IS_ETH_ADDRESS_ALIGNED_BEATS(dmaconf->AddressAlignedBeats));
+ assert_param(IS_ETH_FIXED_BURST(dmaconf->FixedBurst));
+ assert_param(IS_ETH_RXDMA_BURST_LENGTH(dmaconf->RxDMABurstLength));
+ assert_param(IS_ETH_TXDMA_BURST_LENGTH(dmaconf->TxDMABurstLength));
+ assert_param(IS_ETH_ENHANCED_DESCRIPTOR_FORMAT(dmaconf->EnhancedDescriptorFormat));
+ assert_param(IS_ETH_DMA_DESC_SKIP_LENGTH(dmaconf->DescriptorSkipLength));
+ assert_param(IS_ETH_DMA_ARBITRATION_ROUNDROBIN_RXTX(dmaconf->DMAArbitration));
+
+ /*----------------------- ETHERNET DMAOMR Configuration --------------------*/
+ /* Get the ETHERNET DMAOMR value */
+ tmpreg = (heth->Instance)->DMAOMR;
+ /* Clear xx bits */
+ tmpreg &= DMAOMR_CLEAR_MASK;
+
+ tmpreg |= (uint32_t)(dmaconf->DropTCPIPChecksumErrorFrame |
+ dmaconf->ReceiveStoreForward |
+ dmaconf->FlushReceivedFrame |
+ dmaconf->TransmitStoreForward |
+ dmaconf->TransmitThresholdControl |
+ dmaconf->ForwardErrorFrames |
+ dmaconf->ForwardUndersizedGoodFrames |
+ dmaconf->ReceiveThresholdControl |
+ dmaconf->SecondFrameOperate);
+
+ /* Write to ETHERNET DMAOMR */
+ (heth->Instance)->DMAOMR = (uint32_t)tmpreg;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->DMAOMR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->DMAOMR = tmpreg;
+
+ /*----------------------- ETHERNET DMABMR Configuration --------------------*/
+ (heth->Instance)->DMABMR = (uint32_t)(dmaconf->AddressAlignedBeats |
+ dmaconf->FixedBurst |
+ dmaconf->RxDMABurstLength | /* !! if 4xPBL is selected for Tx or Rx it is applied for the other */
+ dmaconf->TxDMABurstLength |
+ dmaconf->EnhancedDescriptorFormat |
+ (dmaconf->DescriptorSkipLength << 2) |
+ dmaconf->DMAArbitration |
+ ETH_DMABMR_USP); /* Enable use of separate PBL for Rx and Tx */
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->DMABMR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->DMABMR = tmpreg;
+
+ /* Set the ETH state to Ready */
+ heth->State= HAL_ETH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(heth);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup ETH_Group4 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+ @verbatim
+ ===============================================================================
+ ##### Peripheral State functions #####
+ ===============================================================================
+ [..]
+ This subsection permits to get in run-time the status of the peripheral
+ and the data flow.
+ (+) Get the ETH handle state:
+ HAL_ETH_GetState();
+
+
+ @endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the ETH HAL state
+ * @param heth: ETH handle
+ * @retval HAL state
+ */
+HAL_ETH_StateTypeDef HAL_ETH_GetState(ETH_HandleTypeDef *heth)
+{
+ /* Return ETH state */
+ return heth->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Configures Ethernet MAC and DMA with default parameters.
+ * @param heth: ETH handle
+ * @param err: Ethernet Init error
+ * @retval HAL status
+ */
+static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err)
+{
+ ETH_MACInitTypeDef macinit;
+ ETH_DMAInitTypeDef dmainit;
+ uint32_t tmpreg = 0;
+
+ if (err != ETH_SUCCESS) /* Auto-negotiation failed */
+ {
+ /* Set Ethernet duplex mode to Full-duplex */
+ (heth->Init).DuplexMode = ETH_MODE_FULLDUPLEX;
+
+ /* Set Ethernet speed to 100M */
+ (heth->Init).Speed = ETH_SPEED_100M;
+ }
+
+ /* Ethernet MAC default initialization **************************************/
+ macinit.Watchdog = ETH_WATCHDOG_ENABLE;
+ macinit.Jabber = ETH_JABBER_ENABLE;
+ macinit.InterFrameGap = ETH_INTERFRAMEGAP_96BIT;
+ macinit.CarrierSense = ETH_CARRIERSENCE_ENABLE;
+ macinit.ReceiveOwn = ETH_RECEIVEOWN_ENABLE;
+ macinit.LoopbackMode = ETH_LOOPBACKMODE_DISABLE;
+ if(heth->Init.ChecksumMode == ETH_CHECKSUM_BY_HARDWARE)
+ {
+ macinit.ChecksumOffload = ETH_CHECKSUMOFFLAOD_ENABLE;
+ }
+ else
+ {
+ macinit.ChecksumOffload = ETH_CHECKSUMOFFLAOD_DISABLE;
+ }
+ macinit.RetryTransmission = ETH_RETRYTRANSMISSION_DISABLE;
+ macinit.AutomaticPadCRCStrip = ETH_AUTOMATICPADCRCSTRIP_DISABLE;
+ macinit.BackOffLimit = ETH_BACKOFFLIMIT_10;
+ macinit.DeferralCheck = ETH_DEFFERRALCHECK_DISABLE;
+ macinit.ReceiveAll = ETH_RECEIVEAll_DISABLE;
+ macinit.SourceAddrFilter = ETH_SOURCEADDRFILTER_DISABLE;
+ macinit.PassControlFrames = ETH_PASSCONTROLFRAMES_BLOCKALL;
+ macinit.BroadcastFramesReception = ETH_BROADCASTFRAMESRECEPTION_ENABLE;
+ macinit.DestinationAddrFilter = ETH_DESTINATIONADDRFILTER_NORMAL;
+ macinit.PromiscuousMode = ETH_PROMISCIOUSMODE_DISABLE;
+ macinit.MulticastFramesFilter = ETH_MULTICASTFRAMESFILTER_PERFECT;
+ macinit.UnicastFramesFilter = ETH_UNICASTFRAMESFILTER_PERFECT;
+ macinit.HashTableHigh = 0x0;
+ macinit.HashTableLow = 0x0;
+ macinit.PauseTime = 0x0;
+ macinit.ZeroQuantaPause = ETH_ZEROQUANTAPAUSE_DISABLE;
+ macinit.PauseLowThreshold = ETH_PAUSELOWTHRESHOLD_MINUS4;
+ macinit.UnicastPauseFrameDetect = ETH_UNICASTPAUSEFRAMEDETECT_DISABLE;
+ macinit.ReceiveFlowControl = ETH_RECEIVEFLOWCONTROL_DISABLE;
+ macinit.TransmitFlowControl = ETH_TRANSMITFLOWCONTROL_DISABLE;
+ macinit.VLANTagComparison = ETH_VLANTAGCOMPARISON_16BIT;
+ macinit.VLANTagIdentifier = 0x0;
+
+ /*------------------------ ETHERNET MACCR Configuration --------------------*/
+ /* Get the ETHERNET MACCR value */
+ tmpreg = (heth->Instance)->MACCR;
+ /* Clear WD, PCE, PS, TE and RE bits */
+ tmpreg &= MACCR_CLEAR_MASK;
+ /* Set the WD bit according to ETH Watchdog value */
+ /* Set the JD: bit according to ETH Jabber value */
+ /* Set the IFG bit according to ETH InterFrameGap value */
+ /* Set the DCRS bit according to ETH CarrierSense value */
+ /* Set the FES bit according to ETH Speed value */
+ /* Set the DO bit according to ETH ReceiveOwn value */
+ /* Set the LM bit according to ETH LoopbackMode value */
+ /* Set the DM bit according to ETH Mode value */
+ /* Set the IPCO bit according to ETH ChecksumOffload value */
+ /* Set the DR bit according to ETH RetryTransmission value */
+ /* Set the ACS bit according to ETH AutomaticPadCRCStrip value */
+ /* Set the BL bit according to ETH BackOffLimit value */
+ /* Set the DC bit according to ETH DeferralCheck value */
+ tmpreg |= (uint32_t)(macinit.Watchdog |
+ macinit.Jabber |
+ macinit.InterFrameGap |
+ macinit.CarrierSense |
+ (heth->Init).Speed |
+ macinit.ReceiveOwn |
+ macinit.LoopbackMode |
+ (heth->Init).DuplexMode |
+ macinit.ChecksumOffload |
+ macinit.RetryTransmission |
+ macinit.AutomaticPadCRCStrip |
+ macinit.BackOffLimit |
+ macinit.DeferralCheck);
+
+ /* Write to ETHERNET MACCR */
+ (heth->Instance)->MACCR = (uint32_t)tmpreg;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACCR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACCR = tmpreg;
+
+ /*----------------------- ETHERNET MACFFR Configuration --------------------*/
+ /* Set the RA bit according to ETH ReceiveAll value */
+ /* Set the SAF and SAIF bits according to ETH SourceAddrFilter value */
+ /* Set the PCF bit according to ETH PassControlFrames value */
+ /* Set the DBF bit according to ETH BroadcastFramesReception value */
+ /* Set the DAIF bit according to ETH DestinationAddrFilter value */
+ /* Set the PR bit according to ETH PromiscuousMode value */
+ /* Set the PM, HMC and HPF bits according to ETH MulticastFramesFilter value */
+ /* Set the HUC and HPF bits according to ETH UnicastFramesFilter value */
+ /* Write to ETHERNET MACFFR */
+ (heth->Instance)->MACFFR = (uint32_t)(macinit.ReceiveAll |
+ macinit.SourceAddrFilter |
+ macinit.PassControlFrames |
+ macinit.BroadcastFramesReception |
+ macinit.DestinationAddrFilter |
+ macinit.PromiscuousMode |
+ macinit.MulticastFramesFilter |
+ macinit.UnicastFramesFilter);
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACFFR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACFFR = tmpreg;
+
+ /*--------------- ETHERNET MACHTHR and MACHTLR Configuration --------------*/
+ /* Write to ETHERNET MACHTHR */
+ (heth->Instance)->MACHTHR = (uint32_t)macinit.HashTableHigh;
+
+ /* Write to ETHERNET MACHTLR */
+ (heth->Instance)->MACHTLR = (uint32_t)macinit.HashTableLow;
+ /*----------------------- ETHERNET MACFCR Configuration -------------------*/
+
+ /* Get the ETHERNET MACFCR value */
+ tmpreg = (heth->Instance)->MACFCR;
+ /* Clear xx bits */
+ tmpreg &= MACFCR_CLEAR_MASK;
+
+ /* Set the PT bit according to ETH PauseTime value */
+ /* Set the DZPQ bit according to ETH ZeroQuantaPause value */
+ /* Set the PLT bit according to ETH PauseLowThreshold value */
+ /* Set the UP bit according to ETH UnicastPauseFrameDetect value */
+ /* Set the RFE bit according to ETH ReceiveFlowControl value */
+ /* Set the TFE bit according to ETH TransmitFlowControl value */
+ tmpreg |= (uint32_t)((macinit.PauseTime << 16) |
+ macinit.ZeroQuantaPause |
+ macinit.PauseLowThreshold |
+ macinit.UnicastPauseFrameDetect |
+ macinit.ReceiveFlowControl |
+ macinit.TransmitFlowControl);
+
+ /* Write to ETHERNET MACFCR */
+ (heth->Instance)->MACFCR = (uint32_t)tmpreg;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACFCR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACFCR = tmpreg;
+
+ /*----------------------- ETHERNET MACVLANTR Configuration ----------------*/
+ /* Set the ETV bit according to ETH VLANTagComparison value */
+ /* Set the VL bit according to ETH VLANTagIdentifier value */
+ (heth->Instance)->MACVLANTR = (uint32_t)(macinit.VLANTagComparison |
+ macinit.VLANTagIdentifier);
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACVLANTR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACVLANTR = tmpreg;
+
+ /* Ethernet DMA default initialization ************************************/
+ dmainit.DropTCPIPChecksumErrorFrame = ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE;
+ dmainit.ReceiveStoreForward = ETH_RECEIVESTOREFORWARD_ENABLE;
+ dmainit.FlushReceivedFrame = ETH_FLUSHRECEIVEDFRAME_ENABLE;
+ dmainit.TransmitStoreForward = ETH_TRANSMITSTOREFORWARD_ENABLE;
+ dmainit.TransmitThresholdControl = ETH_TRANSMITTHRESHOLDCONTROL_64BYTES;
+ dmainit.ForwardErrorFrames = ETH_FORWARDERRORFRAMES_DISABLE;
+ dmainit.ForwardUndersizedGoodFrames = ETH_FORWARDUNDERSIZEDGOODFRAMES_DISABLE;
+ dmainit.ReceiveThresholdControl = ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES;
+ dmainit.SecondFrameOperate = ETH_SECONDFRAMEOPERARTE_ENABLE;
+ dmainit.AddressAlignedBeats = ETH_ADDRESSALIGNEDBEATS_ENABLE;
+ dmainit.FixedBurst = ETH_FIXEDBURST_ENABLE;
+ dmainit.RxDMABurstLength = ETH_RXDMABURSTLENGTH_32BEAT;
+ dmainit.TxDMABurstLength = ETH_TXDMABURSTLENGTH_32BEAT;
+ dmainit.EnhancedDescriptorFormat = ETH_DMAENHANCEDDESCRIPTOR_ENABLE;
+ dmainit.DescriptorSkipLength = 0x0;
+ dmainit.DMAArbitration = ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1;
+
+ /* Get the ETHERNET DMAOMR value */
+ tmpreg = (heth->Instance)->DMAOMR;
+ /* Clear xx bits */
+ tmpreg &= DMAOMR_CLEAR_MASK;
+
+ /* Set the DT bit according to ETH DropTCPIPChecksumErrorFrame value */
+ /* Set the RSF bit according to ETH ReceiveStoreForward value */
+ /* Set the DFF bit according to ETH FlushReceivedFrame value */
+ /* Set the TSF bit according to ETH TransmitStoreForward value */
+ /* Set the TTC bit according to ETH TransmitThresholdControl value */
+ /* Set the FEF bit according to ETH ForwardErrorFrames value */
+ /* Set the FUF bit according to ETH ForwardUndersizedGoodFrames value */
+ /* Set the RTC bit according to ETH ReceiveThresholdControl value */
+ /* Set the OSF bit according to ETH SecondFrameOperate value */
+ tmpreg |= (uint32_t)(dmainit.DropTCPIPChecksumErrorFrame |
+ dmainit.ReceiveStoreForward |
+ dmainit.FlushReceivedFrame |
+ dmainit.TransmitStoreForward |
+ dmainit.TransmitThresholdControl |
+ dmainit.ForwardErrorFrames |
+ dmainit.ForwardUndersizedGoodFrames |
+ dmainit.ReceiveThresholdControl |
+ dmainit.SecondFrameOperate);
+
+ /* Write to ETHERNET DMAOMR */
+ (heth->Instance)->DMAOMR = (uint32_t)tmpreg;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->DMAOMR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->DMAOMR = tmpreg;
+
+ /*----------------------- ETHERNET DMABMR Configuration ------------------*/
+ /* Set the AAL bit according to ETH AddressAlignedBeats value */
+ /* Set the FB bit according to ETH FixedBurst value */
+ /* Set the RPBL and 4*PBL bits according to ETH RxDMABurstLength value */
+ /* Set the PBL and 4*PBL bits according to ETH TxDMABurstLength value */
+ /* Set the Enhanced DMA descriptors bit according to ETH EnhancedDescriptorFormat value*/
+ /* Set the DSL bit according to ETH DesciptorSkipLength value */
+ /* Set the PR and DA bits according to ETH DMAArbitration value */
+ (heth->Instance)->DMABMR = (uint32_t)(dmainit.AddressAlignedBeats |
+ dmainit.FixedBurst |
+ dmainit.RxDMABurstLength | /* !! if 4xPBL is selected for Tx or Rx it is applied for the other */
+ dmainit.TxDMABurstLength |
+ dmainit.EnhancedDescriptorFormat |
+ (dmainit.DescriptorSkipLength << 2) |
+ dmainit.DMAArbitration |
+ ETH_DMABMR_USP); /* Enable use of separate PBL for Rx and Tx */
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->DMABMR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->DMABMR = tmpreg;
+
+ if((heth->Init).RxMode == ETH_RXINTERRUPT_MODE)
+ {
+ /* Enable the Ethernet Rx Interrupt */
+ __HAL_ETH_DMA_ENABLE_IT((heth), ETH_DMA_IT_NIS | ETH_DMA_IT_R);
+ }
+
+ /* Initialize MAC address in ethernet MAC */
+ ETH_MACAddressConfig(heth, ETH_MAC_ADDRESS0, heth->Init.MACAddr);
+}
+
+/**
+ * @brief Configures the selected MAC address.
+ * @param heth: ETH handle
+ * @param MacAddr: The MAC address to configure
+ * This parameter can be one of the following values:
+ * @arg ETH_MAC_Address0: MAC Address0
+ * @arg ETH_MAC_Address1: MAC Address1
+ * @arg ETH_MAC_Address2: MAC Address2
+ * @arg ETH_MAC_Address3: MAC Address3
+ * @param Addr: Pointer to MAC address buffer data (6 bytes)
+ * @retval HAL status
+ */
+static void ETH_MACAddressConfig(ETH_HandleTypeDef *heth, uint32_t MacAddr, uint8_t *Addr)
+{
+ uint32_t tmpreg;
+
+ /* Check the parameters */
+ assert_param(IS_ETH_MAC_ADDRESS0123(MacAddr));
+
+ /* Calculate the selected MAC address high register */
+ tmpreg = ((uint32_t)Addr[5] << 8) | (uint32_t)Addr[4];
+ /* Load the selected MAC address high register */
+ (*(__IO uint32_t *)((uint32_t)(ETH_MAC_ADDR_HBASE + MacAddr))) = tmpreg;
+ /* Calculate the selected MAC address low register */
+ tmpreg = ((uint32_t)Addr[3] << 24) | ((uint32_t)Addr[2] << 16) | ((uint32_t)Addr[1] << 8) | Addr[0];
+
+ /* Load the selected MAC address low register */
+ (*(__IO uint32_t *)((uint32_t)(ETH_MAC_ADDR_LBASE + MacAddr))) = tmpreg;
+}
+
+/**
+ * @brief Enables the MAC transmission.
+ * @param heth: ETH handle
+ * @retval None
+ */
+static void ETH_MACTransmissionEnable(ETH_HandleTypeDef *heth)
+{
+ __IO uint32_t tmpreg = 0;
+
+ /* Enable the MAC transmission */
+ (heth->Instance)->MACCR |= ETH_MACCR_TE;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACCR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACCR = tmpreg;
+}
+
+/**
+ * @brief Disables the MAC transmission.
+ * @param heth: ETH handle
+ * @retval None
+ */
+static void ETH_MACTransmissionDisable(ETH_HandleTypeDef *heth)
+{
+ __IO uint32_t tmpreg = 0;
+
+ /* Disable the MAC transmission */
+ (heth->Instance)->MACCR &= ~ETH_MACCR_TE;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACCR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACCR = tmpreg;
+}
+
+/**
+ * @brief Enables the MAC reception.
+ * @param heth: ETH handle
+ * @retval None
+ */
+static void ETH_MACReceptionEnable(ETH_HandleTypeDef *heth)
+{
+ __IO uint32_t tmpreg = 0;
+
+ /* Enable the MAC reception */
+ (heth->Instance)->MACCR |= ETH_MACCR_RE;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACCR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACCR = tmpreg;
+}
+
+/**
+ * @brief Disables the MAC reception.
+ * @param heth: ETH handle
+ * @retval None
+ */
+static void ETH_MACReceptionDisable(ETH_HandleTypeDef *heth)
+{
+ __IO uint32_t tmpreg = 0;
+
+ /* Disable the MAC reception */
+ (heth->Instance)->MACCR &= ~ETH_MACCR_RE;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->MACCR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->MACCR = tmpreg;
+}
+
+/**
+ * @brief Enables the DMA transmission.
+ * @param heth: ETH handle
+ * @retval None
+ */
+static void ETH_DMATransmissionEnable(ETH_HandleTypeDef *heth)
+{
+ /* Enable the DMA transmission */
+ (heth->Instance)->DMAOMR |= ETH_DMAOMR_ST;
+}
+
+/**
+ * @brief Disables the DMA transmission.
+ * @param heth: ETH handle
+ * @retval None
+ */
+static void ETH_DMATransmissionDisable(ETH_HandleTypeDef *heth)
+{
+ /* Disable the DMA transmission */
+ (heth->Instance)->DMAOMR &= ~ETH_DMAOMR_ST;
+}
+
+/**
+ * @brief Enables the DMA reception.
+ * @param heth: ETH handle
+ * @retval None
+ */
+static void ETH_DMAReceptionEnable(ETH_HandleTypeDef *heth)
+{
+ /* Enable the DMA reception */
+ (heth->Instance)->DMAOMR |= ETH_DMAOMR_SR;
+}
+
+/**
+ * @brief Disables the DMA reception.
+ * @param heth: ETH handle
+ * @retval None
+ */
+static void ETH_DMAReceptionDisable(ETH_HandleTypeDef *heth)
+{
+ /* Disable the DMA reception */
+ (heth->Instance)->DMAOMR &= ~ETH_DMAOMR_SR;
+}
+
+/**
+ * @brief Clears the ETHERNET transmit FIFO.
+ * @param heth: ETH handle
+ * @retval None
+ */
+static void ETH_FlushTransmitFIFO(ETH_HandleTypeDef *heth)
+{
+ __IO uint32_t tmpreg = 0;
+
+ /* Set the Flush Transmit FIFO bit */
+ (heth->Instance)->DMAOMR |= ETH_DMAOMR_FTF;
+
+ /* Wait until the write operation will be taken into account:
+ at least four TX_CLK/RX_CLK clock cycles */
+ tmpreg = (heth->Instance)->DMAOMR;
+ HAL_Delay(ETH_REG_WRITE_DELAY);
+ (heth->Instance)->DMAOMR = tmpreg;
+}
+
+/**
+ * @}
+ */
+
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_ETH_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash.c
new file mode 100644
index 0000000..624fea0
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash.c
@@ -0,0 +1,748 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_flash.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief FLASH HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the internal FLASH memory:
+ * + Program operations functions
+ * + Memory Control functions
+ * + Peripheral Errors functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### FLASH peripheral features #####
+ ==============================================================================
+
+ [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses
+ to the Flash memory. It implements the erase and program Flash memory operations
+ and the read and write protection mechanisms.
+
+ [..] The Flash memory interface accelerates code execution with a system of instruction
+ prefetch and cache lines.
+
+ [..] The FLASH main features are:
+ (+) Flash memory read operations
+ (+) Flash memory program/erase operations
+ (+) Read / write protections
+ (+) Prefetch on I-Code
+ (+) 64 cache lines of 128 bits on I-Code
+ (+) 8 cache lines of 128 bits on D-Code
+
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ This driver provides functions and macros to configure and program the FLASH
+ memory of all STM32F4xx devices.
+
+ (#) FLASH Memory IO Programming functions:
+ (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and
+ HAL_FLASH_Lock() functions
+ (++) Program functions: byte, half word, word and double word
+ (++) There Two modes of programming :
+ (+++) Polling mode using HAL_FLASH_Program() function
+ (+++) Interrupt mode using HAL_FLASH_Program_IT() function
+
+ (#) Interrupts and flags management functions :
+ (++) Handle FLASH interrupts by calling HAL_FLASH_IRQHandler()
+ (++) Wait for last FLASH operation according to its status
+ (++) Get error flag status by calling HAL_SetErrorCode()
+
+ [..]
+ In addition to these functions, this driver includes a set of macros allowing
+ to handle the following operations:
+ (+) Set the latency
+ (+) Enable/Disable the prefetch buffer
+ (+) Enable/Disable the Instruction cache and the Data cache
+ (+) Reset the Instruction cache and the Data cache
+ (+) Enable/Disable the FLASH interrupts
+ (+) Monitor the FLASH flags status
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup FLASH
+ * @brief FLASH HAL module driver
+ * @{
+ */
+
+#ifdef HAL_FLASH_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define SECTOR_MASK ((uint32_t)0xFFFFFF07)
+
+#define HAL_FLASH_TIMEOUT_VALUE ((uint32_t)50000)/* 50 s */
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Variable used for Erase sectors under interruption */
+FLASH_ProcessTypeDef pFlash;
+
+
+/* Private function prototypes -----------------------------------------------*/
+/* Program operations */
+static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data);
+static void FLASH_Program_Word(uint32_t Address, uint32_t Data);
+static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data);
+static void FLASH_Program_Byte(uint32_t Address, uint8_t Data);
+static void FLASH_SetErrorCode(void);
+
+HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout);
+
+/* Private functions ---------------------------------------------------------*/
+/** @defgroup FLASH_Private_Functions FLASH Private functions
+ * @{
+ */
+
+/** @defgroup FLASH_Group1 Programming operation functions
+ * @brief Programming operation functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Programming operation functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the FLASH
+ program operations.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Program byte, halfword, word or double word at a specified address
+ * @param TypeProgram: Indicate the way to program at a specified address.
+ * This parameter can be a value of @ref FLASH_Type_Program
+ * @param Address: specifies the address to be programmed.
+ * @param Data: specifies the data to be programmed
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
+{
+ HAL_StatusTypeDef status = HAL_ERROR;
+
+ /* Process Locked */
+ __HAL_LOCK(&pFlash);
+
+ /* Check the parameters */
+ assert_param(IS_TYPEPROGRAM(TypeProgram));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ if(TypeProgram == TYPEPROGRAM_BYTE)
+ {
+ /*Program byte (8-bit) at a specified address.*/
+ FLASH_Program_Byte(Address, (uint8_t) Data);
+ }
+ else if(TypeProgram == TYPEPROGRAM_HALFWORD)
+ {
+ /*Program halfword (16-bit) at a specified address.*/
+ FLASH_Program_HalfWord(Address, (uint16_t) Data);
+ }
+ else if(TypeProgram == TYPEPROGRAM_WORD)
+ {
+ /*Program word (32-bit) at a specified address.*/
+ FLASH_Program_Word(Address, (uint32_t) Data);
+ }
+ else
+ {
+ /*Program double word (64-bit) at a specified address.*/
+ FLASH_Program_DoubleWord(Address, Data);
+ }
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ /* If the program operation is completed, disable the PG Bit */
+ FLASH->CR &= (~FLASH_CR_PG);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(&pFlash);
+
+ return status;
+}
+
+/**
+ * @brief Program byte, halfword, word or double word at a specified address with interrupt enabled.
+ * @param TypeProgram: Indicate the way to program at a specified address.
+ * This parameter can be a value of @ref FLASH_Type_Program
+ * @param Address: specifies the address to be programmed.
+ * @param Data: specifies the data to be programmed
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Process Locked */
+ __HAL_LOCK(&pFlash);
+
+ /* Check the parameters */
+ assert_param(IS_TYPEPROGRAM(TypeProgram));
+
+ /* Enable End of FLASH Operation interrupt */
+ __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP);
+
+ /* Enable Error source interrupt */
+ __HAL_FLASH_ENABLE_IT(FLASH_IT_ERR);
+
+ /* Clear pending flags (if any) */
+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |\
+ FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR| FLASH_FLAG_PGSERR);
+
+ pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAM;
+ pFlash.Address = Address;
+
+ if(TypeProgram == TYPEPROGRAM_BYTE)
+ {
+ /*Program byte (8-bit) at a specified address.*/
+ FLASH_Program_Byte(Address, (uint8_t) Data);
+ }
+ else if(TypeProgram == TYPEPROGRAM_HALFWORD)
+ {
+ /*Program halfword (16-bit) at a specified address.*/
+ FLASH_Program_HalfWord(Address, (uint16_t) Data);
+ }
+ else if(TypeProgram == TYPEPROGRAM_WORD)
+ {
+ /*Program word (32-bit) at a specified address.*/
+ FLASH_Program_Word(Address, (uint32_t) Data);
+ }
+ else
+ {
+ /*Program double word (64-bit) at a specified address.*/
+ FLASH_Program_DoubleWord(Address, Data);
+ }
+
+ return status;
+}
+
+/**
+ * @brief This function handles FLASH interrupt request.
+ * @param None
+ * @retval None
+ */
+void HAL_FLASH_IRQHandler(void)
+{
+ uint32_t temp;
+
+ /* If the program operation is completed, disable the PG Bit */
+ FLASH->CR &= (~FLASH_CR_PG);
+
+ /* If the erase operation is completed, disable the SER Bit */
+ FLASH->CR &= (~FLASH_CR_SER);
+ FLASH->CR &= SECTOR_MASK;
+
+ /* if the erase operation is completed, disable the MER Bit */
+ FLASH->CR &= (~FLASH_MER_BIT);
+
+ /* Check FLASH End of Operation flag */
+ if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP) != RESET)
+ {
+ if(pFlash.ProcedureOnGoing == FLASH_PROC_SECTERASE)
+ {
+ /*Nb of sector to erased can be decreased*/
+ pFlash.NbSectorsToErase--;
+
+ /* Check if there are still sectors to erase*/
+ if(pFlash.NbSectorsToErase != 0)
+ {
+ temp = pFlash.Sector;
+ /*Indicate user which sector has been erased*/
+ HAL_FLASH_EndOfOperationCallback(temp);
+
+ /* Clear pending flags (if any) */
+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |\
+ FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR| FLASH_FLAG_PGSERR);
+
+ /*Increment sector number*/
+ temp = ++pFlash.Sector;
+ FLASH_Erase_Sector(temp, pFlash.VoltageForErase);
+ }
+ else
+ {
+ /*No more sectors to Erase, user callback can be called.*/
+ /*Reset Sector and stop Erase sectors procedure*/
+ pFlash.Sector = temp = 0xFFFFFFFF;
+ pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
+ /* FLASH EOP interrupt user callback */
+ HAL_FLASH_EndOfOperationCallback(temp);
+ /* Clear FLASH End of Operation pending bit */
+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
+ }
+ }
+ else
+ {
+ if (pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE)
+ {
+ /*MassErase ended. Return the selected bank*/
+ /* FLASH EOP interrupt user callback */
+ HAL_FLASH_EndOfOperationCallback(pFlash.Bank);
+ }
+ else
+ {
+ /*Program ended. Return the selected address*/
+ /* FLASH EOP interrupt user callback */
+ HAL_FLASH_EndOfOperationCallback(pFlash.Address);
+ }
+ pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
+ /* Clear FLASH End of Operation pending bit */
+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
+ }
+
+ }
+
+ /* Check FLASH operation error flags */
+ if(__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \
+ FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR)) != RESET)
+ {
+ if(pFlash.ProcedureOnGoing == FLASH_PROC_SECTERASE)
+ {
+ /*return the faulty sector*/
+ temp = pFlash.Sector;
+ pFlash.Sector = 0xFFFFFFFF;
+ }
+ else if (pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE)
+ {
+ /*return the faulty bank*/
+ temp = pFlash.Bank;
+ }
+ else
+ {
+ /*retrun the faulty address*/
+ temp = pFlash.Address;
+ }
+
+ /*Save the Error code*/
+ FLASH_SetErrorCode();
+
+ /* FLASH error interrupt user callback */
+ HAL_FLASH_OperationErrorCallback(temp);
+ /* Clear FLASH error pending bits */
+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR |\
+ FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR);
+
+ /*Stop the procedure ongoing*/
+ pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
+ }
+
+ if(pFlash.ProcedureOnGoing == FLASH_PROC_NONE)
+ {
+ /* Disable End of FLASH Operation interrupt */
+ __HAL_FLASH_DISABLE_IT(FLASH_IT_EOP);
+
+ /* Disable Error source interrupt */
+ __HAL_FLASH_DISABLE_IT(FLASH_IT_ERR);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(&pFlash);
+ }
+
+}
+
+/**
+ * @brief FLASH end of operation interrupt callback
+ * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
+ * - Mass Erase: Bank number which has been requested to erase
+ * - Sectors Erase: Sector which has been erased
+ * (if 0xFFFFFFFF, it means that all the selected sectors have been erased)
+ * - Program: Address which was selected for data program
+ * @retval none
+ */
+__weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_FLASH_EndOfOperationCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief FLASH operation error interrupt callback
+ * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
+ * - Mass Erase: Bank number which has been requested to erase
+ * - Sectors Erase: Sector number which returned an error
+ * - Program: Address which was selected for data program
+ * @retval none
+ */
+__weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_FLASH_OperationErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup FLASH_Group2 Peripheral Control functions
+ * @brief management functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the FLASH
+ memory operations.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Unlock the FLASH control register access
+ * @param None
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_Unlock(void)
+{
+ if((FLASH->CR & FLASH_CR_LOCK) != RESET)
+ {
+ /* Authorize the FLASH Registers access */
+ FLASH->KEYR = FLASH_KEY1;
+ FLASH->KEYR = FLASH_KEY2;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Locks the FLASH control register access
+ * @param None
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_Lock(void)
+{
+ /* Set the LOCK Bit to lock the FLASH Registers access */
+ FLASH->CR |= FLASH_CR_LOCK;
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Unlock the FLASH Option Control Registers access.
+ * @param None
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void)
+{
+ if((FLASH->OPTCR & FLASH_OPTCR_OPTLOCK) != RESET)
+ {
+ /* Authorizes the Option Byte register programming */
+ FLASH->OPTKEYR = FLASH_OPT_KEY1;
+ FLASH->OPTKEYR = FLASH_OPT_KEY2;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Lock the FLASH Option Control Registers access.
+ * @param None
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_OB_Lock(void)
+{
+ /* Set the OPTLOCK Bit to lock the FLASH Option Byte Registers access */
+ FLASH->OPTCR |= FLASH_OPTCR_OPTLOCK;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Launch the option byte loading.
+ * @param None
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_OB_Launch(void)
+{
+ /* Set the OPTSTRT bit in OPTCR register */
+ *(__IO uint8_t *)OPTCR_BYTE0_ADDRESS |= FLASH_OPTCR_OPTSTRT;
+
+ /* Wait for last operation to be completed */
+ return(FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE));
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup FLASH_Group3 Peripheral State and Errors functions
+ * @brief Peripheral Errors functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection permit to get in run-time Errors of the FLASH peripheral.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Get the specific FLASH error flag.
+ * @param None
+ * @retval FLASH_ErrorCode: The returned value can be:
+ * @arg FLASH_ERROR_RD: FLASH Read Protection error flag (PCROP)
+ * @arg FLASH_ERROR_PGS: FLASH Programming Sequence error flag
+ * @arg FLASH_ERROR_PGP: FLASH Programming Parallelism error flag
+ * @arg FLASH_ERROR_PGA: FLASH Programming Alignment error flag
+ * @arg FLASH_ERROR_WRP: FLASH Write protected error flag
+ * @arg FLASH_ERROR_OPERATION: FLASH operation Error flag
+ */
+FLASH_ErrorTypeDef HAL_FLASH_GetError(void)
+{
+ return pFlash.ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Wait for a FLASH operation to complete.
+ * @param Timeout: maximum flash operationtimeout
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout)
+{
+ /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset.
+ Even if the FLASH operation fails, the BUSY flag will be reset and an error
+ flag will be set */
+
+ uint32_t timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY) != RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ if(__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \
+ FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR)) != RESET)
+ {
+ /*Save the error code*/
+ FLASH_SetErrorCode();
+ return HAL_ERROR;
+ }
+
+ /* If there is an error flag set */
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Program a double word (64-bit) at a specified address.
+ * @note This function must be used when the device voltage range is from
+ * 2.7V to 3.6V and an External Vpp is present.
+ *
+ * @note If an erase and a program operations are requested simultaneously,
+ * the erase operation is performed before the program one.
+ *
+ * @param Address: specifies the address to be programmed.
+ * @param Data: specifies the data to be programmed.
+ * @retval None
+ */
+static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data)
+{
+ /* Check the parameters */
+ assert_param(IS_FLASH_ADDRESS(Address));
+
+ /* If the previous operation is completed, proceed to program the new data */
+ FLASH->CR &= CR_PSIZE_MASK;
+ FLASH->CR |= FLASH_PSIZE_DOUBLE_WORD;
+ FLASH->CR |= FLASH_CR_PG;
+
+ *(__IO uint64_t*)Address = Data;
+}
+
+
+/**
+ * @brief Program word (32-bit) at a specified address.
+ * @note This function must be used when the device voltage range is from
+ * 2.7V to 3.6V.
+ *
+ * @note If an erase and a program operations are requested simultaneously,
+ * the erase operation is performed before the program one.
+ *
+ * @param Address: specifies the address to be programmed.
+ * @param Data: specifies the data to be programmed.
+ * @retval None
+ */
+static void FLASH_Program_Word(uint32_t Address, uint32_t Data)
+{
+ /* Check the parameters */
+ assert_param(IS_FLASH_ADDRESS(Address));
+
+ /* If the previous operation is completed, proceed to program the new data */
+ FLASH->CR &= CR_PSIZE_MASK;
+ FLASH->CR |= FLASH_PSIZE_WORD;
+ FLASH->CR |= FLASH_CR_PG;
+
+ *(__IO uint32_t*)Address = Data;
+}
+
+/**
+ * @brief Program a half-word (16-bit) at a specified address.
+ * @note This function must be used when the device voltage range is from
+ * 2.7V to 3.6V.
+ *
+ * @note If an erase and a program operations are requested simultaneously,
+ * the erase operation is performed before the program one.
+ *
+ * @param Address: specifies the address to be programmed.
+ * @param Data: specifies the data to be programmed.
+ * @retval None
+ */
+static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data)
+{
+ /* Check the parameters */
+ assert_param(IS_FLASH_ADDRESS(Address));
+
+ /* If the previous operation is completed, proceed to program the new data */
+ FLASH->CR &= CR_PSIZE_MASK;
+ FLASH->CR |= FLASH_PSIZE_HALF_WORD;
+ FLASH->CR |= FLASH_CR_PG;
+
+ *(__IO uint16_t*)Address = Data;
+}
+
+/**
+ * @brief Program byte (8-bit) at a specified address.
+ * @note This function must be used when the device voltage range is from
+ * 2.7V to 3.6V.
+ *
+ * @note If an erase and a program operations are requested simultaneously,
+ * the erase operation is performed before the program one.
+ *
+ * @param Address: specifies the address to be programmed.
+ * @param Data: specifies the data to be programmed.
+ * @retval None
+ */
+static void FLASH_Program_Byte(uint32_t Address, uint8_t Data)
+{
+ /* Check the parameters */
+ assert_param(IS_FLASH_ADDRESS(Address));
+
+ /* If the previous operation is completed, proceed to program the new data */
+ FLASH->CR &= CR_PSIZE_MASK;
+ FLASH->CR |= FLASH_PSIZE_BYTE;
+ FLASH->CR |= FLASH_CR_PG;
+
+ *(__IO uint8_t*)Address = Data;
+}
+
+/**
+ * @brief Set the specific FLASH error flag.
+ * @param None
+ * @retval None
+ */
+static void FLASH_SetErrorCode(void)
+{
+ if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) != RESET)
+ {
+ pFlash.ErrorCode = FLASH_ERROR_WRP;
+ }
+
+ if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGAERR) != RESET)
+ {
+ pFlash.ErrorCode |= FLASH_ERROR_PGA;
+ }
+
+ if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGPERR) != RESET)
+ {
+ pFlash.ErrorCode |= FLASH_ERROR_PGP;
+ }
+
+ if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGSERR) != RESET)
+ {
+ pFlash.ErrorCode |= FLASH_ERROR_PGS;
+ }
+
+ if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_RDERR) != RESET)
+ {
+ pFlash.ErrorCode |= FLASH_ERROR_RD;
+ }
+
+ if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_OPERR) != RESET)
+ {
+ pFlash.ErrorCode |= FLASH_ERROR_OPERATION;
+ }
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_FLASH_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash_ex.c
new file mode 100644
index 0000000..5f4b2b6
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash_ex.c
@@ -0,0 +1,1299 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_flash_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief Extended FLASH HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the FLASH extension peripheral:
+ * + Extended programming operations functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### Flash Extension features #####
+ ==============================================================================
+
+ [..] Comparing to other previous devices, the FLASH interface for STM32F427xx/437xx and
+ STM32F429xx/439xx devices contains the following additional features
+
+ (+) Capacity up to 2 Mbyte with dual bank architecture supporting read-while-write
+ capability (RWW)
+ (+) Dual bank memory organization
+ (+) PCROP protection for all banks
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..] This driver provides functions to configure and program the FLASH memory
+ of all STM32F427xx/437xx andSTM32F429xx/439xx devices. It includes
+ (#) FLASH Memory Erase functions:
+ (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and
+ HAL_FLASH_Lock() functions
+ (++) Erase function: Erase sector, erase all sectors
+ (++) There is two mode of erase :
+ (+++) Polling Mode using HAL_FLASHEx_Erase()
+ (+++) Interrupt Mode using HAL_FLASHEx_Erase_IT()
+
+ (#) Option Bytes Programming functions: Use HAL_FLASHEx_OBProgram() to :
+ (++) Set/Reset the write protection
+ (++) Set the Read protection Level
+ (++) Set the BOR level
+ (++) Program the user Option Bytes
+ (#) Advanced Option Bytes Programming functions: Use HAL_FLASHEx_AdvOBProgram() to :
+ (++) Extended space (bank 2) erase function
+ (++) Full FLASH space (2 Mo) erase (bank 1 and bank 2)
+ (++) Dual Boot actrivation
+ (++) Write protection configuration for bank 2
+ (++) PCROP protection configuration and control for both banks
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup FLASHEx
+ * @brief FLASH HAL Extension module driver
+ * @{
+ */
+
+#ifdef HAL_FLASH_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define SECTOR_MASK ((uint32_t)0xFFFFFF07)
+
+#define HAL_FLASH_TIMEOUT_VALUE ((uint32_t)50000)/* 50 s */
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+extern FLASH_ProcessTypeDef pFlash;
+
+/* Private function prototypes -----------------------------------------------*/
+/* Option bytes control */
+static void FLASH_MassErase(uint8_t VoltageRange, uint32_t Banks);
+static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WRPSector, uint32_t Banks);
+static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WRPSector, uint32_t Banks);
+static HAL_StatusTypeDef FLASH_OB_RDP_LevelConfig(uint8_t Level);
+static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t Iwdg, uint8_t Stop, uint8_t Stdby);
+static HAL_StatusTypeDef FLASH_OB_BOR_LevelConfig(uint8_t Level);
+static uint8_t FLASH_OB_GetUser(void);
+static uint16_t FLASH_OB_GetWRP(void);
+static FlagStatus FLASH_OB_GetRDP(void);
+static uint8_t FLASH_OB_GetBOR(void);
+
+#if defined(STM32F401xC) || defined(STM32F401xE)
+static HAL_StatusTypeDef FLASH_OB_EnablePCROP(uint32_t Sector);
+static HAL_StatusTypeDef FLASH_OB_DisablePCROP(uint32_t Sector);
+#endif /* STM32F401xC || STM32F401xE */
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx)
+static HAL_StatusTypeDef FLASH_OB_EnablePCROP(uint32_t SectorBank1, uint32_t SectorBank2, uint32_t Banks);
+static HAL_StatusTypeDef FLASH_OB_DisablePCROP(uint32_t SectorBank1, uint32_t SectorBank2, uint32_t Banks);
+static HAL_StatusTypeDef FLASH_OB_BootConfig(uint8_t BootConfig);
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx|| STM32F439xx */
+
+/* Private functions ---------------------------------------------------------*/
+extern HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout);
+
+/** @defgroup FLASHEx_Private_Functions Extended FLASH Private functions
+ * @{
+ */
+
+/** @defgroup FLASHEx_Group1 Extended IO operation functions
+ * @brief Extended IO operation functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Extended programming operation functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the Extension FLASH
+ programming operations Operations.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Perform a mass erase or erase the specified FLASH memory sectors
+ * @param[in] pEraseInit: pointer to an FLASH_EraseInitTypeDef structure that
+ * contains the configuration information for the erasing.
+ *
+ * @param[out] SectorError: pointer to variable that
+ * contains the configuration information on faulty sector in case of error
+ * (0xFFFFFFFF means that all the sectors have been correctly erased)
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *SectorError)
+{
+ HAL_StatusTypeDef status = HAL_ERROR;
+ uint32_t index = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(&pFlash);
+
+ /* Check the parameters */
+ assert_param(IS_TYPEERASE(pEraseInit->TypeErase));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if (status == HAL_OK)
+ {
+ /*Initialization of SectorError variable*/
+ *SectorError = 0xFFFFFFFF;
+
+ if (pEraseInit->TypeErase == TYPEERASE_MASSERASE)
+ {
+ /*Mass erase to be done*/
+ FLASH_MassErase((uint8_t) pEraseInit->VoltageRange, pEraseInit->Banks);
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ /* if the erase operation is completed, disable the MER Bit */
+ FLASH->CR &= (~FLASH_MER_BIT);
+ }
+ else
+ {
+ /* Check the parameters */
+ assert_param(IS_NBSECTORS(pEraseInit->NbSectors + pEraseInit->Sector));
+
+ /* Erase by sector by sector to be done*/
+ for(index = pEraseInit->Sector; index < (pEraseInit->NbSectors + pEraseInit->Sector); index++)
+ {
+ FLASH_Erase_Sector(index, (uint8_t) pEraseInit->VoltageRange);
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ /* If the erase operation is completed, disable the SER Bit */
+ FLASH->CR &= (~FLASH_CR_SER);
+ FLASH->CR &= SECTOR_MASK;
+
+ if (status != HAL_OK)
+ {
+ /* In case of error, stop erase procedure and return the faulty sector*/
+ *SectorError = index;
+ break;
+ }
+ }
+ }
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(&pFlash);
+
+ return status;
+}
+
+/**
+ * @brief Perform a mass erase or erase the specified FLASH memory sectors with interrupt enabled
+ * @param pEraseInit: pointer to an FLASH_EraseInitTypeDef structure that
+ * contains the configuration information for the erasing.
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Process Locked */
+ __HAL_LOCK(&pFlash);
+
+ /* Check the parameters */
+ assert_param(IS_TYPEERASE(pEraseInit->TypeErase));
+
+ /* Enable End of FLASH Operation interrupt */
+ __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP);
+
+ /* Enable Error source interrupt */
+ __HAL_FLASH_ENABLE_IT(FLASH_IT_ERR);
+
+ /* Clear pending flags (if any) */
+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |\
+ FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR| FLASH_FLAG_PGSERR);
+
+ if (pEraseInit->TypeErase == TYPEERASE_MASSERASE)
+ {
+ /*Mass erase to be done*/
+ pFlash.ProcedureOnGoing = FLASH_PROC_MASSERASE;
+ pFlash.Bank = pEraseInit->Banks;
+ FLASH_MassErase((uint8_t) pEraseInit->VoltageRange, pEraseInit->Banks);
+ }
+ else
+ {
+ /* Erase by sector to be done*/
+
+ /* Check the parameters */
+ assert_param(IS_NBSECTORS(pEraseInit->NbSectors + pEraseInit->Sector));
+
+ pFlash.ProcedureOnGoing = FLASH_PROC_SECTERASE;
+ pFlash.NbSectorsToErase = pEraseInit->NbSectors;
+ pFlash.Sector = pEraseInit->Sector;
+ pFlash.VoltageForErase = (uint8_t)pEraseInit->VoltageRange;
+
+ /*Erase 1st sector and wait for IT*/
+ FLASH_Erase_Sector(pEraseInit->Sector, pEraseInit->VoltageRange);
+ }
+
+ return status;
+}
+
+/**
+ * @brief Program option bytes
+ * @param pOBInit: pointer to an FLASH_OBInitStruct structure that
+ * contains the configuration information for the programming.
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit)
+{
+ HAL_StatusTypeDef status = HAL_ERROR;
+
+ /* Process Locked */
+ __HAL_LOCK(&pFlash);
+
+ /* Check the parameters */
+ assert_param(IS_OPTIONBYTE(pOBInit->OptionType));
+
+ /*Write protection configuration*/
+ if((pOBInit->OptionType & OPTIONBYTE_WRP) == OPTIONBYTE_WRP)
+ {
+ assert_param(IS_WRPSTATE(pOBInit->WRPState));
+ if (pOBInit->WRPState == WRPSTATE_ENABLE)
+ {
+ /*Enable of Write protection on the selected Sector*/
+ status = FLASH_OB_EnableWRP(pOBInit->WRPSector, pOBInit->Banks);
+ }
+ else
+ {
+ /*Disable of Write protection on the selected Sector*/
+ status = FLASH_OB_DisableWRP(pOBInit->WRPSector, pOBInit->Banks);
+ }
+ }
+
+ /*Read protection configuration*/
+ if((pOBInit->OptionType & OPTIONBYTE_RDP) == OPTIONBYTE_RDP)
+ {
+ status = FLASH_OB_RDP_LevelConfig(pOBInit->RDPLevel);
+ }
+
+ /*USER configuration*/
+ if((pOBInit->OptionType & OPTIONBYTE_USER) == OPTIONBYTE_USER)
+ {
+ status = FLASH_OB_UserConfig(pOBInit->USERConfig&OB_IWDG_SW,
+ pOBInit->USERConfig&OB_STOP_NO_RST,
+ pOBInit->USERConfig&OB_STDBY_NO_RST);
+ }
+
+ /*BOR Level configuration*/
+ if((pOBInit->OptionType & OPTIONBYTE_BOR) == OPTIONBYTE_BOR)
+ {
+ status = FLASH_OB_BOR_LevelConfig(pOBInit->BORLevel);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(&pFlash);
+
+ return status;
+}
+
+/**
+ * @brief Get the Option byte configuration
+ * @param pOBInit: pointer to an FLASH_OBInitStruct structure that
+ * contains the configuration information for the programming.
+ *
+ * @retval None
+ */
+void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit)
+{
+ pOBInit->OptionType = OPTIONBYTE_WRP | OPTIONBYTE_RDP | OPTIONBYTE_USER | OPTIONBYTE_BOR;
+
+ /*Get WRP*/
+ pOBInit->WRPSector = FLASH_OB_GetWRP();
+
+ /*Get RDP Level*/
+ pOBInit->RDPLevel = FLASH_OB_GetRDP();
+
+ /*Get USER*/
+ pOBInit->USERConfig = FLASH_OB_GetUser();
+
+ /*Get BOR Level*/
+ pOBInit->BORLevel = FLASH_OB_GetBOR();
+}
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F401xC) || defined(STM32F401xE)
+/**
+ * @brief Program option bytes
+ * @param pAdvOBInit: pointer to an FLASH_AdvOBProgramInitTypeDef structure that
+ * contains the configuration information for the programming.
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASHEx_AdvOBProgram (FLASH_AdvOBProgramInitTypeDef *pAdvOBInit)
+{
+ HAL_StatusTypeDef status = HAL_ERROR;
+
+ /* Check the parameters */
+ assert_param(IS_OBEX(pAdvOBInit->OptionType));
+
+ /*Program PCROP option byte*/
+ if (((pAdvOBInit->OptionType) & OBEX_PCROP) == OBEX_PCROP)
+ {
+ /* Check the parameters */
+ assert_param(IS_PCROPSTATE(pAdvOBInit->PCROPState));
+ if ((pAdvOBInit->PCROPState) == PCROPSTATE_ENABLE)
+ {
+ /*Enable of Write protection on the selected Sector*/
+#if defined(STM32F401xC) || defined(STM32F401xE)
+ status = FLASH_OB_EnablePCROP(pAdvOBInit->Sectors);
+#else /* STM32F427xx || STM32F437xx || STM32F429xx|| STM32F439xx */
+ status = FLASH_OB_EnablePCROP(pAdvOBInit->SectorsBank1, pAdvOBInit->SectorsBank2, pAdvOBInit->Banks);
+#endif /* STM32F401xC || STM32F401xE */
+ }
+ else
+ {
+ /*Disable of Write protection on the selected Sector*/
+#if defined(STM32F401xC) || defined(STM32F401xE)
+ status = FLASH_OB_DisablePCROP(pAdvOBInit->Sectors);
+#else /* STM32F427xx || STM32F437xx || STM32F429xx|| STM32F439xx */
+ status = FLASH_OB_DisablePCROP(pAdvOBInit->SectorsBank1, pAdvOBInit->SectorsBank2, pAdvOBInit->Banks);
+#endif /* STM32F401xC || STM32F401xE */
+ }
+ }
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx)
+ /*Program BOOT config option byte*/
+ if (((pAdvOBInit->OptionType) & OBEX_BOOTCONFIG) == OBEX_BOOTCONFIG)
+ {
+ status = FLASH_OB_BootConfig(pAdvOBInit->BootConfig);
+ }
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+
+ return status;
+}
+
+/**
+ * @brief Get the OBEX byte configuration
+ * @param pAdvOBInit: pointer to an FLASH_AdvOBProgramInitTypeDef structure that
+ * contains the configuration information for the programming.
+ *
+ * @retval None
+ */
+void HAL_FLASHEx_AdvOBGetConfig(FLASH_AdvOBProgramInitTypeDef *pAdvOBInit)
+{
+#if defined(STM32F401xC) || defined(STM32F401xE)
+ /*Get Sector*/
+ pAdvOBInit->Sectors = (*(__IO uint16_t *)(OPTCR_BYTE2_ADDRESS));
+#else /* STM32F427xx || STM32F437xx || STM32F429xx|| STM32F439xx */
+ /*Get Sector for Bank1*/
+ pAdvOBInit->SectorsBank1 = (*(__IO uint16_t *)(OPTCR_BYTE2_ADDRESS));
+
+ /*Get Sector for Bank2*/
+ pAdvOBInit->SectorsBank2 = (*(__IO uint16_t *)(OPTCR1_BYTE2_ADDRESS));
+
+ /*Get Boot config OB*/
+ pAdvOBInit->BootConfig = *(__IO uint8_t *)OPTCR_BYTE0_ADDRESS;
+#endif /* STM32F401xC || STM32F401xE */
+}
+
+/**
+ * @brief Select the Protection Mode
+ *
+ * @note After PCROP activated Option Byte modification NOT POSSIBLE! excepted
+ * Global Read Out Protection modification (from level1 to level0)
+ * @note Once SPRMOD bit is active unprotection of a protected sector is not possible
+ * @note Read a prtotected sector will set RDERR Flag and write a protected sector will set WRPERR Flag
+ * @note This function can be used only for STM32F427xx/STM32F429xx/STM32F437xx/STM32F439xx/STM32F401xx devices.
+ *
+ * @param None
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASHEx_OB_SelectPCROP(void)
+{
+ uint8_t optiontmp = 0xFF;
+
+ /* Mask SPRMOD bit */
+ optiontmp = (uint8_t)((*(__IO uint8_t *)OPTCR_BYTE3_ADDRESS) & (uint8_t)0x7F);
+
+ /* Update Option Byte */
+ *(__IO uint8_t *)OPTCR_BYTE3_ADDRESS = (uint8_t)(OB_PCROP_SELECTED | optiontmp);
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Deselect the Protection Mode
+ *
+ * @note After PCROP activated Option Byte modification NOT POSSIBLE! excepted
+ * Global Read Out Protection modification (from level1 to level0)
+ * @note Once SPRMOD bit is active unprotection of a protected sector is not possible
+ * @note Read a prtotected sector will set RDERR Flag and write a protected sector will set WRPERR Flag
+ * @note This function can be used only for STM32F427xx/STM32F429xx/STM32F437xx/STM32F439xx/STM32F401xx devices.
+ *
+ * @param None
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASHEx_OB_DeSelectPCROP(void)
+{
+ uint8_t optiontmp = 0xFF;
+
+ /* Mask SPRMOD bit */
+ optiontmp = (uint8_t)((*(__IO uint8_t *)OPTCR_BYTE3_ADDRESS) & (uint8_t)0x7F);
+
+ /* Update Option Byte */
+ *(__IO uint8_t *)OPTCR_BYTE3_ADDRESS = (uint8_t)(OB_PCROP_DESELECTED | optiontmp);
+
+ return HAL_OK;
+}
+
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE */
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx)
+
+/**
+ * @brief Returns the FLASH Write Protection Option Bytes value for Bank 2
+ * @note This function can be used only for STM32F427X and STM32F429X devices.
+ * @param None
+ * @retval The FLASH Write Protection Option Bytes value
+ */
+uint16_t HAL_FLASHEx_OB_GetBank2WRP(void)
+{
+ /* Return the FLASH write protection Register value */
+ return (*(__IO uint16_t *)(OPTCR1_BYTE2_ADDRESS));
+}
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+
+/**
+ * @}
+ */
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx)
+/**
+ * @brief Full erase of FLASH memory sectors
+ * @param VoltageRange: The device voltage range which defines the erase parallelism.
+ * This parameter can be one of the following values:
+ * @arg VOLTAGE_RANGE_1: when the device voltage range is 1.8V to 2.1V,
+ * the operation will be done by byte (8-bit)
+ * @arg VOLTAGE_RANGE_2: when the device voltage range is 2.1V to 2.7V,
+ * the operation will be done by half word (16-bit)
+ * @arg VOLTAGE_RANGE_3: when the device voltage range is 2.7V to 3.6V,
+ * the operation will be done by word (32-bit)
+ * @arg VOLTAGE_RANGE_4: when the device voltage range is 2.7V to 3.6V + External Vpp,
+ * the operation will be done by double word (64-bit)
+ *
+ * @param Banks: Banks to be erased
+ * This parameter can be one of the following values:
+ * @arg FLASH_BANK_1: Bank1 to be erased
+ * @arg FLASH_BANK_2: Bank2 to be erased
+ * @arg FLASH_BANK_BOTH: Bank1 and Bank2 to be erased
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static void FLASH_MassErase(uint8_t VoltageRange, uint32_t Banks)
+{
+ uint32_t tmp_psize = 0;
+
+ /* Check the parameters */
+ assert_param(IS_VOLTAGERANGE(VoltageRange));
+ assert_param(IS_FLASH_BANK(Banks));
+
+ /* if the previous operation is completed, proceed to erase all sectors */
+ FLASH->CR &= CR_PSIZE_MASK;
+ FLASH->CR |= tmp_psize;
+ if(Banks == FLASH_BANK_BOTH)
+ {
+ /* bank1 & bank2 will be erased*/
+ FLASH->CR |= FLASH_MER_BIT;
+ }
+ else if(Banks == FLASH_BANK_1)
+ {
+ /*Only bank1 will be erased*/
+ FLASH->CR |= FLASH_CR_MER1;
+ }
+ else
+ {
+ /*Only bank2 will be erased*/
+ FLASH->CR |= FLASH_CR_MER2;
+ }
+ FLASH->CR |= FLASH_CR_STRT;
+}
+
+/**
+ * @brief Erase the specified FLASH memory sector
+ * @param Sector: FLASH sector to erase
+ * The value of this parameter depend on device used within the same series
+ * @param VoltageRange: The device voltage range which defines the erase parallelism.
+ * This parameter can be one of the following values:
+ * @arg VOLTAGE_RANGE_1: when the device voltage range is 1.8V to 2.1V,
+ * the operation will be done by byte (8-bit)
+ * @arg VOLTAGE_RANGE_2: when the device voltage range is 2.1V to 2.7V,
+ * the operation will be done by half word (16-bit)
+ * @arg VOLTAGE_RANGE_3: when the device voltage range is 2.7V to 3.6V,
+ * the operation will be done by word (32-bit)
+ * @arg VOLTAGE_RANGE_4: when the device voltage range is 2.7V to 3.6V + External Vpp,
+ * the operation will be done by double word (64-bit)
+ *
+ * @retval None
+ */
+void FLASH_Erase_Sector(uint32_t Sector, uint8_t VoltageRange)
+{
+ uint32_t tmp_psize = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FLASH_SECTOR(Sector));
+ assert_param(IS_VOLTAGERANGE(VoltageRange));
+
+ if(VoltageRange == VOLTAGE_RANGE_1)
+ {
+ tmp_psize = FLASH_PSIZE_BYTE;
+ }
+ else if(VoltageRange == VOLTAGE_RANGE_2)
+ {
+ tmp_psize = FLASH_PSIZE_HALF_WORD;
+ }
+ else if(VoltageRange == VOLTAGE_RANGE_3)
+ {
+ tmp_psize = FLASH_PSIZE_WORD;
+ }
+ else
+ {
+ tmp_psize = FLASH_PSIZE_DOUBLE_WORD;
+ }
+
+ /* Need to add offset of 4 when sector higher than FLASH_SECTOR_11 */
+ if (Sector > FLASH_SECTOR_11)
+ {
+ Sector += 4;
+ }
+ /* If the previous operation is completed, proceed to erase the sector */
+ FLASH->CR &= CR_PSIZE_MASK;
+ FLASH->CR |= tmp_psize;
+ FLASH->CR &= SECTOR_MASK;
+ FLASH->CR |= FLASH_CR_SER | (Sector << POSITION_VAL(FLASH_CR_SNB));
+ FLASH->CR |= FLASH_CR_STRT;
+}
+
+/**
+ * @brief Enable the write protection of the desired bank1 or bank 2 sectors
+ *
+ * @note When the memory read protection level is selected (RDP level = 1),
+ * it is not possible to program or erase the flash sector i if CortexM4
+ * debug features are connected or boot code is executed in RAM, even if nWRPi = 1
+ * @note Active value of nWRPi bits is inverted when PCROP mode is active (SPRMOD =1).
+ *
+ * @param WRPSector: specifies the sector(s) to be write protected.
+ * This parameter can be one of the following values:
+ * @arg WRPSector: A value between OB_WRP_SECTOR_0 and OB_WRP_SECTOR_23
+ * @arg OB_WRP_SECTOR_All
+ * @note BANK2 starts from OB_WRP_SECTOR_12
+ *
+ * @param Banks: Enable write protection on all the sectors for the specific bank
+ * This parameter can be one of the following values:
+ * @arg FLASH_BANK_1: WRP on all sectors of bank1
+ * @arg FLASH_BANK_2: WRP on all sectors of bank2
+ * @arg FLASH_BANK_BOTH: WRP on all sectors of bank1 & bank2
+ *
+ * @retval HAL FLASH State
+ */
+static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WRPSector, uint32_t Banks)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_OB_WRP_SECTOR(WRPSector));
+ assert_param(IS_FLASH_BANK(Banks));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ if (((WRPSector == OB_WRP_SECTOR_All) && ((Banks == FLASH_BANK_1) || (Banks == FLASH_BANK_BOTH))) ||
+ (WRPSector < OB_WRP_SECTOR_12))
+ {
+ if (WRPSector == OB_WRP_SECTOR_All)
+ {
+ /*Write protection on all sector of BANK1*/
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS &= (~(WRPSector>>12));
+ }
+ else
+ {
+ /*Write protection done on sectors of BANK1*/
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS &= (~WRPSector);
+ }
+ }
+ else
+ {
+ /*Write protection done on sectors of BANK2*/
+ *(__IO uint16_t*)OPTCR1_BYTE2_ADDRESS &= (~(WRPSector>>12));
+ }
+
+ /*Write protection on all sector of BANK2*/
+ if ((WRPSector == OB_WRP_SECTOR_All) && (Banks == FLASH_BANK_BOTH))
+ {
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ *(__IO uint16_t*)OPTCR1_BYTE2_ADDRESS &= (~(WRPSector>>12));
+ }
+ }
+
+ }
+
+ return status;
+}
+
+/**
+ * @brief Disable the write protection of the desired bank1 or bank 2 sectors
+ *
+ * @note When the memory read protection level is selected (RDP level = 1),
+ * it is not possible to program or erase the flash sector i if CortexM4
+ * debug features are connected or boot code is executed in RAM, even if nWRPi = 1
+ * @note Active value of nWRPi bits is inverted when PCROP mode is active (SPRMOD =1).
+ *
+ * @param WRPSector: specifies the sector(s) to be write protected.
+ * This parameter can be one of the following values:
+ * @arg WRPSector: A value between OB_WRP_SECTOR_0 and OB_WRP_SECTOR_23
+ * @arg OB_WRP_Sector_All
+ * @note BANK2 starts from OB_WRP_SECTOR_12
+ *
+ * @param Banks: Disable write protection on all the sectors for the specific bank
+ * This parameter can be one of the following values:
+ * @arg FLASH_BANK_1: Bank1 to be erased
+ * @arg FLASH_BANK_2: Bank2 to be erased
+ * @arg FLASH_BANK_BOTH: Bank1 and Bank2 to be erased
+ *
+ * @retval HAL Staus
+ */
+static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WRPSector, uint32_t Banks)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_OB_WRP_SECTOR(WRPSector));
+ assert_param(IS_FLASH_BANK(Banks));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ if (((WRPSector == OB_WRP_SECTOR_All) && ((Banks == FLASH_BANK_1) || (Banks == FLASH_BANK_BOTH))) ||
+ (WRPSector < OB_WRP_SECTOR_12))
+ {
+ if (WRPSector == OB_WRP_SECTOR_All)
+ {
+ /*Write protection on all sector of BANK1*/
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS |= (uint16_t)(WRPSector>>12);
+ }
+ else
+ {
+ /*Write protection done on sectors of BANK1*/
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS |= (uint16_t)WRPSector;
+ }
+ }
+ else
+ {
+ /*Write protection done on sectors of BANK2*/
+ *(__IO uint16_t*)OPTCR1_BYTE2_ADDRESS |= (uint16_t)(WRPSector>>12);
+ }
+
+ /*Write protection on all sector of BANK2*/
+ if ((WRPSector == OB_WRP_SECTOR_All) && (Banks == FLASH_BANK_BOTH))
+ {
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ *(__IO uint16_t*)OPTCR1_BYTE2_ADDRESS |= (uint16_t)(WRPSector>>12);
+ }
+ }
+
+ }
+
+ return status;
+}
+
+/**
+ * @brief Configure the Dual Bank Boot.
+ *
+ * @note This function can be used only for STM32F42xxx/43xxx devices.
+ *
+ * @param BootConfig specifies the Dual Bank Boot Option byte.
+ * This parameter can be one of the following values:
+ * @arg OB_Dual_BootEnabled: Dual Bank Boot Enable
+ * @arg OB_Dual_BootDisabled: Dual Bank Boot Disabled
+ * @retval None
+ */
+static HAL_StatusTypeDef FLASH_OB_BootConfig(uint8_t BootConfig)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_OB_BOOT(BootConfig));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ /* Set Dual Bank Boot */
+ *(__IO uint8_t *)OPTCR_BYTE0_ADDRESS &= (~FLASH_OPTCR_BFB2);
+ *(__IO uint8_t *)OPTCR_BYTE0_ADDRESS |= BootConfig;
+ }
+
+ return status;
+}
+
+/**
+ * @brief Enable the read/write protection (PCROP) of the desired
+ * sectors of Bank 1 and/or Bank 2.
+ * @note This function can be used only for STM32F42xxx/43xxx devices.
+ * @param SectorBank1 Specifies the sector(s) to be read/write protected or unprotected for bank1.
+ * This parameter can be one of the following values:
+ * @arg OB_PCROP: A value between OB_PCROP_SECTOR_0 and OB_PCROP_SECTOR_11
+ * @arg OB_PCROP_SECTOR__All
+ * @param SectorBank2 Specifies the sector(s) to be read/write protected or unprotected for bank2.
+ * This parameter can be one of the following values:
+ * @arg OB_PCROP: A value between OB_PCROP_SECTOR_12 and OB_PCROP_SECTOR_23
+ * @arg OB_PCROP_SECTOR__All
+ * @param Banks Enable PCROP protection on all the sectors for the specific bank
+ * This parameter can be one of the following values:
+ * @arg FLASH_BANK_1: WRP on all sectors of bank1
+ * @arg FLASH_BANK_2: WRP on all sectors of bank2
+ * @arg FLASH_BANK_BOTH: WRP on all sectors of bank1 & bank2
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static HAL_StatusTypeDef FLASH_OB_EnablePCROP(uint32_t SectorBank1, uint32_t SectorBank2, uint32_t Banks)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ assert_param(IS_FLASH_BANK(Banks));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ if ((Banks == FLASH_BANK_1) || (Banks == FLASH_BANK_BOTH))
+ {
+ assert_param(IS_OB_PCROP(SectorBank1));
+ /*Write protection done on sectors of BANK1*/
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS |= (uint16_t)SectorBank1;
+ }
+ else
+ {
+ assert_param(IS_OB_PCROP(SectorBank2));
+ /*Write protection done on sectors of BANK2*/
+ *(__IO uint16_t*)OPTCR1_BYTE2_ADDRESS |= (uint16_t)SectorBank2;
+ }
+
+ /*Write protection on all sector of BANK2*/
+ if (Banks == FLASH_BANK_BOTH)
+ {
+ assert_param(IS_OB_PCROP(SectorBank2));
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ /*Write protection done on sectors of BANK2*/
+ *(__IO uint16_t*)OPTCR1_BYTE2_ADDRESS |= (uint16_t)SectorBank2;
+ }
+ }
+
+ }
+
+ return status;
+}
+
+
+/**
+ * @brief Disable the read/write protection (PCROP) of the desired
+ * sectors of Bank 1 and/or Bank 2.
+ * @note This function can be used only for STM32F42xxx/43xxx devices.
+ * @param SectorBank1 specifies the sector(s) to be read/write protected or unprotected for bank1.
+ * This parameter can be one of the following values:
+ * @arg OB_PCROP: A value between OB_PCROP_SECTOR_0 and OB_PCROP_SECTOR_11
+ * @arg OB_PCROP_SECTOR__All
+ * @param SectorBank2 Specifies the sector(s) to be read/write protected or unprotected for bank2.
+ * This parameter can be one of the following values:
+ * @arg OB_PCROP: A value between OB_PCROP_SECTOR_12 and OB_PCROP_SECTOR_23
+ * @arg OB_PCROP_SECTOR__All
+ * @param Banks Disable PCROP protection on all the sectors for the specific bank
+ * This parameter can be one of the following values:
+ * @arg FLASH_BANK_1: WRP on all sectors of bank1
+ * @arg FLASH_BANK_2: WRP on all sectors of bank2
+ * @arg FLASH_BANK_BOTH: WRP on all sectors of bank1 & bank2
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static HAL_StatusTypeDef FLASH_OB_DisablePCROP(uint32_t SectorBank1, uint32_t SectorBank2, uint32_t Banks)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_FLASH_BANK(Banks));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ if ((Banks == FLASH_BANK_1) || (Banks == FLASH_BANK_BOTH))
+ {
+ assert_param(IS_OB_PCROP(SectorBank1));
+ /*Write protection done on sectors of BANK1*/
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS &= (~SectorBank1);
+ }
+ else
+ {
+ /*Write protection done on sectors of BANK2*/
+ assert_param(IS_OB_PCROP(SectorBank2));
+ *(__IO uint16_t*)OPTCR1_BYTE2_ADDRESS &= (~SectorBank2);
+ }
+
+ /*Write protection on all sector of BANK2*/
+ if (Banks == FLASH_BANK_BOTH)
+ {
+ assert_param(IS_OB_PCROP(SectorBank2));
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ /*Write protection done on sectors of BANK2*/
+ *(__IO uint16_t*)OPTCR1_BYTE2_ADDRESS &= (~SectorBank2);
+ }
+ }
+
+ }
+
+ return status;
+
+}
+
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) || defined(STM32F401xC) || defined(STM32F401xE)
+/**
+ * @brief Mass erase of FLASH memory
+ * @param VoltageRange: The device voltage range which defines the erase parallelism.
+ * This parameter can be one of the following values:
+ * @arg VOLTAGE_RANGE_1: when the device voltage range is 1.8V to 2.1V,
+ * the operation will be done by byte (8-bit)
+ * @arg VOLTAGE_RANGE_2: when the device voltage range is 2.1V to 2.7V,
+ * the operation will be done by half word (16-bit)
+ * @arg VOLTAGE_RANGE_3: when the device voltage range is 2.7V to 3.6V,
+ * the operation will be done by word (32-bit)
+ * @arg VOLTAGE_RANGE_4: when the device voltage range is 2.7V to 3.6V + External Vpp,
+ * the operation will be done by double word (64-bit)
+ *
+ * @param Banks: Banks to be erased
+ * This parameter can be one of the following values:
+ * @arg FLASH_BANK_1: Bank1 to be erased
+ *
+ * @retval None
+ */
+static void FLASH_MassErase(uint8_t VoltageRange, uint32_t Banks)
+{
+ uint32_t tmp_psize = 0;
+
+ /* Check the parameters */
+ assert_param(IS_VOLTAGERANGE(VoltageRange));
+ assert_param(IS_FLASH_BANK(Banks));
+
+ /* If the previous operation is completed, proceed to erase all sectors */
+ FLASH->CR &= CR_PSIZE_MASK;
+ FLASH->CR |= tmp_psize;
+ FLASH->CR |= FLASH_CR_MER;
+ FLASH->CR |= FLASH_CR_STRT;
+}
+
+/**
+ * @brief Erase the specified FLASH memory sector
+ * @param Sector: FLASH sector to erase
+ * The value of this parameter depend on device used within the same series
+ * @param VoltageRange: The device voltage range which defines the erase parallelism.
+ * This parameter can be one of the following values:
+ * @arg VOLTAGE_RANGE_1: when the device voltage range is 1.8V to 2.1V,
+ * the operation will be done by byte (8-bit)
+ * @arg VOLTAGE_RANGE_2: when the device voltage range is 2.1V to 2.7V,
+ * the operation will be done by half word (16-bit)
+ * @arg VOLTAGE_RANGE_3: when the device voltage range is 2.7V to 3.6V,
+ * the operation will be done by word (32-bit)
+ * @arg VOLTAGE_RANGE_4: when the device voltage range is 2.7V to 3.6V + External Vpp,
+ * the operation will be done by double word (64-bit)
+ *
+ * @retval None
+ */
+void FLASH_Erase_Sector(uint32_t Sector, uint8_t VoltageRange)
+{
+ uint32_t tmp_psize = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FLASH_SECTOR(Sector));
+ assert_param(IS_VOLTAGERANGE(VoltageRange));
+
+ if(VoltageRange == VOLTAGE_RANGE_1)
+ {
+ tmp_psize = FLASH_PSIZE_BYTE;
+ }
+ else if(VoltageRange == VOLTAGE_RANGE_2)
+ {
+ tmp_psize = FLASH_PSIZE_HALF_WORD;
+ }
+ else if(VoltageRange == VOLTAGE_RANGE_3)
+ {
+ tmp_psize = FLASH_PSIZE_WORD;
+ }
+ else
+ {
+ tmp_psize = FLASH_PSIZE_DOUBLE_WORD;
+ }
+
+ /* If the previous operation is completed, proceed to erase the sector */
+ FLASH->CR &= CR_PSIZE_MASK;
+ FLASH->CR |= tmp_psize;
+ FLASH->CR &= SECTOR_MASK;
+ FLASH->CR |= FLASH_CR_SER | (Sector << POSITION_VAL(FLASH_CR_SNB));
+ FLASH->CR |= FLASH_CR_STRT;
+}
+
+/**
+ * @brief Enable the write protection of the desired bank 1 sectors
+ *
+ * @note When the memory read protection level is selected (RDP level = 1),
+ * it is not possible to program or erase the flash sector i if CortexM4
+ * debug features are connected or boot code is executed in RAM, even if nWRPi = 1
+ * @note Active value of nWRPi bits is inverted when PCROP mode is active (SPRMOD =1).
+ *
+ * @param WRPSector: specifies the sector(s) to be write protected.
+ * The value of this parameter depend on device used within the same series
+ *
+ * @param Banks: Enable write protection on all the sectors for the specific bank
+ * This parameter can be one of the following values:
+ * @arg FLASH_BANK_1: WRP on all sectors of bank1
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WRPSector, uint32_t Banks)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_OB_WRP_SECTOR(WRPSector));
+ assert_param(IS_FLASH_BANK(Banks));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS &= (~WRPSector);
+ }
+
+ return status;
+}
+
+/**
+ * @brief Disable the write protection of the desired bank 1 sectors
+ *
+ * @note When the memory read protection level is selected (RDP level = 1),
+ * it is not possible to program or erase the flash sector i if CortexM4
+ * debug features are connected or boot code is executed in RAM, even if nWRPi = 1
+ * @note Active value of nWRPi bits is inverted when PCROP mode is active (SPRMOD =1).
+ *
+ * @param WRPSector: specifies the sector(s) to be write protected.
+ * The value of this parameter depend on device used within the same series
+ *
+ * @param Banks: Enable write protection on all the sectors for the specific bank
+ * This parameter can be one of the following values:
+ * @arg FLASH_BANK_1: WRP on all sectors of bank1
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WRPSector, uint32_t Banks)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_OB_WRP_SECTOR(WRPSector));
+ assert_param(IS_FLASH_BANK(Banks));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS |= (uint16_t)WRPSector;
+ }
+
+ return status;
+}
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE */
+
+#if defined(STM32F401xC) || defined(STM32F401xE)
+/**
+ * @brief Enable the read/write protection (PCROP) of the desired sectors.
+ * @note This function can be used only for STM32F401xx devices.
+ * @param Sector specifies the sector(s) to be read/write protected or unprotected.
+ * This parameter can be one of the following values:
+ * @arg OB_PCROP: A value between OB_PCROP_Sector0 and OB_PCROP_Sector5
+ * @arg OB_PCROP_Sector_All
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static HAL_StatusTypeDef FLASH_OB_EnablePCROP(uint32_t Sector)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_OB_PCROP(Sector));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS |= (uint16_t)Sector;
+ }
+
+ return status;
+}
+
+
+/**
+ * @brief Disable the read/write protection (PCROP) of the desired sectors.
+ * @note This function can be used only for STM32F401xx devices.
+ * @param Sector specifies the sector(s) to be read/write protected or unprotected.
+ * This parameter can be one of the following values:
+ * @arg OB_PCROP: A value between OB_PCROP_Sector0 and OB_PCROP_Sector5
+ * @arg OB_PCROP_Sector_All
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static HAL_StatusTypeDef FLASH_OB_DisablePCROP(uint32_t Sector)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_OB_PCROP(Sector));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ *(__IO uint16_t*)OPTCR_BYTE2_ADDRESS &= (~Sector);
+ }
+
+ return status;
+
+}
+#endif /* STM32F401xC || STM32F401xE */
+
+/**
+ * @brief Set the read protection level.
+ * @param Level: specifies the read protection level.
+ * This parameter can be one of the following values:
+ * @arg OB_RDP_LEVEL_0: No protection
+ * @arg OB_RDP_LEVEL_1: Read protection of the memory
+ * @arg OB_RDP_LEVEL_2: Full chip protection
+ *
+ * @note WARNING: When enabling OB_RDP level 2 it's no more possible to go back to level 1 or 0
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static HAL_StatusTypeDef FLASH_OB_RDP_LevelConfig(uint8_t Level)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_OB_RDP_LEVEL(Level));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ *(__IO uint8_t*)OPTCR_BYTE1_ADDRESS = Level;
+ }
+
+ return status;
+}
+
+/**
+ * @brief Program the FLASH User Option Byte: IWDG_SW / RST_STOP / RST_STDBY.
+ * @param Iwdg: Selects the IWDG mode
+ * This parameter can be one of the following values:
+ * @arg OB_IWDG_SW: Software IWDG selected
+ * @arg OB_IWDG_HW: Hardware IWDG selected
+ * @param Stop: Reset event when entering STOP mode.
+ * This parameter can be one of the following values:
+ * @arg OB_STOP_NO_RST: No reset generated when entering in STOP
+ * @arg OB_STOP_RST: Reset generated when entering in STOP
+ * @param Stdby: Reset event when entering Standby mode.
+ * This parameter can be one of the following values:
+ * @arg OB_STDBY_NO_RST: No reset generated when entering in STANDBY
+ * @arg OB_STDBY_RST: Reset generated when entering in STANDBY
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t Iwdg, uint8_t Stop, uint8_t Stdby)
+{
+ uint8_t optiontmp = 0xFF;
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the parameters */
+ assert_param(IS_OB_IWDG_SOURCE(Iwdg));
+ assert_param(IS_OB_STOP_SOURCE(Stop));
+ assert_param(IS_OB_STDBY_SOURCE(Stdby));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
+
+ if(status == HAL_OK)
+ {
+ /* Mask OPTLOCK, OPTSTRT, BOR_LEV and BFB2 bits */
+ optiontmp = (uint8_t)((*(__IO uint8_t *)OPTCR_BYTE0_ADDRESS) & (uint8_t)0x1F);
+
+ /* Update User Option Byte */
+ *(__IO uint8_t *)OPTCR_BYTE0_ADDRESS = Iwdg | (uint8_t)(Stdby | (uint8_t)(Stop | ((uint8_t)optiontmp)));
+ }
+
+ return status;
+
+}
+
+/**
+ * @brief Set the BOR Level.
+ * @param Level: specifies the Option Bytes BOR Reset Level.
+ * This parameter can be one of the following values:
+ * @arg OB_BOR_LEVEL3: Supply voltage ranges from 2.7 to 3.6 V
+ * @arg OB_BOR_LEVEL2: Supply voltage ranges from 2.4 to 2.7 V
+ * @arg OB_BOR_LEVEL1: Supply voltage ranges from 2.1 to 2.4 V
+ * @arg OB_BOR_OFF: Supply voltage ranges from 1.62 to 2.1 V
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+static HAL_StatusTypeDef FLASH_OB_BOR_LevelConfig(uint8_t Level)
+{
+ /* Check the parameters */
+ assert_param(IS_OB_BOR_LEVEL(Level));
+
+ /* Set the BOR Level */
+ *(__IO uint8_t *)OPTCR_BYTE0_ADDRESS &= (~FLASH_OPTCR_BOR_LEV);
+ *(__IO uint8_t *)OPTCR_BYTE0_ADDRESS |= Level;
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Return the FLASH User Option Byte value.
+ * @param None
+ * @retval uint8_t FLASH User Option Bytes values: IWDG_SW(Bit0), RST_STOP(Bit1)
+ * and RST_STDBY(Bit2).
+ */
+static uint8_t FLASH_OB_GetUser(void)
+{
+ /* Return the User Option Byte */
+ return ((uint8_t)(FLASH->OPTCR & 0xE0));
+}
+
+/**
+ * @brief Return the FLASH Write Protection Option Bytes value.
+ * @param None
+ * @retval uint16_t FLASH Write Protection Option Bytes value
+ */
+static uint16_t FLASH_OB_GetWRP(void)
+{
+ /* Return the FLASH write protection Register value */
+ return (*(__IO uint16_t *)(OPTCR_BYTE2_ADDRESS));
+}
+
+/**
+ * @brief Returns the FLASH Read Protection level.
+ * @param None
+ * @retval FlagStatus FLASH ReadOut Protection Status:
+ * - SET, when OB_RDP_Level_1 or OB_RDP_Level_2 is set
+ * - RESET, when OB_RDP_Level_0 is set
+ */
+static FlagStatus FLASH_OB_GetRDP(void)
+{
+ FlagStatus readstatus = RESET;
+
+ if ((*(__IO uint8_t*)(OPTCR_BYTE1_ADDRESS) != (uint8_t)OB_RDP_LEVEL_0))
+ {
+ readstatus = SET;
+ }
+
+ return readstatus;
+}
+
+/**
+ * @brief Returns the FLASH BOR level.
+ * @param None
+ * @retval uint8_t The FLASH BOR level:
+ * - OB_BOR_LEVEL3: Supply voltage ranges from 2.7 to 3.6 V
+ * - OB_BOR_LEVEL2: Supply voltage ranges from 2.4 to 2.7 V
+ * - OB_BOR_LEVEL1: Supply voltage ranges from 2.1 to 2.4 V
+ * - OB_BOR_OFF : Supply voltage ranges from 1.62 to 2.1 V
+ */
+static uint8_t FLASH_OB_GetBOR(void)
+{
+ /* Return the FLASH BOR level */
+ return (uint8_t)(*(__IO uint8_t *)(OPTCR_BYTE0_ADDRESS) & (uint8_t)0x0C);
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_FLASH_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_gpio.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_gpio.c
new file mode 100644
index 0000000..65080d7
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_gpio.c
@@ -0,0 +1,479 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_gpio.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief GPIO HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the General Purpose Input/Output (GPIO) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### GPIO Peripheral features #####
+ ==============================================================================
+ [..]
+ (+) Each port bit of the general-purpose I/O (GPIO) ports can be individually
+ configured by software in several modes:
+ (++) Input mode
+ (++) Analog mode
+ (++) Output mode
+ (++) Alternate function mode
+ (++) External interrupt/event lines
+
+ (+) During and just after reset, the alternate functions and external interrupt
+ lines are not active and the I/O ports are configured in input floating mode.
+
+ (+) All GPIO pins have weak internal pull-up and pull-down resistors, which can be
+ activated or not.
+
+ (+) In Output or Alternate mode, each IO can be configured on open-drain or push-pull
+ type and the IO speed can be selected depending on the VDD value.
+
+ (+) The microcontroller IO pins are connected to onboard peripherals/modules through a
+ multiplexer that allows only one peripheral alternate function (AF) connected
+ to an IO pin at a time. In this way, there can be no conflict between peripherals
+ sharing the same IO pin.
+
+ (+) All ports have external interrupt/event capability. To use external interrupt
+ lines, the port must be configured in input mode. All available GPIO pins are
+ connected to the 16 external interrupt/event lines from EXTI0 to EXTI15.
+
+ (+) The external interrupt/event controller consists of up to 23 edge detectors
+ (16 lines are connected to GPIO) for generating event/interrupt requests (each
+ input line can be independently configured to select the type (interrupt or event)
+ and the corresponding trigger event (rising or falling or both). Each line can
+ also be masked independently.
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#) Enable the GPIO AHB clock using the following function: __GPIOx_CLK_ENABLE().
+
+ (#) Configure the GPIO pin(s) using HAL_GPIO_Init().
+ (++) Configure the IO mode using "Mode" member from GPIO_InitTypeDef structure
+ (++) Activate Pull-up, Pull-down resistor using "Pull" member from GPIO_InitTypeDef
+ structure.
+ (++) In case of Output or alternate function mode selection: the speed is
+ configured through "Speed" member from GPIO_InitTypeDef structure.
+ (++) In alternate mode is selection, the alternate function connected to the IO
+ is configured through "Alternate" member from GPIO_InitTypeDef structure.
+ (++) Analog mode is required when a pin is to be used as ADC channel
+ or DAC output.
+ (++) In case of external interrupt/event selection the "Mode" member from
+ GPIO_InitTypeDef structure select the type (interrupt or event) and
+ the corresponding trigger event (rising or falling or both).
+
+ (#) In case of external interrupt/event mode selection, configure NVIC IRQ priority
+ mapped to the EXTI line using HAL_NVIC_SetPriority() and enable it using
+ HAL_NVIC_EnableIRQ().
+
+ (#) To get the level of a pin configured in input mode use HAL_GPIO_ReadPin().
+
+ (#) To set/reset the level of a pin configured in output mode use
+ HAL_GPIO_WritePin()/HAL_GPIO_TogglePin().
+
+ (#) During and just after reset, the alternate functions are not
+ active and the GPIO pins are configured in input floating mode (except JTAG
+ pins).
+
+ (#) The LSE oscillator pins OSC32_IN and OSC32_OUT can be used as general purpose
+ (PC14 and PC15, respectively) when the LSE oscillator is off. The LSE has
+ priority over the GPIO function.
+
+ (#) The HSE oscillator pins OSC_IN/OSC_OUT can be used as
+ general purpose PH0 and PH1, respectively, when the HSE oscillator is off.
+ The HSE has priority over the GPIO function.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup GPIO
+ * @brief GPIO HAL module driver
+ * @{
+ */
+
+#ifdef HAL_GPIO_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+#define __HAL_GET_GPIO_SOURCE(__GPIOx__) \
+(((uint32_t)(__GPIOx__) == ((uint32_t)GPIOA_BASE))? (uint32_t)0 :\
+ ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0400)))? (uint32_t)1 :\
+ ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0800)))? (uint32_t)2 :\
+ ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0C00)))? (uint32_t)3 :\
+ ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x1000)))? (uint32_t)4 :\
+ ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x1400)))? (uint32_t)5 :\
+ ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x1800)))? (uint32_t)6 :\
+ ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x1C00)))? (uint32_t)7 :\
+ ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x2000)))? (uint32_t)8 :\
+ ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x2400)))? (uint32_t)9 : (uint32_t)10)
+
+#define GPIO_MODE ((uint32_t)0x00000003)
+#define EXTI_MODE ((uint32_t)0x10000000)
+#define GPIO_MODE_IT ((uint32_t)0x00010000)
+#define GPIO_MODE_EVT ((uint32_t)0x00020000)
+#define RISING_EDGE ((uint32_t)0x00100000)
+#define FALLING_EDGE ((uint32_t)0x00200000)
+#define GPIO_OUTPUT_TYPE ((uint32_t)0x00000010)
+
+#define GPIO_NUMBER ((uint32_t)16)
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup GPIO_Private_Functions
+ * @{
+ */
+
+/** @defgroup GPIO_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the GPIOx peripheral according to the specified parameters in the GPIO_Init.
+ * @param GPIOx: where x can be (A..K) to select the GPIO peripheral for STM32F429X device or
+ * x can be (A..I) to select the GPIO peripheral for STM32F40XX and STM32F427X devices.
+ * @param GPIO_Init: pointer to a GPIO_InitTypeDef structure that contains
+ * the configuration information for the specified GPIO peripheral.
+ * @retval None
+ */
+void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init)
+{
+ uint32_t position;
+ uint32_t ioposition = 0x00;
+ uint32_t iocurrent = 0x00;
+ uint32_t temp = 0x00;
+
+ /* Check the parameters */
+ assert_param(IS_GPIO_PIN(GPIO_Init->Pin));
+ assert_param(IS_GPIO_MODE(GPIO_Init->Mode));
+ assert_param(IS_GPIO_PULL(GPIO_Init->Pull));
+
+ /* Configure the port pins */
+ for(position = 0; position < GPIO_NUMBER; position++)
+ {
+ /* Get the IO position */
+ ioposition = ((uint32_t)0x01) << position;
+ /* Get the current IO position */
+ iocurrent = (uint32_t)(GPIO_Init->Pin) & ioposition;
+
+ if(iocurrent == ioposition)
+ {
+ /*--------------------- GPIO Mode Configuration ------------------------*/
+ /* In case of Alternate function mode selection */
+ if((GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_OD))
+ {
+ /* Check the Alternate function parameter */
+ assert_param(IS_GPIO_AF(GPIO_Init->Alternate));
+ /* Configure Alternate function mapped with the current IO */
+ temp = ((uint32_t)(GPIO_Init->Alternate) << (((uint32_t)position & (uint32_t)0x07) * 4)) ;
+ GPIOx->AFR[position >> 3] &= ~((uint32_t)0xF << ((uint32_t)(position & (uint32_t)0x07) * 4)) ;
+ GPIOx->AFR[position >> 3] |= temp;
+ }
+
+ /* Configure IO Direction mode (Input, Output, Alternate or Analog) */
+ GPIOx->MODER &= ~(GPIO_MODER_MODER0 << (position * 2));
+ GPIOx->MODER |= ((GPIO_Init->Mode & GPIO_MODE) << (position * 2));
+
+ /* In case of Output or Alternate function mode selection */
+ if((GPIO_Init->Mode == GPIO_MODE_OUTPUT_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_PP) ||
+ (GPIO_Init->Mode == GPIO_MODE_OUTPUT_OD) || (GPIO_Init->Mode == GPIO_MODE_AF_OD))
+ {
+ /* Check the Speed parameter */
+ assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
+ /* Configure the IO Speed */
+ GPIOx->OSPEEDR &= ~(GPIO_OSPEEDER_OSPEEDR0 << (position * 2));
+ GPIOx->OSPEEDR |= (GPIO_Init->Speed << (position * 2));
+
+ /* Configure the IO Output Type */
+ GPIOx->OTYPER &= ~(GPIO_OTYPER_OT_0 << position) ;
+ GPIOx->OTYPER |= (((GPIO_Init->Mode & GPIO_OUTPUT_TYPE) >> 4) << position);
+ }
+
+ /* Activate the Pull-up or Pull down resistor for the current IO */
+ GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPDR0 << (position * 2));
+ GPIOx->PUPDR |= ((GPIO_Init->Pull) << (position * 2));
+
+
+ /*--------------------- EXTI Mode Configuration ------------------------*/
+ /* Configure the External Interrupt or event for the current IO */
+ if((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE)
+ {
+ /* Enable SYSCFG Clock */
+ __SYSCFG_CLK_ENABLE();
+
+ temp = ((uint32_t)0x0F) << (4 * (position & 0x03));
+ SYSCFG->EXTICR[position >> 2] &= ~temp;
+ SYSCFG->EXTICR[position >> 2] |= ((uint32_t)(__HAL_GET_GPIO_SOURCE(GPIOx)) << (4 * (position & 0x03)));
+
+ /* Clear EXTI line configuration */
+ EXTI->IMR &= ~((uint32_t)iocurrent);
+ EXTI->EMR &= ~((uint32_t)iocurrent);
+
+ if((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT)
+ {
+ EXTI->IMR |= iocurrent;
+ }
+ if((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT)
+ {
+ EXTI->EMR |= iocurrent;
+ }
+
+ /* Clear Rising Falling edge configuration */
+ EXTI->RTSR &= ~((uint32_t)iocurrent);
+ EXTI->FTSR &= ~((uint32_t)iocurrent);
+
+ if((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE)
+ {
+ EXTI->RTSR |= iocurrent;
+ }
+ if((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE)
+ {
+ EXTI->FTSR |= iocurrent;
+ }
+ }
+ }
+ }
+}
+
+/**
+ * @brief De-initializes the GPIOx peripheral registers to their default reset values.
+ * @param GPIOx: where x can be (A..K) to select the GPIO peripheral for STM32F429X device or
+ * x can be (A..I) to select the GPIO peripheral for STM32F40XX and STM32F427X devices.
+ * @param GPIO_Pin: specifies the port bit to be written.
+ * This parameter can be one of GPIO_PIN_x where x can be (0..15).
+ * @retval None
+ */
+void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin)
+{
+ uint32_t position;
+ uint32_t ioposition = 0x00;
+ uint32_t iocurrent = 0x00;
+ uint32_t tmp = 0x00;
+
+ /* Configure the port pins */
+ for(position = 0; position < GPIO_NUMBER; position++)
+ {
+ /* Get the IO position */
+ ioposition = ((uint32_t)0x01) << position;
+ /* Get the current IO position */
+ iocurrent = (GPIO_Pin) & ioposition;
+
+ if(iocurrent == ioposition)
+ {
+ /*------------------------- GPIO Mode Configuration --------------------*/
+ /* Configure IO Direction in Input Floting Mode */
+ GPIOx->MODER &= ~(GPIO_MODER_MODER0 << (position * 2));
+
+ /* Configure the default Alternate Function in current IO */
+ GPIOx->AFR[position >> 3] &= ~((uint32_t)0xF << ((uint32_t)(position & (uint32_t)0x07) * 4)) ;
+
+ /* Configure the default value for IO Speed */
+ GPIOx->OSPEEDR &= ~(GPIO_OSPEEDER_OSPEEDR0 << (position * 2));
+
+ /* Configure the default value IO Output Type */
+ GPIOx->OTYPER &= ~(GPIO_OTYPER_OT_0 << position) ;
+
+ /* Deactivate the Pull-up oand Pull-down resistor for the current IO */
+ GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPDR0 << (position * 2));
+
+
+ /*------------------------- EXTI Mode Configuration --------------------*/
+ /* Configure the External Interrupt or event for the current IO */
+ tmp = ((uint32_t)0x0F) << (4 * (position & 0x03));
+ SYSCFG->EXTICR[position >> 2] &= ~tmp;
+
+ /* Clear EXTI line configuration */
+ EXTI->IMR &= ~((uint32_t)iocurrent);
+ EXTI->EMR &= ~((uint32_t)iocurrent);
+
+ /* Clear Rising Falling edge configuration */
+ EXTI->RTSR &= ~((uint32_t)iocurrent);
+ EXTI->FTSR &= ~((uint32_t)iocurrent);
+ }
+ }
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup GPIO_Group2 IO operation functions
+ * @brief GPIO Read and Write
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Reads the specified input port pin.
+ * @param GPIOx: where x can be (A..K) to select the GPIO peripheral for STM32F429X device or
+ * x can be (A..I) to select the GPIO peripheral for STM32F40XX and STM32F427X devices.
+ * @param GPIO_Pin: specifies the port bit to read.
+ * This parameter can be GPIO_PIN_x where x can be (0..15).
+ * @retval The input port pin value.
+ */
+GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
+{
+ GPIO_PinState bitstatus;
+
+ /* Check the parameters */
+ assert_param(IS_GET_GPIO_PIN(GPIO_Pin));
+
+ if((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET)
+ {
+ bitstatus = GPIO_PIN_SET;
+ }
+ else
+ {
+ bitstatus = GPIO_PIN_RESET;
+ }
+ return bitstatus;
+}
+
+/**
+ * @brief Sets or clears the selected data port bit.
+ *
+ * @note This function uses GPIOx_BSRR register to allow atomic read/modify
+ * accesses. In this way, there is no risk of an IRQ occurring between
+ * the read and the modify access.
+ *
+ * @param GPIOx: where x can be (A..K) to select the GPIO peripheral for STM32F429X device or
+ * x can be (A..I) to select the GPIO peripheral for STM32F40XX and STM32F427X devices.
+ * @param GPIO_Pin: specifies the port bit to be written.
+ * This parameter can be one of GPIO_PIN_x where x can be (0..15).
+ * @param PinState: specifies the value to be written to the selected bit.
+ * This parameter can be one of the GPIO_PinState enum values:
+ * @arg GPIO_BIT_RESET: to clear the port pin
+ * @arg GPIO_BIT_SET: to set the port pin
+ * @retval None
+ */
+void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState)
+{
+ /* Check the parameters */
+ assert_param(IS_GET_GPIO_PIN(GPIO_Pin));
+ assert_param(IS_GPIO_PIN_ACTION(PinState));
+
+ if(PinState != GPIO_PIN_RESET)
+ {
+ GPIOx->BSRRL = GPIO_Pin;
+ }
+ else
+ {
+ GPIOx->BSRRH = GPIO_Pin ;
+ }
+}
+
+/**
+ * @brief Toggles the specified GPIO pins.
+ * @param GPIOx: Where x can be (A..K) to select the GPIO peripheral for STM32F429X device or
+ * x can be (A..I) to select the GPIO peripheral for STM32F40XX and STM32F427X devices.
+ * @param GPIO_Pin: Specifies the pins to be toggled.
+ * @retval None
+ */
+void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
+{
+ /* Check the parameters */
+ assert_param(IS_GET_GPIO_PIN(GPIO_Pin));
+
+ GPIOx->ODR ^= GPIO_Pin;
+}
+
+/**
+ * @brief This function handles EXTI interrupt request.
+ * @param GPIO_Pin: Specifies the pins connected EXTI line
+ * @retval None
+ */
+void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin)
+{
+ /* EXTI line interrupt detected */
+ if(__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != RESET)
+ {
+ __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin);
+ HAL_GPIO_EXTI_Callback(GPIO_Pin);
+ }
+}
+
+/**
+ * @brief EXTI line detection callbacks.
+ * @param GPIO_Pin: Specifies the pins connected EXTI line
+ * @retval None
+ */
+__weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_GPIO_EXTI_Callback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+
+/**
+ * @}
+ */
+
+#endif /* HAL_GPIO_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hash.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hash.c
new file mode 100644
index 0000000..95d6478
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hash.c
@@ -0,0 +1,1812 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_hash.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief HASH HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the HASH peripheral:
+ * + Initialization and de-initialization functions
+ * + HASH/HMAC Processing functions by algorithm using polling mode
+ * + HASH/HMAC functions by algorithm using interrupt mode
+ * + HASH/HMAC functions by algorithm using DMA mode
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The HASH HAL driver can be used as follows:
+ (#)Initialize the HASH low level resources by implementing the HAL_HASH_MspInit():
+ (##) Enable the HASH interface clock using __HASH_CLK_ENABLE()
+ (##) In case of using processing APIs based on interrupts (e.g. HAL_HMAC_SHA1_Start_IT())
+ (+++) Configure the HASH interrupt priority using HAL_NVIC_SetPriority()
+ (+++) Enable the HASH IRQ handler using HAL_NVIC_EnableIRQ()
+ (+++) In HASH IRQ handler, call HAL_HASH_IRQHandler()
+ (##) In case of using DMA to control data transfer (e.g. HAL_HMAC_SHA1_Start_DMA())
+ (+++) Enable the DMAx interface clock using __DMAx_CLK_ENABLE()
+ (+++) Configure and enable one DMA stream one for managing data transfer from
+ memory to peripheral (input stream). Managing data transfer from
+ peripheral to memory can be performed only using CPU
+ (+++) Associate the initialized DMA handle to the HASH DMA handle
+ using __HAL_LINKDMA()
+ (+++) Configure the priority and enable the NVIC for the transfer complete
+ interrupt on the DMA Stream using HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ()
+ (#)Initialize the HASH HAL using HAL_HASH_Init(). This function configures mainly:
+ (##) The data type: 1-bit, 8-bit, 16-bit and 32-bit.
+ (##) For HMAC, the encryption key.
+ (##) For HMAC, the key size used for encryption.
+ (#)Three processing functions are available:
+ (##) Polling mode: processing APIs are blocking functions
+ i.e. they process the data and wait till the digest computation is finished
+ e.g. HAL_HASH_SHA1_Start()
+ (##) Interrupt mode: encryption and decryption APIs are not blocking functions
+ i.e. they process the data under interrupt
+ e.g. HAL_HASH_SHA1_Start_IT()
+ (##) DMA mode: processing APIs are not blocking functions and the CPU is
+ not used for data transfer i.e. the data transfer is ensured by DMA
+ e.g. HAL_HASH_SHA1_Start_DMA()
+ (#)When the processing function is called at first time after HAL_HASH_Init()
+ the HASH peripheral is initialized and processes the buffer in input.
+ After that, the digest computation is started.
+ When processing multi-buffer use the accumulate function to write the
+ data in the peripheral without starting the digest computation. In last
+ buffer use the start function to input the last buffer ans start the digest
+ computation.
+ (##) e.g. HAL_HASH_SHA1_Accumulate() : write 1st data buffer in the peripheral without starting the digest computation
+ (##) write (n-1)th data buffer in the peripheral without starting the digest computation
+ (##) HAL_HASH_SHA1_Start() : write (n)th data buffer in the peripheral and start the digest computation
+ (#)In HMAC mode, there is no Accumulate API. Only Start API is available.
+ (#)In case of using DMA, call the DMA start processing e.g. HAL_HASH_SHA1_Start_DMA().
+ After that, call the finish function in order to get the digest value
+ e.g. HAL_HASH_SHA1_Finish()
+ (#)Call HAL_HASH_DeInit() to deinitialize the HASH peripheral.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup HASH
+ * @brief HASH HAL module driver.
+ * @{
+ */
+
+#ifdef HAL_HASH_MODULE_ENABLED
+
+#if defined(STM32F415xx) || defined(STM32F417xx) || defined(STM32F437xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void HASH_DMAXferCplt(DMA_HandleTypeDef *hdma);
+static void HASH_DMAError(DMA_HandleTypeDef *hdma);
+static void HASH_GetDigest(uint8_t *pMsgDigest, uint8_t Size);
+static void HASH_WriteData(uint8_t *pInBuffer, uint32_t Size);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup HASH_Private_Functions
+ * @{
+ */
+
+/** @defgroup HASH_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions.
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize the HASH according to the specified parameters
+ in the HASH_InitTypeDef and creates the associated handle.
+ (+) DeInitialize the HASH peripheral.
+ (+) Initialize the HASH MSP.
+ (+) DeInitialize HASH MSP.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH according to the specified parameters in the
+ HASH_HandleTypeDef and creates the associated handle.
+ * @param hhash: HASH handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_Init(HASH_HandleTypeDef *hhash)
+{
+ /* Check the hash handle allocation */
+ if(hhash == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_HASH_DATATYPE(hhash->Init.DataType));
+
+ if(hhash->State == HAL_HASH_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_HASH_MspInit(hhash);
+ }
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Reset HashInCount, HashBuffSize and HashITCounter */
+ hhash->HashInCount = 0;
+ hhash->HashBuffSize = 0;
+ hhash->HashITCounter = 0;
+
+ /* Set the data type */
+ HASH->CR |= (uint32_t) (hhash->Init.DataType);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Set the default HASH phase */
+ hhash->Phase = HAL_HASH_PHASE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the HASH peripheral.
+ * @note This API must be called before starting a new processing.
+ * @param hhash: HASH handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_DeInit(HASH_HandleTypeDef *hhash)
+{
+ /* Check the HASH handle allocation */
+ if(hhash == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Set the default HASH phase */
+ hhash->Phase = HAL_HASH_PHASE_READY;
+
+ /* Reset HashInCount, HashBuffSize and HashITCounter */
+ hhash->HashInCount = 0;
+ hhash->HashBuffSize = 0;
+ hhash->HashITCounter = 0;
+
+ /* DeInit the low level hardware */
+ HAL_HASH_MspDeInit(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH MSP.
+ * @param hhash: HASH handle
+ * @retval None
+ */
+__weak void HAL_HASH_MspInit(HASH_HandleTypeDef *hhash)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_HASH_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes HASH MSP.
+ * @param hhash: HASH handle
+ * @retval None
+ */
+__weak void HAL_HASH_MspDeInit(HASH_HandleTypeDef *hhash)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_HASH_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Input data transfer complete callback.
+ * @param hhash: HASH handle
+ * @retval None
+ */
+ __weak void HAL_HASH_InCpltCallback(HASH_HandleTypeDef *hhash)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_HASH_InCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Data transfer Error callback.
+ * @param hhash: HASH handle
+ * @retval None
+ */
+ __weak void HAL_HASH_ErrorCallback(HASH_HandleTypeDef *hhash)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_HASH_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Digest computation complete callback. It is used only with interrupt.
+ * @note This callback is not relevant with DMA.
+ * @param hhash: HASH handle
+ * @retval None
+ */
+ __weak void HAL_HASH_DgstCpltCallback(HASH_HandleTypeDef *hhash)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_HASH_DgstCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HASH_Group2 HASH processing functions using polling mode
+ * @brief processing functions using polling mode
+ *
+@verbatim
+ ===============================================================================
+ ##### HASH processing using polling mode functions#####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in polling mode
+ the hash value using one of the following algorithms:
+ (+) MD5
+ (+) SHA1
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH peripheral in MD5 mode then processes pInBuffer.
+ The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param pOutBuffer: Pointer to the Output buffer (hashed buffer).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is multiple of 64 bytes, appending the input buffer is possible.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware
+ * and appending the input buffer is no more possible.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 16 bytes.
+ * @param Timeout: Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the MD5 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_MD5 | HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(pInBuffer, Size);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(HASH->SR, HASH_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the message digest */
+ HASH_GetDigest(pOutBuffer, 16);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in MD5 mode then writes the pInBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is multiple of 64 bytes, appending the input buffer is possible.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware
+ * and appending the input buffer is no more possible.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_MD5_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the MD5 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_MD5 | HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(pInBuffer, Size);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in SHA1 mode then processes pInBuffer.
+ The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param pOutBuffer: Pointer to the Output buffer (hashed buffer).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @param Timeout: Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA1 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_SHA1 | HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(pInBuffer, Size);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(HASH->SR, HASH_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the message digest */
+ HASH_GetDigest(pOutBuffer, 20);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in SHA1 mode then processes pInBuffer.
+ The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_SHA1_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA1 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_SHA1 | HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(pInBuffer, Size);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HASH_Group3 HASH processing functions using interrupt mode
+ * @brief processing functions using interrupt mode.
+ *
+@verbatim
+ ===============================================================================
+ ##### HASH processing using interrupt mode functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in interrupt mode
+ the hash value using one of the following algorithms:
+ (+) MD5
+ (+) SHA1
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH peripheral in MD5 mode then processes pInBuffer.
+ * The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param pOutBuffer: Pointer to the Output buffer (hashed buffer).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 16 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+ uint32_t buffercounter;
+ uint32_t inputcounter;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ if(hhash->HashITCounter == 0)
+ {
+ hhash->HashITCounter = 1;
+ }
+ else
+ {
+ hhash->HashITCounter = 0;
+ }
+ if(hhash->State == HAL_HASH_STATE_READY)
+ {
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ hhash->HashInCount = Size;
+ hhash->pHashInBuffPtr = pInBuffer;
+ hhash->pHashOutBuffPtr = pOutBuffer;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA1 mode */
+ HASH->CR |= HASH_AlgoSelection_MD5;
+ /* Reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Enable Interrupts */
+ HASH->IMR = (HASH_IT_DINI | HASH_IT_DCI);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ if(__HAL_HASH_GET_FLAG(HASH_FLAG_DCIS))
+ {
+ outputaddr = (uint32_t)hhash->pHashOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = __REV(HASH->HR[0]);
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = __REV(HASH->HR[1]);
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = __REV(HASH->HR[2]);
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = __REV(HASH->HR[3]);
+
+ if(hhash->HashInCount == 0)
+ {
+ /* Disable Interrupts */
+ HASH->IMR = 0;
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+ /* Call digest computation complete callback */
+ HAL_HASH_DgstCpltCallback(hhash);
+ }
+ }
+ if(__HAL_HASH_GET_FLAG(HASH_FLAG_DINIS))
+ {
+ if(hhash->HashInCount > 64)
+ {
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ /* Write the Input block in the Data IN register */
+ for(buffercounter = 0; buffercounter < 64; buffercounter+=4)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ }
+ if(hhash->HashITCounter == 0)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+
+ if(hhash->HashInCount >= 68)
+ {
+ /* Decrement buffer counter */
+ hhash->HashInCount -= 68;
+ hhash->pHashInBuffPtr+= 68;
+ }
+ else
+ {
+ hhash->HashInCount -= 64;
+ }
+ }
+ else
+ {
+ /* Decrement buffer counter */
+ hhash->HashInCount -= 64;
+ hhash->pHashInBuffPtr+= 64;
+ }
+ }
+ else
+ {
+ /* Get the buffer address */
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ /* Get the buffer counter */
+ inputcounter = hhash->HashInCount;
+ /* Disable Interrupts */
+ HASH->IMR &= ~(HASH_IT_DINI);
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(inputcounter);
+
+ if((inputcounter > 4) && (inputcounter%4))
+ {
+ inputcounter = (inputcounter+4-inputcounter%4);
+ }
+
+ /* Write the Input block in the Data IN register */
+ for(buffercounter = 0; buffercounter < inputcounter/4; buffercounter++)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ inputaddr+=4;
+ }
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+ /* Reset buffer counter */
+ hhash->HashInCount = 0;
+ }
+ /* Call Input data transfer complete callback */
+ HAL_HASH_InCpltCallback(hhash);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in SHA1 mode then processes pInBuffer.
+ * The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param pOutBuffer: Pointer to the Output buffer (hashed buffer).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer)
+{
+ uint32_t inputaddr;
+ uint32_t outputaddr;
+ uint32_t buffercounter;
+ uint32_t inputcounter;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ if(hhash->HashITCounter == 0)
+ {
+ hhash->HashITCounter = 1;
+ }
+ else
+ {
+ hhash->HashITCounter = 0;
+ }
+ if(hhash->State == HAL_HASH_STATE_READY)
+ {
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ hhash->HashInCount = Size;
+ hhash->pHashInBuffPtr = pInBuffer;
+ hhash->pHashOutBuffPtr = pOutBuffer;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA1 mode */
+ HASH->CR |= HASH_AlgoSelection_SHA1;
+ /* Reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Enable Interrupts */
+ HASH->IMR = (HASH_IT_DINI | HASH_IT_DCI);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ if(__HAL_HASH_GET_FLAG(HASH_FLAG_DCIS))
+ {
+ outputaddr = (uint32_t)hhash->pHashOutBuffPtr;
+ /* Read the Output block from the Output FIFO */
+ *(uint32_t*)(outputaddr) = __REV(HASH->HR[0]);
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = __REV(HASH->HR[1]);
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = __REV(HASH->HR[2]);
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = __REV(HASH->HR[3]);
+ outputaddr+=4;
+ *(uint32_t*)(outputaddr) = __REV(HASH->HR[4]);
+ if(hhash->HashInCount == 0)
+ {
+ /* Disable Interrupts */
+ HASH->IMR = 0;
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+ /* Call digest computation complete callback */
+ HAL_HASH_DgstCpltCallback(hhash);
+ }
+ }
+ if(__HAL_HASH_GET_FLAG(HASH_FLAG_DINIS))
+ {
+ if(hhash->HashInCount > 64)
+ {
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ /* Write the Input block in the Data IN register */
+ for(buffercounter = 0; buffercounter < 64; buffercounter+=4)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ inputaddr+=4;
+ }
+ if(hhash->HashITCounter == 0)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+
+ if(hhash->HashInCount >= 68)
+ {
+ /* Decrement buffer counter */
+ hhash->HashInCount -= 68;
+ hhash->pHashInBuffPtr+= 68;
+ }
+ else
+ {
+ hhash->HashInCount -= 64;
+ }
+ }
+ else
+ {
+ /* Decrement buffer counter */
+ hhash->HashInCount -= 64;
+ hhash->pHashInBuffPtr+= 64;
+ }
+ }
+ else
+ {
+ /* Get the buffer address */
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ /* Get the buffer counter */
+ inputcounter = hhash->HashInCount;
+ /* Disable Interrupts */
+ HASH->IMR &= ~(HASH_IT_DINI);
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(inputcounter);
+
+ if((inputcounter > 4) && (inputcounter%4))
+ {
+ inputcounter = (inputcounter+4-inputcounter%4);
+ }
+
+ /* Write the Input block in the Data IN register */
+ for(buffercounter = 0; buffercounter < inputcounter/4; buffercounter++)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ inputaddr+=4;
+ }
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+ /* Reset buffer counter */
+ hhash->HashInCount = 0;
+ }
+ /* Call Input data transfer complete callback */
+ HAL_HASH_InCpltCallback(hhash);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles HASH interrupt request.
+ * @param hhash: hash handle
+ * @retval None
+ */
+void HAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash)
+{
+ switch(HASH->CR & HASH_CR_ALGO)
+ {
+ case HASH_AlgoSelection_MD5:
+ HAL_HASH_MD5_Start_IT(hhash, NULL, 0, NULL);
+ break;
+
+ case HASH_AlgoSelection_SHA1:
+ HAL_HASH_SHA1_Start_IT(hhash, NULL, 0, NULL);
+ break;
+
+ default:
+ break;
+ }
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HASH_Group4 HASH processing functions using DMA mode
+ * @brief processing functions using DMA mode.
+ *
+@verbatim
+ ===============================================================================
+ ##### HASH processing using DMA mode functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in DMA mode
+ the hash value using one of the following algorithms:
+ (+) MD5
+ (+) SHA1
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH peripheral in MD5 mode then enables DMA to
+ control data transfer. Use HAL_HASH_MD5_Finish() to get the digest.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 16 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t inputaddr = (uint32_t)pInBuffer;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the MD5 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_MD5 | HASH_CR_INIT;
+ }
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Set the HASH DMA transfer complete callback */
+ hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt;
+ /* Set the DMA error callback */
+ hhash->hdmain->XferErrorCallback = HASH_DMAError;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (Size%4 ? (Size+3)/4:Size/4));
+
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Returns the computed digest in MD5 mode
+ * @param hhash: HASH handle
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 16 bytes.
+ * @param Timeout: Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_MD5_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(HASH->SR, HASH_FLAG_DCIS))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the message digest */
+ HASH_GetDigest(pOutBuffer, 16);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in SHA1 mode then enables DMA to
+ control data transfer. Use HAL_HASH_SHA1_Finish() to get the digest.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t inputaddr = (uint32_t)pInBuffer;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA1 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_SHA1;
+ HASH->CR |= HASH_CR_INIT;
+ }
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Set the HASH DMA transfer complete callback */
+ hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt;
+ /* Set the DMA error callback */
+ hhash->hdmain->XferErrorCallback = HASH_DMAError;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (Size%4 ? (Size+3)/4:Size/4));
+
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Returns the computed digest in SHA1 mode.
+ * @param hhash: HASH handle
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @param Timeout: Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASH_SHA1_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+ while(HAL_IS_BIT_CLR(HASH->SR, HASH_FLAG_DCIS))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the message digest */
+ HASH_GetDigest(pOutBuffer, 20);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process UnLock */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+
+/**
+ * @}
+ */
+
+/** @defgroup HASH_Group5 HASH-MAC (HMAC) processing functions using polling mode
+ * @brief HMAC processing functions using polling mode .
+ *
+@verbatim
+ ===============================================================================
+ ##### HMAC processing using polling mode functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in polling mode
+ the HMAC value using one of the following algorithms:
+ (+) MD5
+ (+) SHA1
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH peripheral in HMAC MD5 mode
+ * then processes pInBuffer. The digest is available in pOutBuffer
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @param Timeout: Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Check if key size is greater than 64 bytes */
+ if(hhash->Init.KeySize > 64)
+ {
+ /* Select the HMAC MD5 mode */
+ HASH->CR |= (HASH_AlgoSelection_MD5 | HASH_AlgoMode_HMAC | HASH_HMACKeyType_LongKey | HASH_CR_INIT);
+ }
+ else
+ {
+ /* Select the HMAC MD5 mode */
+ HASH->CR |= (HASH_AlgoSelection_MD5 | HASH_AlgoMode_HMAC | HASH_CR_INIT);
+ }
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /************************** STEP 1 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(hhash->Init.pKey, hhash->Init.KeySize);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(HASH->SR, HASH_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /************************** STEP 2 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(pInBuffer, Size);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(HASH->SR, HASH_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /************************** STEP 3 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(hhash->Init.pKey, hhash->Init.KeySize);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(HASH->SR, HASH_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the message digest */
+ HASH_GetDigest(pOutBuffer, 16);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in HMAC SHA1 mode
+ * then processes pInBuffer. The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @param Timeout: Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HMAC_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Check if key size is greater than 64 bytes */
+ if(hhash->Init.KeySize > 64)
+ {
+ /* Select the HMAC SHA1 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA1 | HASH_AlgoMode_HMAC | HASH_HMACKeyType_LongKey | HASH_CR_INIT);
+ }
+ else
+ {
+ /* Select the HMAC SHA1 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA1 | HASH_AlgoMode_HMAC | HASH_CR_INIT);
+ }
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /************************** STEP 1 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(hhash->Init.pKey, hhash->Init.KeySize);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(HASH->SR, HASH_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /************************** STEP 2 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(pInBuffer, Size);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(HASH->SR, HASH_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /************************** STEP 3 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Write input buffer in data register */
+ HASH_WriteData(hhash->Init.pKey, hhash->Init.KeySize);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_SET(HASH->SR, HASH_FLAG_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Read the message digest */
+ HASH_GetDigest(pOutBuffer, 20);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+
+
+
+/**
+ * @}
+ */
+
+/** @defgroup HASH_Group6 HASH-MAC (HMAC) processing functions using DMA mode
+ * @brief HMAC processing functions using DMA mode .
+ *
+@verbatim
+ ===============================================================================
+ ##### HMAC processing using DMA mode functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in DMA mode
+ the HMAC value using one of the following algorithms:
+ (+) MD5
+ (+) SHA1
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH peripheral in HMAC MD5 mode
+ * then enables DMA to control data transfer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t inputaddr = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Save buffer pointer and size in handle */
+ hhash->pHashInBuffPtr = pInBuffer;
+ hhash->HashBuffSize = Size;
+ hhash->HashInCount = 0;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Check if key size is greater than 64 bytes */
+ if(hhash->Init.KeySize > 64)
+ {
+ /* Select the HMAC MD5 mode */
+ HASH->CR |= (HASH_AlgoSelection_MD5 | HASH_AlgoMode_HMAC | HASH_HMACKeyType_LongKey | HASH_CR_INIT);
+ }
+ else
+ {
+ /* Select the HMAC MD5 mode */
+ HASH->CR |= (HASH_AlgoSelection_MD5 | HASH_AlgoMode_HMAC | HASH_CR_INIT);
+ }
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Get the key address */
+ inputaddr = (uint32_t)(hhash->Init.pKey);
+
+ /* Set the HASH DMA transfer complete callback */
+ hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt;
+ /* Set the DMA error callback */
+ hhash->hdmain->XferErrorCallback = HASH_DMAError;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (hhash->Init.KeySize%4 ? (hhash->Init.KeySize+3)/4:hhash->Init.KeySize/4));
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in HMAC SHA1 mode
+ * then enables DMA to control data transfer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t inputaddr = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Save buffer pointer and size in handle */
+ hhash->pHashInBuffPtr = pInBuffer;
+ hhash->HashBuffSize = Size;
+ hhash->HashInCount = 0;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Check if key size is greater than 64 bytes */
+ if(hhash->Init.KeySize > 64)
+ {
+ /* Select the HMAC SHA1 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA1 | HASH_AlgoMode_HMAC | HASH_HMACKeyType_LongKey | HASH_CR_INIT);
+ }
+ else
+ {
+ /* Select the HMAC SHA1 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA1 | HASH_AlgoMode_HMAC | HASH_CR_INIT);
+ }
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Get the key address */
+ inputaddr = (uint32_t)(hhash->Init.pKey);
+
+ /* Set the HASH DMA transfer complete callback */
+ hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt;
+ /* Set the DMA error callback */
+ hhash->hdmain->XferErrorCallback = HASH_DMAError;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (hhash->Init.KeySize%4 ? (hhash->Init.KeySize+3)/4:hhash->Init.KeySize/4));
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HASH_Group7 Peripheral State functions
+ * @brief Peripheral State functions.
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State functions #####
+ ===============================================================================
+ [..]
+ This subsection permits to get in run-time the status of the peripheral.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief return the HASH state
+ * @param hhash: HASH handle
+ * @retval HAL state
+ */
+HAL_HASH_STATETypeDef HAL_HASH_GetState(HASH_HandleTypeDef *hhash)
+{
+ return hhash->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief DMA HASH Input Data complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void HASH_DMAXferCplt(DMA_HandleTypeDef *hdma)
+{
+ HASH_HandleTypeDef* hhash = ( HASH_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ uint32_t inputaddr = 0;
+ uint32_t buffersize = 0;
+
+ if((HASH->CR & HASH_CR_MODE) != HASH_CR_MODE)
+ {
+ /* Disable the DMA transfer */
+ HASH->CR &= (uint32_t)(~HASH_CR_DMAE);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Call Input data transfer complete callback */
+ HAL_HASH_InCpltCallback(hhash);
+ }
+ else
+ {
+ /* Increment Interrupt counter */
+ hhash->HashInCount++;
+ /* Disable the DMA transfer before starting the next transfer */
+ HASH->CR &= (uint32_t)(~HASH_CR_DMAE);
+
+ if(hhash->HashInCount <= 2)
+ {
+ /* In case HashInCount = 1, set the DMA to transfer data to HASH DIN register */
+ if(hhash->HashInCount == 1)
+ {
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ buffersize = hhash->HashBuffSize;
+ }
+ /* In case HashInCount = 2, set the DMA to transfer key to HASH DIN register */
+ else if(hhash->HashInCount == 2)
+ {
+ inputaddr = (uint32_t)hhash->Init.pKey;
+ buffersize = hhash->Init.KeySize;
+ }
+ /* Configure the number of valid bits in last word of the message */
+ HASH->STR |= 8 * (buffersize % 4);
+
+ /* Set the HASH DMA transfer complete */
+ hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (buffersize%4 ? (buffersize+3)/4:buffersize/4));
+
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+ }
+ else
+ {
+ /* Disable the DMA transfer */
+ HASH->CR &= (uint32_t)(~HASH_CR_DMAE);
+
+ /* Reset the InCount */
+ hhash->HashInCount = 0;
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Call Input data transfer complete callback */
+ HAL_HASH_InCpltCallback(hhash);
+ }
+ }
+}
+
+/**
+ * @brief DMA HASH communication error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void HASH_DMAError(DMA_HandleTypeDef *hdma)
+{
+ HASH_HandleTypeDef* hhash = ( HASH_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ hhash->State= HAL_HASH_STATE_READY;
+ HAL_HASH_ErrorCallback(hhash);
+}
+
+/**
+ * @brief Writes the input buffer in data register.
+ * @param pInBuffer: Pointer to input buffer
+ * @param Size: The size of input buffer
+ * @retval None
+ */
+static void HASH_WriteData(uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t buffercounter;
+ uint32_t inputaddr = (uint32_t) pInBuffer;
+
+ for(buffercounter = 0; buffercounter < Size; buffercounter+=4)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ inputaddr+=4;
+ }
+}
+
+/**
+ * @brief Provides the message digest result.
+ * @param pMsgDigest: Pointer to the message digest
+ * @param Size: The size of the message digest in bytes
+ * @retval None
+ */
+static void HASH_GetDigest(uint8_t *pMsgDigest, uint8_t Size)
+{
+ uint32_t msgdigest = (uint32_t)pMsgDigest;
+
+ switch(Size)
+ {
+ case 16:
+ /* Read the message digest */
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[0]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[1]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[2]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[3]);
+ break;
+ case 20:
+ /* Read the message digest */
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[0]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[1]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[2]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[3]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[4]);
+ break;
+ case 28:
+ /* Read the message digest */
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[0]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[1]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[2]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[3]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[4]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[5]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[6]);
+ break;
+ case 32:
+ /* Read the message digest */
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[0]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[1]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[2]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[3]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[4]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[5]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[6]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[7]);
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * @}
+ */
+#endif /* STM32F415xx || STM32F417xx || STM32F437xx || STM32F439xx */
+#endif /* HAL_HASH_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hash_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hash_ex.c
new file mode 100644
index 0000000..4a64c23
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hash_ex.c
@@ -0,0 +1,1598 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_hash_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief HASH HAL Extension module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of HASH peripheral:
+ * + Extended HASH processing functions based on SHA224 Algorithm
+ * + Extended HASH processing functions based on SHA256 Algorithm
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The HASH HAL driver can be used as follows:
+ (#)Initialize the HASH low level resources by implementing the HAL_HASH_MspInit():
+ (##) Enable the HASH interface clock using __HASH_CLK_ENABLE()
+ (##) In case of using processing APIs based on interrupts (e.g. HAL_HMACEx_SHA224_Start())
+ (+++) Configure the HASH interrupt priority using HAL_NVIC_SetPriority()
+ (+++) Enable the HASH IRQ handler using HAL_NVIC_EnableIRQ()
+ (+++) In HASH IRQ handler, call HAL_HASH_IRQHandler()
+ (##) In case of using DMA to control data transfer (e.g. HAL_HMACEx_SH224_Start_DMA())
+ (+++) Enable the DMAx interface clock using __DMAx_CLK_ENABLE()
+ (+++) Configure and enable one DMA stream one for managing data transfer from
+ memory to peripheral (input stream). Managing data transfer from
+ peripheral to memory can be performed only using CPU
+ (+++) Associate the initialized DMA handle to the HASH DMA handle
+ using __HAL_LINKDMA()
+ (+++) Configure the priority and enable the NVIC for the transfer complete
+ interrupt on the DMA Stream: HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ()
+ (#)Initialize the HASH HAL using HAL_HASH_Init(). This function configures mainly:
+ (##) The data type: 1-bit, 8-bit, 16-bit and 32-bit.
+ (##) For HMAC, the encryption key.
+ (##) For HMAC, the key size used for encryption.
+ (#)Three processing functions are available:
+ (##) Polling mode: processing APIs are blocking functions
+ i.e. they process the data and wait till the digest computation is finished
+ e.g. HAL_HASHEx_SHA224_Start()
+ (##) Interrupt mode: encryption and decryption APIs are not blocking functions
+ i.e. they process the data under interrupt
+ e.g. HAL_HASHEx_SHA224_Start_IT()
+ (##) DMA mode: processing APIs are not blocking functions and the CPU is
+ not used for data transfer i.e. the data transfer is ensured by DMA
+ e.g. HAL_HASHEx_SHA224_Start_DMA()
+ (#)When the processing function is called at first time after HAL_HASH_Init()
+ the HASH peripheral is initialized and processes the buffer in input.
+ After that, the digest computation is started.
+ When processing multi-buffer use the accumulate function to write the
+ data in the peripheral without starting the digest computation. In last
+ buffer use the start function to input the last buffer ans start the digest
+ computation.
+ (##) e.g. HAL_HASHEx_SHA224_Accumulate() : write 1st data buffer in the peripheral without starting the digest computation
+ (##) write (n-1)th data buffer in the peripheral without starting the digest computation
+ (##) HAL_HASHEx_SHA224_Start() : write (n)th data buffer in the peripheral and start the digest computation
+ (#)In HMAC mode, there is no Accumulate API. Only Start API is available.
+ (#)In case of using DMA, call the DMA start processing e.g. HAL_HASHEx_SHA224_Start_DMA().
+ After that, call the finish function in order to get the digest value
+ e.g. HAL_HASHEx_SHA224_Finish()
+ (#)Call HAL_HASH_DeInit() to deinitialize the HASH peripheral.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup HASHEx
+ * @brief HASH Extension HAL module driver.
+ * @{
+ */
+
+#ifdef HAL_HASH_MODULE_ENABLED
+
+#if defined(STM32F437xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void HASHEx_DMAXferCplt(DMA_HandleTypeDef *hdma);
+static void HASHEx_WriteData(uint8_t *pInBuffer, uint32_t Size);
+static void HASHEx_GetDigest(uint8_t *pMsgDigest, uint8_t Size);
+static void HASHEx_DMAError(DMA_HandleTypeDef *hdma);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup HASHEx_Private_Functions
+ * @{
+ */
+
+/** @defgroup HASHEx_Group1 HASH processing functions
+ * @brief processing functions using polling mode
+ *
+@verbatim
+ ===============================================================================
+ ##### HASH processing using polling mode functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in polling mode
+ the hash value using one of the following algorithms:
+ (+) SHA224
+ (+) SHA256
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH peripheral in SHA224 mode
+ * then processes pInBuffer. The digest is available in pOutBuffer
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param pOutBuffer: Pointer to the output buffer (hashed buffer).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 28 bytes.
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA224 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_SHA224 | HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(pInBuffer, Size);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((HASH->SR & HASH_FLAG_BUSY) == HASH_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the message digest */
+ HASHEx_GetDigest(pOutBuffer, 28);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in SHA256 mode then processes pInBuffer.
+ The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param pOutBuffer: Pointer to the output buffer (hashed buffer).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 32 bytes.
+ * @param Timeout: Specify Timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA256 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_SHA256 | HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(pInBuffer, Size);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((HASH->SR & HASH_FLAG_BUSY) == HASH_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the message digest */
+ HASHEx_GetDigest(pOutBuffer, 32);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Initializes the HASH peripheral in SHA224 mode
+ * then processes pInBuffer. The digest is available in pOutBuffer
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA224_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA224 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_SHA224 | HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(pInBuffer, Size);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Initializes the HASH peripheral in SHA256 mode then processes pInBuffer.
+ The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA256_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA256 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_SHA256 | HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(pInBuffer, Size);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+
+/**
+ * @}
+ */
+
+/** @defgroup HASHEx_Group2 HMAC processing functions using polling mode
+ * @brief HMAC processing functions using polling mode .
+ *
+@verbatim
+ ===============================================================================
+ ##### HMAC processing using polling mode functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in polling mode
+ the HMAC value using one of the following algorithms:
+ (+) SHA224
+ (+) SHA256
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH peripheral in HMAC SHA224 mode
+ * then processes pInBuffer. The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param pOutBuffer: Pointer to the output buffer (hashed buffer).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HMACEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Check if key size is greater than 64 bytes */
+ if(hhash->Init.KeySize > 64)
+ {
+ /* Select the HMAC SHA224 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA224 | HASH_AlgoMode_HMAC | HASH_HMACKeyType_LongKey | HASH_CR_INIT);
+ }
+ else
+ {
+ /* Select the HMAC SHA224 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA224 | HASH_AlgoMode_HMAC | HASH_CR_INIT);
+ }
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /************************** STEP 1 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(hhash->Init.pKey, hhash->Init.KeySize);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((HASH->SR & HASH_FLAG_BUSY) == HASH_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /************************** STEP 2 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(pInBuffer, Size);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((HASH->SR & HASH_FLAG_BUSY) == HASH_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /************************** STEP 3 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(hhash->Init.pKey, hhash->Init.KeySize);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((HASH->SR & HASH_FLAG_BUSY) == HASH_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Read the message digest */
+ HASHEx_GetDigest(pOutBuffer, 28);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in HMAC SHA256 mode
+ * then processes pInBuffer. The digest is available in pOutBuffer
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param pOutBuffer: Pointer to the output buffer (hashed buffer).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HMACEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Check if key size is greater than 64 bytes */
+ if(hhash->Init.KeySize > 64)
+ {
+ /* Select the HMAC SHA256 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA256 | HASH_AlgoMode_HMAC | HASH_HMACKeyType_LongKey);
+ }
+ else
+ {
+ /* Select the HMAC SHA256 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA256 | HASH_AlgoMode_HMAC);
+ }
+ /* Reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /************************** STEP 1 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(hhash->Init.pKey, hhash->Init.KeySize);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((HASH->SR & HASH_FLAG_BUSY) == HASH_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /************************** STEP 2 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(pInBuffer, Size);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((HASH->SR & HASH_FLAG_BUSY) == HASH_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /************************** STEP 3 ******************************************/
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Write input buffer in data register */
+ HASHEx_WriteData(hhash->Init.pKey, hhash->Init.KeySize);
+
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((HASH->SR & HASH_FLAG_BUSY) == HASH_FLAG_BUSY)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Read the message digest */
+ HASHEx_GetDigest(pOutBuffer, 32);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HASHEx_Group3 HASH processing functions using interrupt mode
+ * @brief processing functions using interrupt mode.
+ *
+@verbatim
+ ===============================================================================
+ ##### HASH processing using interrupt functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in interrupt mode
+ the hash value using one of the following algorithms:
+ (+) SHA224
+ (+) SHA256
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH peripheral in SHA224 mode then processes pInBuffer.
+ * The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA224_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer)
+{
+ uint32_t inputaddr;
+ uint32_t buffercounter;
+ uint32_t inputcounter;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ if(hhash->HashITCounter == 0)
+ {
+ hhash->HashITCounter = 1;
+ }
+ else
+ {
+ hhash->HashITCounter = 0;
+ }
+ if(hhash->State == HAL_HASH_STATE_READY)
+ {
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ hhash->HashInCount = Size;
+ hhash->pHashInBuffPtr = pInBuffer;
+ hhash->pHashOutBuffPtr = pOutBuffer;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA224 mode */
+ HASH->CR |= HASH_AlgoSelection_SHA224;
+ /* Reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Enable Interrupts */
+ HASH->IMR = (HASH_IT_DINI | HASH_IT_DCI);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ if(__HAL_HASH_GET_FLAG(HASH_FLAG_DCIS))
+ {
+ /* Read the message digest */
+ HASHEx_GetDigest(hhash->pHashOutBuffPtr, 28);
+ if(hhash->HashInCount == 0)
+ {
+ /* Disable Interrupts */
+ HASH->IMR = 0;
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+ /* Call digest computation complete callback */
+ HAL_HASH_DgstCpltCallback(hhash);
+ }
+ }
+ if(__HAL_HASH_GET_FLAG(HASH_FLAG_DINIS))
+ {
+ if(hhash->HashInCount > 64)
+ {
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ /* Write the Input block in the Data IN register */
+ for(buffercounter = 0; buffercounter < 64; buffercounter+=4)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ inputaddr+=4;
+ }
+ if(hhash->HashITCounter == 0)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ if(hhash->HashInCount >= 68)
+ {
+ /* Decrement buffer counter */
+ hhash->HashInCount -= 68;
+ hhash->pHashInBuffPtr+= 68;
+ }
+ else
+ {
+ hhash->HashInCount -= 64;
+ }
+ }
+ else
+ {
+ /* Decrement buffer counter */
+ hhash->HashInCount -= 64;
+ hhash->pHashInBuffPtr+= 64;
+ }
+ }
+ else
+ {
+ /* Get the buffer address */
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ /* Get the buffer counter */
+ inputcounter = hhash->HashInCount;
+ /* Disable Interrupts */
+ HASH->IMR &= ~(HASH_IT_DINI);
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(inputcounter);
+
+ if((inputcounter > 4) && (inputcounter%4))
+ {
+ inputcounter = (inputcounter+4-inputcounter%4);
+ }
+
+ /* Write the Input block in the Data IN register */
+ for(buffercounter = 0; buffercounter < inputcounter/4; buffercounter++)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ inputaddr+=4;
+ }
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+ /* Reset buffer counter */
+ hhash->HashInCount = 0;
+ }
+ /* Call Input data transfer complete callback */
+ HAL_HASH_InCpltCallback(hhash);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Initializes the HASH peripheral in SHA256 mode then processes pInBuffer.
+ * The digest is available in pOutBuffer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA256_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer)
+{
+ uint32_t inputaddr;
+ uint32_t buffercounter;
+ uint32_t inputcounter;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ if(hhash->HashITCounter == 0)
+ {
+ hhash->HashITCounter = 1;
+ }
+ else
+ {
+ hhash->HashITCounter = 0;
+ }
+ if(hhash->State == HAL_HASH_STATE_READY)
+ {
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ hhash->HashInCount = Size;
+ hhash->pHashInBuffPtr = pInBuffer;
+ hhash->pHashOutBuffPtr = pOutBuffer;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA256 mode */
+ HASH->CR |= HASH_AlgoSelection_SHA256;
+ /* Reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Enable Interrupts */
+ HASH->IMR = (HASH_IT_DINI | HASH_IT_DCI);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+ if(__HAL_HASH_GET_FLAG(HASH_FLAG_DCIS))
+ {
+ /* Read the message digest */
+ HASHEx_GetDigest(hhash->pHashOutBuffPtr, 32);
+ if(hhash->HashInCount == 0)
+ {
+ /* Disable Interrupts */
+ HASH->IMR = 0;
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_READY;
+ /* Call digest computation complete callback */
+ HAL_HASH_DgstCpltCallback(hhash);
+ }
+ }
+ if(__HAL_HASH_GET_FLAG(HASH_FLAG_DINIS))
+ {
+ if(hhash->HashInCount > 64)
+ {
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ /* Write the Input block in the Data IN register */
+ for(buffercounter = 0; buffercounter < 64; buffercounter+=4)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ inputaddr+=4;
+ }
+ if(hhash->HashITCounter == 0)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+
+ if(hhash->HashInCount >= 68)
+ {
+ /* Decrement buffer counter */
+ hhash->HashInCount -= 68;
+ hhash->pHashInBuffPtr+= 68;
+ }
+ else
+ {
+ hhash->HashInCount -= 64;
+ }
+ }
+ else
+ {
+ /* Decrement buffer counter */
+ hhash->HashInCount -= 64;
+ hhash->pHashInBuffPtr+= 64;
+ }
+ }
+ else
+ {
+ /* Get the buffer address */
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ /* Get the buffer counter */
+ inputcounter = hhash->HashInCount;
+ /* Disable Interrupts */
+ HASH->IMR &= ~(HASH_IT_DINI);
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(inputcounter);
+
+ if((inputcounter > 4) && (inputcounter%4))
+ {
+ inputcounter = (inputcounter+4-inputcounter%4);
+ }
+
+ /* Write the Input block in the Data IN register */
+ for(buffercounter = 0; buffercounter < inputcounter/4; buffercounter++)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ inputaddr+=4;
+ }
+ /* Start the digest calculation */
+ __HAL_HASH_START_DIGEST();
+ /* Reset buffer counter */
+ hhash->HashInCount = 0;
+ }
+ /* Call Input data transfer complete callback */
+ HAL_HASH_InCpltCallback(hhash);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles HASH interrupt request.
+ * @param hhash: hash handle
+ * @retval None
+ */
+void HAL_HASHEx_IRQHandler(HASH_HandleTypeDef *hhash)
+{
+ switch(HASH->CR & HASH_CR_ALGO)
+ {
+
+ case HASH_AlgoSelection_SHA224:
+ HAL_HASHEx_SHA224_Start_IT(hhash, NULL, 0, NULL);
+ break;
+
+ case HASH_AlgoSelection_SHA256:
+ HAL_HASHEx_SHA256_Start_IT(hhash, NULL, 0, NULL);
+ break;
+
+ default:
+ break;
+ }
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HASHEx_Group4 HASH processing functions using DMA mode
+ * @brief processing functions using DMA mode.
+ *
+@verbatim
+ ===============================================================================
+ ##### HASH processing using DMA functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in DMA mode
+ the hash value using one of the following algorithms:
+ (+) SHA224
+ (+) SHA256
+
+@endverbatim
+ * @{
+ */
+
+
+/**
+ * @brief Initializes the HASH peripheral in SHA224 mode then enables DMA to
+ control data transfer. Use HAL_HASH_SHA224_Finish() to get the digest.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 28 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t inputaddr = (uint32_t)pInBuffer;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA224 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_SHA224 | HASH_CR_INIT;
+ }
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Set the HASH DMA transfer complete callback */
+ hhash->hdmain->XferCpltCallback = HASHEx_DMAXferCplt;
+ /* Set the DMA error callback */
+ hhash->hdmain->XferErrorCallback = HASHEx_DMAError;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (Size%4 ? (Size+3)/4:Size/4));
+
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Returns the computed digest in SHA224
+ * @param hhash: HASH handle
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 28 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA224_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(HASH->SR, HASH_FLAG_DCIS))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the message digest */
+ HASHEx_GetDigest(pOutBuffer, 28);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in SHA256 mode then enables DMA to
+ control data transfer. Use HAL_HASH_SHA256_Finish() to get the digest.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 20 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t inputaddr = (uint32_t)pInBuffer;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Select the SHA256 mode and reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_AlgoSelection_SHA256 | HASH_CR_INIT;
+ }
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(Size);
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Set the HASH DMA transfer complete callback */
+ hhash->hdmain->XferCpltCallback = HASHEx_DMAXferCplt;
+ /* Set the DMA error callback */
+ hhash->hdmain->XferErrorCallback = HASHEx_DMAError;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (Size%4 ? (Size+3)/4:Size/4));
+
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+
+ /* Process UnLock */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Returns the computed digest in SHA256.
+ * @param hhash: HASH handle
+ * @param pOutBuffer: Pointer to the computed digest. Its size must be 32 bytes.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HASHEx_SHA256_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(HAL_IS_BIT_CLR(HASH->SR, HASH_FLAG_DCIS))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Change state */
+ hhash->State = HAL_HASH_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Read the message digest */
+ HASHEx_GetDigest(pOutBuffer, 32);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+
+/**
+ * @}
+ */
+/** @defgroup HASHEx_Group5 HMAC processing functions using DMA mode
+ * @brief HMAC processing functions using DMA mode .
+ *
+@verbatim
+ ===============================================================================
+ ##### HMAC processing using DMA functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to calculate in DMA mode
+ the HMAC value using one of the following algorithms:
+ (+) SHA224
+ (+) SHA256
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the HASH peripheral in HMAC SHA224 mode
+ * then enables DMA to control data transfer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HMACEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t inputaddr;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Save buffer pointer and size in handle */
+ hhash->pHashInBuffPtr = pInBuffer;
+ hhash->HashBuffSize = Size;
+ hhash->HashInCount = 0;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Check if key size is greater than 64 bytes */
+ if(hhash->Init.KeySize > 64)
+ {
+ /* Select the HMAC SHA224 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA224 | HASH_AlgoMode_HMAC | HASH_HMACKeyType_LongKey | HASH_CR_INIT);
+ }
+ else
+ {
+ /* Select the HMAC SHA224 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA224 | HASH_AlgoMode_HMAC | HASH_CR_INIT);
+ }
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Get the key address */
+ inputaddr = (uint32_t)(hhash->Init.pKey);
+
+ /* Set the HASH DMA transfer complete callback */
+ hhash->hdmain->XferCpltCallback = HASHEx_DMAXferCplt;
+ /* Set the DMA error callback */
+ hhash->hdmain->XferErrorCallback = HASHEx_DMAError;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (hhash->Init.KeySize%4 ? (hhash->Init.KeySize+3)/4:hhash->Init.KeySize/4));
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HASH peripheral in HMAC SHA256 mode
+ * then enables DMA to control data transfer.
+ * @param hhash: HASH handle
+ * @param pInBuffer: Pointer to the input buffer (buffer to be hashed).
+ * @param Size: Length of the input buffer in bytes.
+ * If the Size is not multiple of 64 bytes, the padding is managed by hardware.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HMACEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t inputaddr;
+
+ /* Process Locked */
+ __HAL_LOCK(hhash);
+
+ /* Change the HASH state */
+ hhash->State = HAL_HASH_STATE_BUSY;
+
+ /* Save buffer pointer and size in handle */
+ hhash->pHashInBuffPtr = pInBuffer;
+ hhash->HashBuffSize = Size;
+ hhash->HashInCount = 0;
+
+ /* Check if initialization phase has already been performed */
+ if(hhash->Phase == HAL_HASH_PHASE_READY)
+ {
+ /* Check if key size is greater than 64 bytes */
+ if(hhash->Init.KeySize > 64)
+ {
+ /* Select the HMAC SHA256 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA256 | HASH_AlgoMode_HMAC | HASH_HMACKeyType_LongKey);
+ }
+ else
+ {
+ /* Select the HMAC SHA256 mode */
+ HASH->CR |= (HASH_AlgoSelection_SHA256 | HASH_AlgoMode_HMAC);
+ }
+ /* Reset the HASH processor core, so that the HASH will be ready to compute
+ the message digest of a new message */
+ HASH->CR |= HASH_CR_INIT;
+ }
+
+ /* Set the phase */
+ hhash->Phase = HAL_HASH_PHASE_PROCESS;
+
+ /* Configure the number of valid bits in last word of the message */
+ __HAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize);
+
+ /* Get the key address */
+ inputaddr = (uint32_t)(hhash->Init.pKey);
+
+ /* Set the HASH DMA transfer complete callback */
+ hhash->hdmain->XferCpltCallback = HASHEx_DMAXferCplt;
+ /* Set the DMA error callback */
+ hhash->hdmain->XferErrorCallback = HASHEx_DMAError;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (hhash->Init.KeySize%4 ? (hhash->Init.KeySize+3)/4:hhash->Init.KeySize/4));
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hhash);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Writes the input buffer in data register.
+ * @param pInBuffer: Pointer to input buffer
+ * @param Size: The size of input buffer
+ * @retval None
+ */
+static void HASHEx_WriteData(uint8_t *pInBuffer, uint32_t Size)
+{
+ uint32_t buffercounter;
+ uint32_t inputaddr = (uint32_t) pInBuffer;
+
+ for(buffercounter = 0; buffercounter < Size; buffercounter+=4)
+ {
+ HASH->DIN = *(uint32_t*)inputaddr;
+ inputaddr+=4;
+ }
+}
+
+/**
+ * @brief Provides the message digest result.
+ * @param pMsgDigest: Pointer to the message digest
+ * @param Size: The size of the message digest in bytes
+ * @retval None
+ */
+static void HASHEx_GetDigest(uint8_t *pMsgDigest, uint8_t Size)
+{
+ uint32_t msgdigest = (uint32_t)pMsgDigest;
+
+ switch(Size)
+ {
+ case 16:
+ /* Read the message digest */
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[0]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[1]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[2]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[3]);
+ break;
+ case 20:
+ /* Read the message digest */
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[0]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[1]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[2]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[3]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[4]);
+ break;
+ case 28:
+ /* Read the message digest */
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[0]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[1]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[2]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[3]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[4]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[5]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[6]);
+ break;
+ case 32:
+ /* Read the message digest */
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[0]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[1]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[2]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[3]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH->HR[4]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[5]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[6]);
+ msgdigest+=4;
+ *(uint32_t*)(msgdigest) = __REV(HASH_DIGEST->HR[7]);
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * @brief DMA HASH Input Data complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void HASHEx_DMAXferCplt(DMA_HandleTypeDef *hdma)
+{
+ HASH_HandleTypeDef* hhash = ( HASH_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ uint32_t inputaddr = 0;
+ uint32_t buffersize = 0;
+
+ if((HASH->CR & HASH_CR_MODE) != HASH_CR_MODE)
+ {
+ /* Disable the DMA transfer */
+ HASH->CR &= (uint32_t)(~HASH_CR_DMAE);
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Call Input data transfer complete callback */
+ HAL_HASH_InCpltCallback(hhash);
+ }
+ else
+ {
+ /* Increment Interrupt counter */
+ hhash->HashInCount++;
+ /* Disable the DMA transfer before starting the next transfer */
+ HASH->CR &= (uint32_t)(~HASH_CR_DMAE);
+
+ if(hhash->HashInCount <= 2)
+ {
+ /* In case HashInCount = 1, set the DMA to transfer data to HASH DIN register */
+ if(hhash->HashInCount == 1)
+ {
+ inputaddr = (uint32_t)hhash->pHashInBuffPtr;
+ buffersize = hhash->HashBuffSize;
+ }
+ /* In case HashInCount = 2, set the DMA to transfer key to HASH DIN register */
+ else if(hhash->HashInCount == 2)
+ {
+ inputaddr = (uint32_t)hhash->Init.pKey;
+ buffersize = hhash->Init.KeySize;
+ }
+ /* Configure the number of valid bits in last word of the message */
+ HASH->STR |= 8 * (buffersize % 4);
+
+ /* Set the HASH DMA transfer complete */
+ hhash->hdmain->XferCpltCallback = HASHEx_DMAXferCplt;
+
+ /* Enable the DMA In DMA Stream */
+ HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, (buffersize%4 ? (buffersize+3)/4:buffersize/4));
+
+ /* Enable DMA requests */
+ HASH->CR |= (HASH_CR_DMAE);
+ }
+ else
+ {
+ /* Disable the DMA transfer */
+ HASH->CR &= (uint32_t)(~HASH_CR_DMAE);
+
+ /* Reset the InCount */
+ hhash->HashInCount = 0;
+
+ /* Change HASH peripheral state */
+ hhash->State = HAL_HASH_STATE_READY;
+
+ /* Call Input data transfer complete callback */
+ HAL_HASH_InCpltCallback(hhash);
+ }
+ }
+}
+
+/**
+ * @brief DMA HASH communication error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void HASHEx_DMAError(DMA_HandleTypeDef *hdma)
+{
+ HASH_HandleTypeDef* hhash = ( HASH_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ hhash->State= HAL_HASH_STATE_READY;
+ HAL_HASH_ErrorCallback(hhash);
+}
+
+
+/**
+ * @}
+ */
+#endif /* STM32F437xx || STM32F439xx */
+
+#endif /* HAL_HASH_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hcd.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hcd.c
new file mode 100644
index 0000000..8ea7000
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hcd.c
@@ -0,0 +1,1194 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_hcd.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief HCD HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the USB Peripheral Controller:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#)Declare a HCD_HandleTypeDef handle structure, for example:
+ HCD_HandleTypeDef hhcd;
+
+ (#)Fill parameters of Init structure in HCD handle
+
+ (#)Call HAL_HCD_Init() API to initialize the HCD peripheral (Core, Host core, ...)
+
+ (#)Initialize the HCD low level resources through the HAL_HCD_MspInit() API:
+ (##) Enable the HCD/USB Low Level interface clock using
+ (+++) __OTGFS-OTG_CLK_ENABLE()/__OTGHS-OTG_CLK_ENABLE();
+ (+++) __OTGHSULPI_CLK_ENABLE(); (For High Speed Mode)
+
+ (##) Initialize the related GPIO clocks
+ (##) Configure HCD pin-out
+ (##) Configure HCD NVIC interrupt
+
+ (#)Associate the Upper USB Host stack to the HAL HCD Driver:
+ (##) hhcd.pData = phost;
+
+ (#)Enable HCD transmission and reception:
+ (##) HAL_HCD_Start();
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup HCD
+ * @brief HCD HAL module driver
+ * @{
+ */
+
+#ifdef HAL_HCD_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum);
+static void HCD_HC_OUT_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum);
+static void HCD_RXQLVL_IRQHandler(HCD_HandleTypeDef *hhcd);
+static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup HCD_Private_Functions
+ * @{
+ */
+
+/** @defgroup HCD_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initialize the host driver
+ * @param hhcd : HCD handle
+ * @retval HAL state
+ */
+HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd)
+{
+ /* Check the HCD handle allocation */
+ if(hhcd == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_HCD_ALL_INSTANCE(hhcd->Instance));
+
+ hhcd->State = HCD_BUSY;
+
+ /* Init the low level hardware : GPIO, CLOCK, NVIC... */
+ HAL_HCD_MspInit(hhcd);
+
+ /* Disable the Interrupts */
+ __HAL_HCD_DISABLE(hhcd);
+
+ /*Init the Core (common init.) */
+ USB_CoreInit(hhcd->Instance, hhcd->Init);
+
+ /* Force Host Mode*/
+ USB_SetCurrentMode(hhcd->Instance , USB_OTG_HOST_MODE);
+
+ /* Init Host */
+ USB_HostInit(hhcd->Instance, hhcd->Init);
+
+ hhcd->State= HCD_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initialize a host channel
+ * @param hhcd : HCD handle
+ * @param ch_num : Channel number
+ * This parameter can be a value from 1 to 15
+ * @param epnum : Endpoint number
+ * This parameter can be a value from 1 to 15
+ * @param dev_address : Current device address
+ * This parameter can be a value from 0 to 255
+ * @param speed : Current device speed
+ * This parameter can be one of the these values:
+ * @arg HCD_SPEED_HIGH: High speed mode
+ * @arg HCD_SPEED_FULL: Full speed mode
+ * @arg HCD_SPEED_LOW: Low speed mode
+ * @param ep_type : Endpoint Type
+ * This parameter can be one of the these values:
+ * @arg EP_TYPE_CTRL: Control type
+ * @arg EP_TYPE_ISOC: Isochrounous type
+ * @arg EP_TYPE_BULK: Bulk type
+ * @arg EP_TYPE_INTR: Interrupt type
+ * @param mps : Max Packet Size
+ * This parameter can be a value from 0 to32K
+ * @retval HAL state
+ */
+HAL_StatusTypeDef HAL_HCD_HC_Init(HCD_HandleTypeDef *hhcd,
+ uint8_t ch_num,
+ uint8_t epnum,
+ uint8_t dev_address,
+ uint8_t speed,
+ uint8_t ep_type,
+ uint16_t mps)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ __HAL_LOCK(hhcd);
+
+ hhcd->hc[ch_num].dev_addr = dev_address;
+ hhcd->hc[ch_num].max_packet = mps;
+ hhcd->hc[ch_num].ch_num = ch_num;
+ hhcd->hc[ch_num].ep_type = ep_type;
+ hhcd->hc[ch_num].ep_num = epnum & 0x7F;
+ hhcd->hc[ch_num].ep_is_in = ((epnum & 0x80) == 0x80);
+ hhcd->hc[ch_num].speed = speed;
+
+ status = USB_HC_Init(hhcd->Instance,
+ ch_num,
+ epnum,
+ dev_address,
+ speed,
+ ep_type,
+ mps);
+ __HAL_UNLOCK(hhcd);
+
+ return status;
+}
+
+
+
+/**
+ * @brief Halt a host channel
+ * @param hhcd : HCD handle
+ * @param ch_num : Channel number
+ * This parameter can be a value from 1 to 15
+ * @retval HAL state
+ */
+HAL_StatusTypeDef HAL_HCD_HC_Halt(HCD_HandleTypeDef *hhcd,
+ uint8_t ch_num)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ __HAL_LOCK(hhcd);
+ USB_HC_Halt(hhcd->Instance, ch_num);
+ __HAL_UNLOCK(hhcd);
+
+ return status;
+}
+/**
+ * @brief DeInitialize the host driver
+ * @param hhcd : HCD handle
+ * @retval HAL state
+ */
+HAL_StatusTypeDef HAL_HCD_DeInit(HCD_HandleTypeDef *hhcd)
+{
+ /* Check the HCD handle allocation */
+ if(hhcd == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ hhcd->State = HCD_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_HCD_MspDeInit(hhcd);
+
+ __HAL_HCD_DISABLE(hhcd);
+
+ hhcd->State = HCD_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the HCD MSP.
+ * @param hhcd: HCD handle
+ * @retval None
+ */
+__weak void HAL_HCD_MspInit(HCD_HandleTypeDef *hhcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_MspInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes HCD MSP.
+ * @param hhcd: HCD handle
+ * @retval None
+ */
+__weak void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhhcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_MspDeInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HCD_Group2 IO operation functions
+ * @brief HCD IO operation functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ This subsection provides a set of functions allowing to manage the USB Host Data
+ Transfer
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Submit a new URB for processing
+ * @param hhcd : HCD handle
+ * @param ch_num : Channel number
+ * This parameter can be a value from 1 to 15
+ * @param direction : Channel number
+ * This parameter can be one of the these values:
+ * 0 : Output
+ * 1 : Input
+ * @param ep_type : Endpoint Type
+ * This parameter can be one of the these values:
+ * @arg EP_TYPE_CTRL: Control type
+ * @arg EP_TYPE_ISOC: Isochrounous type
+ * @arg EP_TYPE_BULK: Bulk type
+ * @arg EP_TYPE_INTR: Interrupt type
+ * @param token : Endpoint Type
+ * This parameter can be one of the these values:
+ * @arg 0: HC_PID_SETUP
+ * @arg 1: HC_PID_DATA1
+ * @param pbuff : pointer to URB data
+ * @param length : Length of URB data
+ * @param do_ping : activate do ping protocol (for high speed only)
+ * This parameter can be one of the these values:
+ * 0 : do ping inactive
+ * 1 : do ping active
+ * @retval HAL state
+ */
+HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd,
+ uint8_t ch_num,
+ uint8_t direction ,
+ uint8_t ep_type,
+ uint8_t token,
+ uint8_t* pbuff,
+ uint16_t length,
+ uint8_t do_ping)
+{
+ hhcd->hc[ch_num].ep_is_in = direction;
+ hhcd->hc[ch_num].ep_type = ep_type;
+
+ if(token == 0)
+ {
+ hhcd->hc[ch_num].data_pid = HC_PID_SETUP;
+ }
+ else
+ {
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA1;
+ }
+
+ /* Manage Data Toggle */
+ switch(ep_type)
+ {
+ case EP_TYPE_CTRL:
+ if((token == 1) && (direction == 0)) /*send data */
+ {
+ if ( length == 0 )
+ { /* For Status OUT stage, Length==0, Status Out PID = 1 */
+ hhcd->hc[ch_num].toggle_out = 1;
+ }
+
+ /* Set the Data Toggle bit as per the Flag */
+ if ( hhcd->hc[ch_num].toggle_out == 0)
+ { /* Put the PID 0 */
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA0;
+ }
+ else
+ { /* Put the PID 1 */
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA1 ;
+ }
+ if(hhcd->hc[ch_num].urb_state != URB_NOTREADY)
+ {
+ hhcd->hc[ch_num].do_ping = do_ping;
+ }
+ }
+ break;
+
+ case EP_TYPE_BULK:
+ if(direction == 0)
+ {
+ /* Set the Data Toggle bit as per the Flag */
+ if ( hhcd->hc[ch_num].toggle_out == 0)
+ { /* Put the PID 0 */
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA0;
+ }
+ else
+ { /* Put the PID 1 */
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA1 ;
+ }
+ if(hhcd->hc[ch_num].urb_state != URB_NOTREADY)
+ {
+ hhcd->hc[ch_num].do_ping = do_ping;
+ }
+ }
+ else
+ {
+ if( hhcd->hc[ch_num].toggle_in == 0)
+ {
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA0;
+ }
+ else
+ {
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA1;
+ }
+ }
+
+ break;
+ case EP_TYPE_INTR:
+ if(direction == 0)
+ {
+ /* Set the Data Toggle bit as per the Flag */
+ if ( hhcd->hc[ch_num].toggle_out == 0)
+ { /* Put the PID 0 */
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA0;
+ }
+ else
+ { /* Put the PID 1 */
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA1 ;
+ }
+ }
+ else
+ {
+ if( hhcd->hc[ch_num].toggle_in == 0)
+ {
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA0;
+ }
+ else
+ {
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA1;
+ }
+ }
+ break;
+
+ case EP_TYPE_ISOC:
+ hhcd->hc[ch_num].data_pid = HC_PID_DATA0;
+ break;
+
+ }
+
+ hhcd->hc[ch_num].xfer_buff = pbuff;
+ hhcd->hc[ch_num].xfer_len = length;
+ hhcd->hc[ch_num].urb_state = URB_IDLE;
+ hhcd->hc[ch_num].xfer_count = 0 ;
+ hhcd->hc[ch_num].ch_num = ch_num;
+ hhcd->hc[ch_num].state = HC_IDLE;
+
+ return USB_HC_StartXfer(hhcd->Instance, &(hhcd->hc[ch_num]), hhcd->Init.dma_enable);
+}
+
+/**
+ * @brief This function handles HCD interrupt request.
+ * @param hhcd: HCD handle
+ * @retval none
+ */
+void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd)
+{
+ USB_OTG_GlobalTypeDef *USBx = hhcd->Instance;
+ uint32_t i = 0 , interrupt = 0;
+
+ /* ensure that we are in device mode */
+ if (USB_GetMode(hhcd->Instance) == USB_OTG_MODE_HOST)
+ {
+ /* avoid spurious interrupt */
+ if(__HAL_HCD_IS_INVALID_INTERRUPT(hhcd))
+ {
+ return;
+ }
+
+ if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT))
+ {
+ /* incorrect mode, acknowledge the interrupt */
+ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT);
+ }
+
+ if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_IISOIXFR))
+ {
+ /* incorrect mode, acknowledge the interrupt */
+ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_IISOIXFR);
+ }
+
+ if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_PTXFE))
+ {
+ /* incorrect mode, acknowledge the interrupt */
+ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_PTXFE);
+ }
+
+ if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_MMIS))
+ {
+ /* incorrect mode, acknowledge the interrupt */
+ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_MMIS);
+ }
+
+ /* Handle Host Disconnect Interrupts */
+ if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_DISCINT))
+ {
+
+ /* Cleanup HPRT */
+ USBx_HPRT0 &= ~(USB_OTG_HPRT_PENA | USB_OTG_HPRT_PCDET |\
+ USB_OTG_HPRT_PENCHNG | USB_OTG_HPRT_POCCHNG );
+
+ /* Handle Host Port Interrupts */
+ HAL_HCD_Disconnect_Callback(hhcd);
+ USB_InitFSLSPClkSel(hhcd->Instance ,HCFG_48_MHZ );
+ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_DISCINT);
+ }
+
+ /* Handle Host Port Interrupts */
+ if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_HPRTINT))
+ {
+ HCD_Port_IRQHandler (hhcd);
+ }
+
+ /* Handle Host SOF Interrupts */
+ if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_SOF))
+ {
+ HAL_HCD_SOF_Callback(hhcd);
+ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_SOF);
+ }
+
+ /* Handle Host channel Interrupts */
+ if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_HCINT))
+ {
+
+ interrupt = USB_HC_ReadInterrupt(hhcd->Instance);
+ for (i = 0; i < hhcd->Init.Host_channels ; i++)
+ {
+ if (interrupt & (1 << i))
+ {
+ if ((USBx_HC(i)->HCCHAR) & USB_OTG_HCCHAR_EPDIR)
+ {
+ HCD_HC_IN_IRQHandler (hhcd, i);
+ }
+ else
+ {
+ HCD_HC_OUT_IRQHandler (hhcd, i);
+ }
+ }
+ }
+ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_HCINT);
+ }
+
+ /* Handle Rx Queue Level Interrupts */
+ if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_RXFLVL))
+ {
+ USB_MASK_INTERRUPT(hhcd->Instance, USB_OTG_GINTSTS_RXFLVL);
+
+ HCD_RXQLVL_IRQHandler (hhcd);
+
+ USB_UNMASK_INTERRUPT(hhcd->Instance, USB_OTG_GINTSTS_RXFLVL);
+ }
+
+ }
+}
+
+/**
+ * @brief SOF callback.
+ * @param hhcd: HCD handle
+ * @retval None
+ */
+__weak void HAL_HCD_SOF_Callback(HCD_HandleTypeDef *hhcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_HCD_SOF_Callback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Connexion Event callback.
+ * @param hhcd: HCD handle
+ * @retval None
+ */
+__weak void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_HCD_Connect_Callback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Disonnexion Event callback.
+ * @param hhcd: HCD handle
+ * @retval None
+ */
+__weak void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_HCD_Disconnect_Callback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Notify URB state change callback.
+ * @param hhcd: HCD handle
+ * @param chnum : Channel number
+ * This parameter can be a value from 1 to 15
+ * @param urb_state:
+ * This parameter can be one of the these values:
+ * @arg URB_IDLE
+ * @arg URB_DONE
+ * @arg URB_NOTREADY
+ * @arg URB_NYET
+ * @arg URB_ERROR
+ * @arg URB_STALL
+ * @retval None
+ */
+__weak void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, HCD_URBStateTypeDef urb_state)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_HCD_HC_NotifyURBChange_Callback could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HCD_Group3 Peripheral Control functions
+ * @brief management functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the HCD data
+ transfers.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Start the host driver
+ * @param hhcd : HCD handle
+ * @retval HAL state
+ */
+HAL_StatusTypeDef HAL_HCD_Start(HCD_HandleTypeDef *hhcd)
+{
+ __HAL_LOCK(hhcd);
+ __HAL_HCD_ENABLE(hhcd);
+ USB_DriveVbus(hhcd->Instance, 1);
+ __HAL_UNLOCK(hhcd);
+ return HAL_OK;
+}
+
+/**
+ * @brief Stop the host driver
+ * @param hhcd : HCD handle
+ * @retval HAL state
+ */
+
+HAL_StatusTypeDef HAL_HCD_Stop(HCD_HandleTypeDef *hhcd)
+{
+ __HAL_LOCK(hhcd);
+ USB_StopHost(hhcd->Instance);
+ __HAL_UNLOCK(hhcd);
+ return HAL_OK;
+}
+
+/**
+ * @brief Reset the host port
+ * @param hhcd : HCD handle
+ * @retval HAL state
+ */
+HAL_StatusTypeDef HAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd)
+{
+ return (USB_ResetPort(hhcd->Instance));
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HCD_Group4 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State functions #####
+ ===============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the HCD state
+ * @param hhcd : HCD handle
+ * @retval HAL state
+ */
+HCD_StateTypeDef HAL_HCD_GetState(HCD_HandleTypeDef *hhcd)
+{
+ return hhcd->State;
+}
+
+/**
+ * @brief Return URB state for a channel
+ * @param hhcd : HCD handle
+ * @param chnum : Channel number
+ * This parameter can be a value from 1 to 15
+ * @retval URB state
+ * This parameter can be one of the these values:
+ * @arg URB_IDLE
+ * @arg URB_DONE
+ * @arg URB_NOTREADY
+ * @arg URB_NYET
+ * @arg URB_ERROR
+ * @arg URB_STALL
+ */
+HCD_URBStateTypeDef HAL_HCD_HC_GetURBState(HCD_HandleTypeDef *hhcd, uint8_t chnum)
+{
+ return hhcd->hc[chnum].urb_state;
+}
+
+
+/**
+ * @brief Return the last host transfer size
+ * @param hhcd : HCD handle
+ * @param chnum : Channel number
+ * This parameter can be a value from 1 to 15
+ * @retval last transfer size in byte
+ */
+uint32_t HAL_HCD_HC_GetXferCount(HCD_HandleTypeDef *hhcd, uint8_t chnum)
+{
+ return hhcd->hc[chnum].xfer_count;
+}
+
+/**
+ * @brief Return the Host Channel state
+ * @param hhcd : HCD handle
+ * @param chnum : Channel number
+ * This parameter can be a value from 1 to 15
+ * @retval Host channel state
+ * This parameter can be one of the these values:
+ * @arg HC_IDLE
+ * @arg HC_XFRC
+ * @arg HC_HALTED
+ * @arg HC_NYET
+ * @arg HC_NAK
+ * @arg HC_STALL
+ * @arg HC_XACTERR
+ * @arg HC_BBLERR
+ * @arg HC_DATATGLERR
+ */
+HCD_HCStateTypeDef HAL_HCD_HC_GetState(HCD_HandleTypeDef *hhcd, uint8_t chnum)
+{
+ return hhcd->hc[chnum].state;
+}
+
+/**
+ * @brief Return the current Host frame number
+ * @param hhcd : HCD handle
+ * @retval current Host frame number
+ */
+uint32_t HAL_HCD_GetCurrentFrame(HCD_HandleTypeDef *hhcd)
+{
+ return (USB_GetCurrentFrame(hhcd->Instance));
+}
+
+/**
+ * @brief Return the Host enumeration speed
+ * @param hhcd : HCD handle
+ * @retval Enumeration speed
+ */
+uint32_t HAL_HCD_GetCurrentSpeed(HCD_HandleTypeDef *hhcd)
+{
+ return (USB_GetHostSpeed(hhcd->Instance));
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief This function handles Host Channel IN interrupt requests.
+ * @param hhcd: HCD handle
+ * @param chnum : Channel number
+ * This parameter can be a value from 1 to 15
+ * @retval none
+ */
+static void HCD_HC_IN_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum)
+{
+ USB_OTG_GlobalTypeDef *USBx = hhcd->Instance;
+
+ if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_AHBERR)
+ {
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_AHBERR);
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ }
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_ACK)
+ {
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_ACK);
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_STALL)
+ {
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ hhcd->hc[chnum].state = HC_STALL;
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_STALL);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ }
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_DTERR)
+ {
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK);
+ hhcd->hc[chnum].state = HC_DATATGLERR;
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_DTERR);
+ }
+
+ if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_FRMOR)
+ {
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_FRMOR);
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_XFRC)
+ {
+
+ if (hhcd->Init.dma_enable)
+ {
+ hhcd->hc[chnum].xfer_count = hhcd->hc[chnum].xfer_len - \
+ (USBx_HC(chnum)->HCTSIZ & USB_OTG_HCTSIZ_XFRSIZ);
+ }
+
+ hhcd->hc[chnum].state = HC_XFRC;
+ hhcd->hc[chnum].ErrCnt = 0;
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_XFRC);
+
+
+ if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL)||
+ (hhcd->hc[chnum].ep_type == EP_TYPE_BULK))
+ {
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK);
+
+ }
+ else if(hhcd->hc[chnum].ep_type == EP_TYPE_INTR)
+ {
+ USBx_HC(chnum)->HCCHAR |= USB_OTG_HCCHAR_ODDFRM;
+ hhcd->hc[chnum].urb_state = URB_DONE;
+ HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state);
+ }
+ hhcd->hc[chnum].toggle_in ^= 1;
+
+ }
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_CHH)
+ {
+ __HAL_HCD_MASK_HALT_HC_INT(chnum);
+
+ if(hhcd->hc[chnum].state == HC_XFRC)
+ {
+ hhcd->hc[chnum].urb_state = URB_DONE;
+ }
+
+ else if (hhcd->hc[chnum].state == HC_STALL)
+ {
+ hhcd->hc[chnum].urb_state = URB_STALL;
+ }
+
+ else if((hhcd->hc[chnum].state == HC_XACTERR) ||
+ (hhcd->hc[chnum].state == HC_DATATGLERR))
+ {
+ if(hhcd->hc[chnum].ErrCnt++ > 3)
+ {
+ hhcd->hc[chnum].ErrCnt = 0;
+ hhcd->hc[chnum].urb_state = URB_ERROR;
+ }
+ else
+ {
+ hhcd->hc[chnum].urb_state = URB_NOTREADY;
+ }
+
+ /* re-activate the channel */
+ USBx_HC(chnum)->HCCHAR &= ~USB_OTG_HCCHAR_CHDIS;
+ USBx_HC(chnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+ }
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH);
+ HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state);
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_TXERR)
+ {
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ hhcd->hc[chnum].ErrCnt++;
+ hhcd->hc[chnum].state = HC_XACTERR;
+ USB_HC_Halt(hhcd->Instance, chnum);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_TXERR);
+ }
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_NAK)
+ {
+ if(hhcd->hc[chnum].ep_type == EP_TYPE_INTR)
+ {
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ }
+ else if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL)||
+ (hhcd->hc[chnum].ep_type == EP_TYPE_BULK))
+ {
+ /* re-activate the channel */
+ USBx_HC(chnum)->HCCHAR &= ~USB_OTG_HCCHAR_CHDIS;
+ USBx_HC(chnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+
+ }
+ hhcd->hc[chnum].state = HC_NAK;
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK);
+ }
+}
+
+/**
+ * @brief This function handles Host Channel OUT interrupt requests.
+ * @param hhcd: HCD handle
+ * @param chnum : Channel number
+ * This parameter can be a value from 1 to 15
+ * @retval none
+ */
+static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum)
+{
+ USB_OTG_GlobalTypeDef *USBx = hhcd->Instance;
+
+ if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_AHBERR)
+ {
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_AHBERR);
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ }
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_ACK)
+ {
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_ACK);
+
+ if( hhcd->hc[chnum].do_ping == 1)
+ {
+ hhcd->hc[chnum].state = HC_NYET;
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ hhcd->hc[chnum].urb_state = URB_NOTREADY;
+ }
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_NYET)
+ {
+ hhcd->hc[chnum].state = HC_NYET;
+ hhcd->hc[chnum].ErrCnt= 0;
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NYET);
+
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_FRMOR)
+ {
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_FRMOR);
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_XFRC)
+ {
+ hhcd->hc[chnum].ErrCnt = 0;
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_XFRC);
+ hhcd->hc[chnum].state = HC_XFRC;
+
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_STALL)
+ {
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_STALL);
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ hhcd->hc[chnum].state = HC_STALL;
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_NAK)
+ {
+ hhcd->hc[chnum].ErrCnt = 0;
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ hhcd->hc[chnum].state = HC_NAK;
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK);
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_TXERR)
+ {
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ hhcd->hc[chnum].state = HC_XACTERR;
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_TXERR);
+ }
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_DTERR)
+ {
+ __HAL_HCD_UNMASK_HALT_HC_INT(chnum);
+ USB_HC_Halt(hhcd->Instance, chnum);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK);
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_DTERR);
+ hhcd->hc[chnum].state = HC_DATATGLERR;
+ }
+
+
+ else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_CHH)
+ {
+ __HAL_HCD_MASK_HALT_HC_INT(chnum);
+
+ if(hhcd->hc[chnum].state == HC_XFRC)
+ {
+ hhcd->hc[chnum].urb_state = URB_DONE;
+ if (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)
+ {
+ hhcd->hc[chnum].toggle_out ^= 1;
+ }
+ }
+ else if (hhcd->hc[chnum].state == HC_NAK)
+ {
+ hhcd->hc[chnum].urb_state = URB_NOTREADY;
+ }
+
+ else if (hhcd->hc[chnum].state == HC_NYET)
+ {
+ hhcd->hc[chnum].urb_state = URB_NOTREADY;
+ hhcd->hc[chnum].do_ping = 0;
+ }
+
+ else if (hhcd->hc[chnum].state == HC_STALL)
+ {
+ hhcd->hc[chnum].urb_state = URB_STALL;
+ }
+
+ else if((hhcd->hc[chnum].state == HC_XACTERR) ||
+ (hhcd->hc[chnum].state == HC_DATATGLERR))
+ {
+ if(hhcd->hc[chnum].ErrCnt++ > 3)
+ {
+ hhcd->hc[chnum].ErrCnt = 0;
+ hhcd->hc[chnum].urb_state = URB_ERROR;
+ }
+ else
+ {
+ hhcd->hc[chnum].urb_state = URB_NOTREADY;
+ }
+
+ /* re-activate the channel */
+ USBx_HC(chnum)->HCCHAR &= ~USB_OTG_HCCHAR_CHDIS;
+ USBx_HC(chnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+ }
+
+ __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH);
+ HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state);
+ }
+}
+
+/**
+ * @brief This function handles Rx Queue Level interrupt requests.
+ * @param hhcd: HCD handle
+ * @retval none
+ */
+static void HCD_RXQLVL_IRQHandler (HCD_HandleTypeDef *hhcd)
+{
+ USB_OTG_GlobalTypeDef *USBx = hhcd->Instance;
+ uint8_t channelnum =0;
+ uint32_t pktsts;
+ uint32_t pktcnt;
+ uint32_t temp = 0;
+
+ temp = hhcd->Instance->GRXSTSP ;
+ channelnum = temp & USB_OTG_GRXSTSP_EPNUM;
+ pktsts = (temp & USB_OTG_GRXSTSP_PKTSTS) >> 17;
+ pktcnt = (temp & USB_OTG_GRXSTSP_BCNT) >> 4;
+
+ switch (pktsts)
+ {
+ case GRXSTS_PKTSTS_IN:
+ /* Read the data into the host buffer. */
+ if ((pktcnt > 0) && (hhcd->hc[channelnum].xfer_buff != (void *)0))
+ {
+
+ USB_ReadPacket(hhcd->Instance, hhcd->hc[channelnum].xfer_buff, pktcnt);
+
+ /*manage multiple Xfer */
+ hhcd->hc[channelnum].xfer_buff += pktcnt;
+ hhcd->hc[channelnum].xfer_count += pktcnt;
+
+ if((USBx_HC(channelnum)->HCTSIZ & USB_OTG_HCTSIZ_PKTCNT) > 0)
+ {
+ /* re-activate the channel when more packets are expected */
+ USBx_HC(channelnum)->HCCHAR &= ~USB_OTG_HCCHAR_CHDIS;
+ USBx_HC(channelnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+ hhcd->hc[channelnum].toggle_in ^= 1;
+ }
+ }
+ break;
+
+ case GRXSTS_PKTSTS_DATA_TOGGLE_ERR:
+ break;
+ case GRXSTS_PKTSTS_IN_XFER_COMP:
+ case GRXSTS_PKTSTS_CH_HALTED:
+ default:
+ break;
+ }
+}
+
+/**
+ * @brief This function handles Host Port interrupt requests.
+ * @param hhcd: HCD handle
+ * @retval none
+ */
+static void HCD_Port_IRQHandler (HCD_HandleTypeDef *hhcd)
+{
+ USB_OTG_GlobalTypeDef *USBx = hhcd->Instance;
+ __IO uint32_t hprt0, hprt0_dup;
+
+ /* Handle Host Port Interrupts */
+ hprt0 = USBx_HPRT0;
+ hprt0_dup = USBx_HPRT0;
+
+ hprt0_dup &= ~(USB_OTG_HPRT_PENA | USB_OTG_HPRT_PCDET |\
+ USB_OTG_HPRT_PENCHNG | USB_OTG_HPRT_POCCHNG );
+
+ /* Check wether Port Connect Detected */
+ if((hprt0 & USB_OTG_HPRT_PCDET) == USB_OTG_HPRT_PCDET)
+ {
+ if((hprt0 & USB_OTG_HPRT_PCSTS) == USB_OTG_HPRT_PCSTS)
+ {
+ USB_MASK_INTERRUPT(hhcd->Instance, USB_OTG_GINTSTS_DISCINT);
+ HAL_HCD_Connect_Callback(hhcd);
+ }
+ hprt0_dup |= USB_OTG_HPRT_PCDET;
+
+ }
+
+ /* Check whether Port Enable Changed */
+ if((hprt0 & USB_OTG_HPRT_PENCHNG) == USB_OTG_HPRT_PENCHNG)
+ {
+ hprt0_dup |= USB_OTG_HPRT_PENCHNG;
+
+ if((hprt0 & USB_OTG_HPRT_PENA) == USB_OTG_HPRT_PENA)
+ {
+ if(hhcd->Init.phy_itface == USB_OTG_EMBEDDED_PHY)
+ {
+ if ((hprt0 & USB_OTG_HPRT_PSPD) == (HPRT0_PRTSPD_LOW_SPEED << 17))
+ {
+ USB_InitFSLSPClkSel(hhcd->Instance ,HCFG_6_MHZ );
+ }
+ else
+ {
+ USB_InitFSLSPClkSel(hhcd->Instance ,HCFG_48_MHZ );
+ }
+ }
+ else
+ {
+ if(hhcd->Init.speed == HCD_SPEED_FULL)
+ {
+ USBx_HOST->HFIR = (uint32_t)60000;
+ }
+ }
+ HAL_HCD_Connect_Callback(hhcd);
+
+ if(hhcd->Init.speed == HCD_SPEED_HIGH)
+ {
+ USB_UNMASK_INTERRUPT(hhcd->Instance, USB_OTG_GINTSTS_DISCINT);
+ }
+ }
+ else
+ {
+ /* Cleanup HPRT */
+ USBx_HPRT0 &= ~(USB_OTG_HPRT_PENA | USB_OTG_HPRT_PCDET |\
+ USB_OTG_HPRT_PENCHNG | USB_OTG_HPRT_POCCHNG );
+
+ USB_UNMASK_INTERRUPT(hhcd->Instance, USB_OTG_GINTSTS_DISCINT);
+ }
+ }
+
+ /* Check For an overcurrent */
+ if((hprt0 & USB_OTG_HPRT_POCCHNG) == USB_OTG_HPRT_POCCHNG)
+ {
+ hprt0_dup |= USB_OTG_HPRT_POCCHNG;
+ }
+
+ /* Clear Port Interrupts */
+ USBx_HPRT0 = hprt0_dup;
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_HCD_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c.c
new file mode 100644
index 0000000..80d92c5
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c.c
@@ -0,0 +1,3744 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_i2c.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief I2C HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Inter Integrated Circuit (I2C) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The I2C HAL driver can be used as follows:
+
+ (#) Declare a I2C_HandleTypeDef handle structure, for example:
+ I2C_HandleTypeDef hi2c;
+
+ (#)Initialize the I2C low level resources by implement the HAL_I2C_MspInit() API:
+ (##) Enable the I2Cx interface clock
+ (##) I2C pins configuration
+ (+++) Enable the clock for the I2C GPIOs
+ (+++) Configure I2C pins as alternate function open-drain
+ (##) NVIC configuration if you need to use interrupt process
+ (+++) Configure the I2Cx interrupt priority
+ (+++) Enable the NVIC I2C IRQ Channel
+ (##) DMA Configuration if you need to use DMA process
+ (+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive stream
+ (+++) Enable the DMAx interface clock using
+ (+++) Configure the DMA handle parameters
+ (+++) Configure the DMA Tx or Rx Stream
+ (+++) Associate the initilalized DMA handle to the hi2c DMA Tx or Rx handle
+ (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Stream
+
+ (#) Configure the Communication Speed, Duty cycle, Addressing mode, Own Address1,
+ Dual Addressing mode, Own Address2, General call and Nostretch mode in the hi2c Init structure.
+
+ (#) Initialize the I2C registers by calling the HAL_I2C_Init() API:
+ (+++) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc)
+ by calling the customed HAL_I2C_MspInit(&hi2c) API.
+
+ (#) To check if target device is ready for communication, use the function HAL_I2C_IsDeviceReady()
+
+ (#) For I2C IO and IO MEM operations, three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Transmit in master mode an amount of data in blocking mode using HAL_I2C_Master_Transmit()
+ (+) Receive in master mode an amount of data in blocking mode using HAL_I2C_Master_Receive()
+ (+) Transmit in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Transmit()
+ (+) Receive in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Receive()
+
+ *** Polling mode IO MEM operation ***
+ =====================================
+ [..]
+ (+) Write an amount of data in blocking mode to a specific memory address using HAL_I2C_Mem_Write()
+ (+) Read an amount of data in blocking mode from a specific memory address using HAL_I2C_Mem_Read()
+
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Transmit in master mode an amount of data in non blocking mode using HAL_I2C_Master_Transmit_IT()
+ (+) At transmission end of transfer HAL_I2C_MasterTxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_MasterTxCpltCallback
+ (+) Receive in master mode an amount of data in non blocking mode using HAL_I2C_Master_Receive_IT()
+ (+) At reception end of transfer HAL_I2C_MasterRxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback
+ (+) Transmit in slave mode an amount of data in non blocking mode using HAL_I2C_Slave_Transmit_IT()
+ (+) At transmission end of transfer HAL_I2C_SlaveTxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback
+ (+) Receive in slave mode an amount of data in non blocking mode using HAL_I2C_Slave_Receive_IT()
+ (+) At reception end of transfer HAL_I2C_SlaveRxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback
+ (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_I2C_ErrorCallback
+
+ *** Interrupt mode IO MEM operation ***
+ =======================================
+ [..]
+ (+) Write an amount of data in no-blocking mode with Interrupt to a specific memory address using
+ HAL_I2C_Mem_Write_IT()
+ (+) At MEM end of write transfer HAL_I2C_MemTxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_MemTxCpltCallback
+ (+) Read an amount of data in no-blocking mode with Interrupt from a specific memory address using
+ HAL_I2C_Mem_Read_IT()
+ (+) At MEM end of read transfer HAL_I2C_MemRxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_MemRxCpltCallback
+ (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_I2C_ErrorCallback
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Transmit in master mode an amount of data in non blocking mode (DMA) using
+ HAL_I2C_Master_Transmit_DMA()
+ (+) At transmission end of transfer HAL_I2C_MasterTxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_MasterTxCpltCallback
+ (+) Receive in master mode an amount of data in non blocking mode (DMA) using
+ HAL_I2C_Master_Receive_DMA()
+ (+) At reception end of transfer HAL_I2C_MasterRxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback
+ (+) Transmit in slave mode an amount of data in non blocking mode (DMA) using
+ HAL_I2C_Slave_Transmit_DMA()
+ (+) At transmission end of transfer HAL_I2C_SlaveTxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback
+ (+) Receive in slave mode an amount of data in non blocking mode (DMA) using
+ HAL_I2C_Slave_Receive_DMA()
+ (+) At reception end of transfer HAL_I2C_SlaveRxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback
+ (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_I2C_ErrorCallback
+
+ *** DMA mode IO MEM operation ***
+ =================================
+ [..]
+ (+) Write an amount of data in no-blocking mode with DMA to a specific memory address using
+ HAL_I2C_Mem_Write_DMA()
+ (+) At MEM end of write transfer HAL_I2C_MemTxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_MemTxCpltCallback
+ (+) Read an amount of data in no-blocking mode with DMA from a specific memory address using
+ HAL_I2C_Mem_Read_DMA()
+ (+) At MEM end of read transfer HAL_I2C_MemRxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2C_MemRxCpltCallback
+ (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_I2C_ErrorCallback
+
+
+ *** I2C HAL driver macros list ***
+ ==================================
+ [..]
+ Below the list of most used macros in I2C HAL driver.
+
+ (+) __HAL_I2C_ENABLE: Enable the I2C peripheral
+ (+) __HAL_I2C_DISABLE: Disable the I2C peripheral
+ (+) __HAL_I2C_GET_FLAG : Checks whether the specified I2C flag is set or not
+ (+) __HAL_I2C_CLEAR_FLAG : Clears the specified I2C pending flag
+ (+) __HAL_I2C_ENABLE_IT: Enables the specified I2C interrupt
+ (+) __HAL_I2C_DISABLE_IT: Disables the specified I2C interrupt
+
+ [..]
+ (@) You can refer to the I2C HAL driver header file for more useful macros
+
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup I2C
+ * @brief I2C HAL module driver
+ * @{
+ */
+
+#ifdef HAL_I2C_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define I2C_TIMEOUT_FLAG ((uint32_t)35) /* 35 ms */
+#define I2C_TIMEOUT_ADDR_SLAVE ((uint32_t)10000) /* 10 s */
+
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma);
+static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma);
+static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma);
+static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma);
+static void I2C_DMAMemTransmitCplt(DMA_HandleTypeDef *hdma);
+static void I2C_DMAMemReceiveCplt(DMA_HandleTypeDef *hdma);
+static void I2C_DMAError(DMA_HandleTypeDef *hdma);
+
+static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout);
+static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout);
+static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout);
+static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout);
+static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
+static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout);
+
+static HAL_StatusTypeDef I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c);
+static HAL_StatusTypeDef I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c);
+static HAL_StatusTypeDef I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c);
+static HAL_StatusTypeDef I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c);
+
+static HAL_StatusTypeDef I2C_SlaveTransmit_TXE(I2C_HandleTypeDef *hi2c);
+static HAL_StatusTypeDef I2C_SlaveTransmit_BTF(I2C_HandleTypeDef *hi2c);
+static HAL_StatusTypeDef I2C_SlaveReceive_RXNE(I2C_HandleTypeDef *hi2c);
+static HAL_StatusTypeDef I2C_SlaveReceive_BTF(I2C_HandleTypeDef *hi2c);
+static HAL_StatusTypeDef I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c);
+static HAL_StatusTypeDef I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c);
+static HAL_StatusTypeDef I2C_Slave_AF(I2C_HandleTypeDef *hi2c);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup I2C_Private_Functions
+ * @{
+ */
+
+/** @defgroup I2C_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This subsection provides a set of functions allowing to initialize and
+ de-initialiaze the I2Cx peripheral:
+
+ (+) User must Implement HAL_I2C_MspInit() function in which he configures
+ all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC).
+
+ (+) Call the function HAL_I2C_Init() to configure the selected device with
+ the selected configuration:
+ (++) Communication Speed
+ (++) Duty cycle
+ (++) Addressing mode
+ (++) Own Address 1
+ (++) Dual Addressing mode
+ (++) Own Address 2
+ (++) General call mode
+ (++) Nostretch mode
+
+ (+) Call the function HAL_I2C_DeInit() to restore the default configuration
+ of the selected I2Cx periperal.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the I2C according to the specified parameters
+ * in the I2C_InitTypeDef and create the associated handle.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c)
+{
+ uint32_t freqrange = 0;
+ uint32_t pclk1 = 0;
+
+ /* Check the I2C handle allocation */
+ if(hi2c == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
+ assert_param(IS_I2C_CLOCK_SPEED(hi2c->Init.ClockSpeed));
+ assert_param(IS_I2C_DUTY_CYCLE(hi2c->Init.DutyCycle));
+ assert_param(IS_I2C_OWN_ADDRESS1(hi2c->Init.OwnAddress1));
+ assert_param(IS_I2C_ADDRESSING_MODE(hi2c->Init.AddressingMode));
+ assert_param(IS_I2C_DUAL_ADDRESS(hi2c->Init.DualAddressMode));
+ assert_param(IS_I2C_OWN_ADDRESS2(hi2c->Init.OwnAddress2));
+ assert_param(IS_I2C_GENERAL_CALL(hi2c->Init.GeneralCallMode));
+ assert_param(IS_I2C_NO_STRETCH(hi2c->Init.NoStretchMode));
+
+ if(hi2c->State == HAL_I2C_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC */
+ HAL_I2C_MspInit(hi2c);
+ }
+
+ hi2c->State = HAL_I2C_STATE_BUSY;
+
+ /* Disble the selected I2C peripheral */
+ __HAL_I2C_DISABLE(hi2c);
+
+ /* Get PCLK1 frequency */
+ pclk1 = HAL_RCC_GetPCLK1Freq();
+
+ /* Calculate frequency range */
+ freqrange = __HAL_I2C_FREQRANGE(pclk1);
+
+ /*---------------------------- I2Cx CR2 Configuration ----------------------*/
+ /* Configure I2Cx: Frequency range */
+ hi2c->Instance->CR2 = freqrange;
+
+ /*---------------------------- I2Cx TRISE Configuration --------------------*/
+ /* Configure I2Cx: Rise Time */
+ hi2c->Instance->TRISE = __HAL_I2C_RISE_TIME(freqrange, hi2c->Init.ClockSpeed);
+
+ /*---------------------------- I2Cx CCR Configuration ----------------------*/
+ /* Configure I2Cx: Speed */
+ hi2c->Instance->CCR = __HAL_I2C_SPEED(pclk1, hi2c->Init.ClockSpeed, hi2c->Init.DutyCycle);
+
+ /*---------------------------- I2Cx CR1 Configuration ----------------------*/
+ /* Configure I2Cx: Generalcall and NoStretch mode */
+ hi2c->Instance->CR1 = (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode);
+
+ /*---------------------------- I2Cx OAR1 Configuration ---------------------*/
+ /* Configure I2Cx: Own Address1 and addressing mode */
+ hi2c->Instance->OAR1 = (hi2c->Init.AddressingMode | hi2c->Init.OwnAddress1);
+
+ /*---------------------------- I2Cx OAR2 Configuration ---------------------*/
+ /* Configure I2Cx: Dual mode and Own Address2 */
+ hi2c->Instance->OAR2 = (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2);
+
+ /* Enable the selected I2C peripheral */
+ __HAL_I2C_ENABLE(hi2c);
+
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the I2C peripheral.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c)
+{
+ /* Check the I2C handle allocation */
+ if(hi2c == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
+
+ hi2c->State = HAL_I2C_STATE_BUSY;
+
+ /* Disable the I2C Peripheral Clock */
+ __HAL_I2C_DISABLE(hi2c);
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC */
+ HAL_I2C_MspDeInit(hi2c);
+
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->State = HAL_I2C_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief I2C MSP Init.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+ __weak void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2C_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief I2C MSP DeInit
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+ __weak void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2C_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup I2C_Group2 IO operation functions
+ * @brief Data transfers functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the I2C data
+ transfers.
+
+ (#) There is two mode of transfer:
+ (++) Blocking mode : The communication is performed in the polling mode.
+ The status of all data processing is returned by the same function
+ after finishing transfer.
+ (++) No-Blocking mode : The communication is performed using Interrupts
+ or DMA. These functions return the status of the transfer startup.
+ The end of the data processing will be indicated through the
+ dedicated I2C IRQ when using Interrupt mode or the DMA IRQ when
+ using DMA mode.
+
+ (#) Blocking mode functions are :
+ (++) HAL_I2C_Master_Transmit()
+ (++) HAL_I2C_Master_Receive()
+ (++) HAL_I2C_Slave_Transmit()
+ (++) HAL_I2C_Slave_Receive()
+ (++) HAL_I2C_Mem_Write()
+ (++) HAL_I2C_Mem_Read()
+ (++) HAL_I2C_IsDeviceReady()
+
+ (#) No-Blocking mode functions with Interrupt are :
+ (++) HAL_I2C_Master_Transmit_IT()
+ (++) HAL_I2C_Master_Receive_IT()
+ (++) HAL_I2C_Slave_Transmit_IT()
+ (++) HAL_I2C_Slave_Receive_IT()
+ (++) HAL_I2C_Mem_Write_IT()
+ (++) HAL_I2C_Mem_Read_IT()
+
+ (#) No-Blocking mode functions with DMA are :
+ (++) HAL_I2C_Master_Transmit_DMA()
+ (++) HAL_I2C_Master_Receive_DMA()
+ (++) HAL_I2C_Slave_Transmit_DMA()
+ (++) HAL_I2C_Slave_Receive_DMA()
+ (++) HAL_I2C_Mem_Write_DMA()
+ (++) HAL_I2C_Mem_Read_DMA()
+
+ (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode:
+ (++) HAL_I2C_MemTxCpltCallback()
+ (++) HAL_I2C_MemRxCpltCallback()
+ (++) HAL_I2C_MasterTxCpltCallback()
+ (++) HAL_I2C_MasterRxCpltCallback()
+ (++) HAL_I2C_SlaveTxCpltCallback()
+ (++) HAL_I2C_SlaveRxCpltCallback()
+ (++) HAL_I2C_ErrorCallback()
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Transmits in master mode an amount of data in blocking mode.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_TX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ /* Send Slave Address */
+ if(I2C_MasterRequestWrite(hi2c, DevAddress, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ while(Size > 0)
+ {
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Write data to DR */
+ hi2c->Instance->DR = (*pData++);
+ Size--;
+
+ if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (Size != 0))
+ {
+ /* Write data to DR */
+ hi2c->Instance->DR = (*pData++);
+ Size--;
+ }
+ }
+
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receives in master mode an amount of data in blocking mode.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_RX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ /* Send Slave Address */
+ if(I2C_MasterRequestRead(hi2c, DevAddress, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ if(Size == 1)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+ }
+ else if(Size == 2)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Enable Pos */
+ hi2c->Instance->CR1 |= I2C_CR1_POS;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+ else
+ {
+ /* Enable Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+
+ while(Size > 0)
+ {
+ if(Size <= 3)
+ {
+ /* One byte */
+ if(Size == 1)
+ {
+ /* Wait until RXNE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+ }
+ /* Two bytes */
+ else if(Size == 2)
+ {
+ /* Wait until BTF flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+ }
+ /* 3 Last bytes */
+ else
+ {
+ /* Wait until BTF flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+
+ /* Wait until BTF flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+ }
+ }
+ else
+ {
+ /* Wait until RXNE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET)
+ {
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+ }
+ }
+ }
+
+ /* Disable Pos */
+ hi2c->Instance->CR1 &= ~I2C_CR1_POS;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmits in slave mode an amount of data in blocking mode.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_TX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ /* Enable Address Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* If 10bit addressing mode is selected */
+ if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)
+ {
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+
+ while(Size > 0)
+ {
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Write data to DR */
+ hi2c->Instance->DR = (*pData++);
+ Size--;
+
+ if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (Size != 0))
+ {
+ /* Write data to DR */
+ hi2c->Instance->DR = (*pData++);
+ Size--;
+ }
+ }
+
+ /* Wait until AF flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Clear AF flag */
+ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
+
+ /* Disable Address Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive in slave mode an amount of data in blocking mode
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_RX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ /* Enable Address Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ while(Size > 0)
+ {
+ /* Wait until RXNE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+
+ if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (Size != 0))
+ {
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+ }
+ }
+
+ /* Wait until STOP flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Clear STOP flag */
+ __HAL_I2C_CLEAR_STOPFLAG(hi2c);
+
+ /* Disable Address Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit in master mode an amount of data in no-blocking mode with Interrupt
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_TX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Send Slave Address */
+ if(I2C_MasterRequestWrite(hi2c, DevAddress, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ /* Note : The I2C interrupts must be enabled after unlocking current process
+ to avoid the risk of I2C interrupt handle execution before current
+ process unlock */
+
+ /* Enable EVT, BUF and ERR interrupt */
+ __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive in master mode an amount of data in no-blocking mode with Interrupt
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_RX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Send Slave Address */
+ if(I2C_MasterRequestRead(hi2c, DevAddress, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ if(hi2c->XferCount == 1)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+ }
+ else if(hi2c->XferCount == 2)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Enable Pos */
+ hi2c->Instance->CR1 |= I2C_CR1_POS;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+ else
+ {
+ /* Enable Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ /* Note : The I2C interrupts must be enabled after unlocking current process
+ to avoid the risk of I2C interrupt handle execution before current
+ process unlock */
+
+ /* Enable EVT, BUF and ERR interrupt */
+ __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit in slave mode an amount of data in no-blocking mode with Interrupt
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_TX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Enable Address Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ /* Note : The I2C interrupts must be enabled after unlocking current process
+ to avoid the risk of I2C interrupt handle execution before current
+ process unlock */
+
+ /* Enable EVT, BUF and ERR interrupt */
+ __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive in slave mode an amount of data in no-blocking mode with Interrupt
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_RX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Enable Address Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ /* Note : The I2C interrupts must be enabled after unlocking current process
+ to avoid the risk of I2C interrupt handle execution before current
+ process unlock */
+
+ /* Enable EVT, BUF and ERR interrupt */
+ __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit in master mode an amount of data in no-blocking mode with DMA
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_TX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Set the I2C DMA transfert complete callback */
+ hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt;
+
+ /* Set the DMA error callback */
+ hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->DR, Size);
+
+ /* Send Slave Address */
+ if(I2C_MasterRequestWrite(hi2c, DevAddress, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Enable DMA Request */
+ hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive in master mode an amount of data in no-blocking mode with DMA
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_RX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Set the I2C DMA transfert complete callback */
+ hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt;
+
+ /* Set the DMA error callback */
+ hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)pData, Size);
+
+ /* Send Slave Address */
+ if(I2C_MasterRequestRead(hi2c, DevAddress, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ if(Size == 1)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+ }
+ else
+ {
+ /* Enable Last DMA bit */
+ hi2c->Instance->CR2 |= I2C_CR2_LAST;
+ }
+
+ /* Enable DMA Request */
+ hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit in slave mode an amount of data in no-blocking mode with DMA
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_TX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Set the I2C DMA transfert complete callback */
+ hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt;
+
+ /* Set the DMA error callback */
+ hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->DR, Size);
+
+ /* Enable DMA Request */
+ hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
+
+ /* Enable Address Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR_SLAVE) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* If 7bit addressing mode is selected */
+ if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT)
+ {
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+ else
+ {
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR_SLAVE) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive in slave mode an amount of data in no-blocking mode with DMA
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
+{
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY_RX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Set the I2C DMA transfert complete callback */
+ hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt;
+
+ /* Set the DMA error callback */
+ hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)pData, Size);
+
+ /* Enable DMA Request */
+ hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
+
+ /* Enable Address Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR_SLAVE) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+/**
+ * @brief Write an amount of data in blocking mode to a specific memory address
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param MemAddress: Internal memory address
+ * @param MemAddSize: Size of internal memory address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef 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)
+{
+ /* Check the parameters */
+ assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
+
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_MEM_BUSY_TX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ /* Send Slave Address and Memory Address */
+ if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ while(Size > 0)
+ {
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Write data to DR */
+ hi2c->Instance->DR = (*pData++);
+ Size--;
+
+ if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (Size != 0))
+ {
+ /* Write data to DR */
+ hi2c->Instance->DR = (*pData++);
+ Size--;
+ }
+ }
+
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Read an amount of data in blocking mode from a specific memory address
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param MemAddress: Internal memory address
+ * @param MemAddSize: Size of internal memory address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef 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)
+{
+ /* Check the parameters */
+ assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
+
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_MEM_BUSY_RX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ /* Send Slave Address and Memory Address */
+ if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ if(Size == 1)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+ }
+ else if(Size == 2)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Enable Pos */
+ hi2c->Instance->CR1 |= I2C_CR1_POS;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+ else
+ {
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+
+ while(Size > 0)
+ {
+ if(Size <= 3)
+ {
+ /* One byte */
+ if(Size== 1)
+ {
+ /* Wait until RXNE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+ }
+ /* Two bytes */
+ else if(Size == 2)
+ {
+ /* Wait until BTF flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+ }
+ /* 3 Last bytes */
+ else
+ {
+ /* Wait until BTF flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+
+ /* Wait until BTF flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+ }
+ }
+ else
+ {
+ /* Wait until RXNE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET)
+ {
+ /* Read data from DR */
+ (*pData++) = hi2c->Instance->DR;
+ Size--;
+ }
+ }
+ }
+
+ /* Disable Pos */
+ hi2c->Instance->CR1 &= ~I2C_CR1_POS;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+/**
+ * @brief Write an amount of data in no-blocking mode with Interrupt to a specific memory address
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param MemAddress: Internal memory address
+ * @param MemAddSize: Size of internal memory address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
+{
+ /* Check the parameters */
+ assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
+
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_MEM_BUSY_TX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Send Slave Address and Memory Address */
+ if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ /* Note : The I2C interrupts must be enabled after unlocking current process
+ to avoid the risk of I2C interrupt handle execution before current
+ process unlock */
+
+ /* Enable EVT, BUF and ERR interrupt */
+ __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Read an amount of data in no-blocking mode with Interrupt from a specific memory address
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param MemAddress: Internal memory address
+ * @param MemAddSize: Size of internal memory address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
+{
+ /* Check the parameters */
+ assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
+
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_MEM_BUSY_RX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Send Slave Address and Memory Address */
+ if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ if(hi2c->XferCount == 1)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+ }
+ else if(hi2c->XferCount == 2)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Enable Pos */
+ hi2c->Instance->CR1 |= I2C_CR1_POS;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+ else
+ {
+ /* Enable Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ /* Note : The I2C interrupts must be enabled after unlocking current process
+ to avoid the risk of I2C interrupt handle execution before current
+ process unlock */
+
+ /* Enable EVT, BUF and ERR interrupt */
+ __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+/**
+ * @brief Write an amount of data in no-blocking mode with DMA to a specific memory address
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param MemAddress: Internal memory address
+ * @param MemAddSize: Size of internal memory address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
+{
+ /* Check the parameters */
+ assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
+
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_MEM_BUSY_TX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Set the I2C DMA transfert complete callback */
+ hi2c->hdmatx->XferCpltCallback = I2C_DMAMemTransmitCplt;
+
+ /* Set the DMA error callback */
+ hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->DR, Size);
+
+ /* Send Slave Address and Memory Address */
+ if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Enable DMA Request */
+ hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Reads an amount of data in no-blocking mode with DMA from a specific memory address.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param MemAddress: Internal memory address
+ * @param MemAddSize: Size of internal memory address
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be read
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
+{
+ /* Check the parameters */
+ assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
+
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_MEM_BUSY_RX;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
+
+ /* Set the I2C DMA transfert complete callback */
+ hi2c->hdmarx->XferCpltCallback = I2C_DMAMemReceiveCplt;
+
+ /* Set the DMA error callback */
+ hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)pData, Size);
+
+ /* Send Slave Address and Memory Address */
+ if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_TIMEOUT;
+ }
+ }
+
+ if(Size == 1)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+ }
+ else
+ {
+ /* Enable Last DMA bit */
+ hi2c->Instance->CR2 |= I2C_CR2_LAST;
+ }
+
+ /* Enable DMA Request */
+ hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Checks if target device is ready for communication.
+ * @note This function is used with Memory devices
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param Trials: Number of trials
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout)
+{
+ uint32_t timeout = 0, tmp1 = 0, tmp2 = 0, tmp3 = 0, I2C_Trials = 1;
+
+ if(hi2c->State == HAL_I2C_STATE_READY)
+ {
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_BUSY;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+
+ do
+ {
+ /* Generate Start */
+ hi2c->Instance->CR1 |= I2C_CR1_START;
+
+ /* Wait until SB flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Send slave address */
+ hi2c->Instance->DR = __HAL_I2C_7BIT_ADD_WRITE(DevAddress);
+
+ /* Wait until ADDR or AF flag are set */
+ timeout = HAL_GetTick() + Timeout;
+
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR);
+ tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF);
+ tmp3 = hi2c->State;
+ while((tmp1 == RESET) && (tmp2 == RESET) && (tmp3 != HAL_I2C_STATE_TIMEOUT))
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hi2c->State = HAL_I2C_STATE_TIMEOUT;
+ }
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR);
+ tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF);
+ tmp3 = hi2c->State;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Check if the ADDR flag has been set */
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET)
+ {
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Clear ADDR Flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+ }
+ else
+ {
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Clear AF Flag */
+ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }while(I2C_Trials++ < Trials);
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_ERROR;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief This function handles I2C event interrupt request.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c)
+{
+ uint32_t tmp1 = 0, tmp2 = 0, tmp3 = 0, tmp4 = 0;
+ /* Master mode selected */
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_MSL) == SET)
+ {
+ /* I2C in mode Transmitter -----------------------------------------------*/
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TRA) == SET)
+ {
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE);
+ tmp2 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_BUF);
+ tmp3 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF);
+ tmp4 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_EVT);
+ /* TXE set and BTF reset -----------------------------------------------*/
+ if((tmp1 == SET) && (tmp2 == SET) && (tmp3 == RESET))
+ {
+ I2C_MasterTransmit_TXE(hi2c);
+ }
+ /* BTF set -------------------------------------------------------------*/
+ else if((tmp3 == SET) && (tmp4 == SET))
+ {
+ I2C_MasterTransmit_BTF(hi2c);
+ }
+ }
+ /* I2C in mode Receiver --------------------------------------------------*/
+ else
+ {
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE);
+ tmp2 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_BUF);
+ tmp3 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF);
+ tmp4 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_EVT);
+ /* RXNE set and BTF reset -----------------------------------------------*/
+ if((tmp1 == SET) && (tmp2 == SET) && (tmp3 == RESET))
+ {
+ I2C_MasterReceive_RXNE(hi2c);
+ }
+ /* BTF set -------------------------------------------------------------*/
+ else if((tmp3 == SET) && (tmp4 == SET))
+ {
+ I2C_MasterReceive_BTF(hi2c);
+ }
+ }
+ }
+ /* Slave mode selected */
+ else
+ {
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR);
+ tmp2 = __HAL_I2C_GET_IT_SOURCE(hi2c, (I2C_IT_EVT));
+ tmp3 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF);
+ tmp4 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TRA);
+ /* ADDR set --------------------------------------------------------------*/
+ if((tmp1 == SET) && (tmp2 == SET))
+ {
+ I2C_Slave_ADDR(hi2c);
+ }
+ /* STOPF set --------------------------------------------------------------*/
+ else if((tmp3 == SET) && (tmp2 == SET))
+ {
+ I2C_Slave_STOPF(hi2c);
+ }
+ /* I2C in mode Transmitter -----------------------------------------------*/
+ else if(tmp4 == SET)
+ {
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE);
+ tmp2 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_BUF);
+ tmp3 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF);
+ tmp4 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_EVT);
+ /* TXE set and BTF reset -----------------------------------------------*/
+ if((tmp1 == SET) && (tmp2 == SET) && (tmp3 == RESET))
+ {
+ I2C_SlaveTransmit_TXE(hi2c);
+ }
+ /* BTF set -------------------------------------------------------------*/
+ else if((tmp3 == SET) && (tmp4 == SET))
+ {
+ I2C_SlaveTransmit_BTF(hi2c);
+ }
+ }
+ /* I2C in mode Receiver --------------------------------------------------*/
+ else
+ {
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE);
+ tmp2 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_BUF);
+ tmp3 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF);
+ tmp4 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_EVT);
+ /* RXNE set and BTF reset ----------------------------------------------*/
+ if((tmp1 == SET) && (tmp2 == SET) && (tmp3 == RESET))
+ {
+ I2C_SlaveReceive_RXNE(hi2c);
+ }
+ /* BTF set -------------------------------------------------------------*/
+ else if((tmp3 == SET) && (tmp4 == SET))
+ {
+ I2C_SlaveReceive_BTF(hi2c);
+ }
+ }
+ }
+}
+
+/**
+ * @brief This function handles I2C error interrupt request.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c)
+{
+ uint32_t tmp1 = 0, tmp2 = 0, tmp3 = 0;
+
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BERR);
+ tmp2 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERR);
+ /* I2C Bus error interrupt occurred ----------------------------------------*/
+ if((tmp1 == SET) && (tmp2 == SET))
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_BERR;
+
+ /* Clear BERR flag */
+ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR);
+ }
+
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ARLO);
+ tmp2 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERR);
+ /* I2C Arbitration Loss error interrupt occurred ---------------------------*/
+ if((tmp1 == SET) && (tmp2 == SET))
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO;
+
+ /* Clear ARLO flag */
+ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO);
+ }
+
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF);
+ tmp2 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERR);
+ /* I2C Acknowledge failure error interrupt occurred ------------------------*/
+ if((tmp1 == SET) && (tmp2 == SET))
+ {
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_MSL);
+ tmp2 = hi2c->XferCount;
+ tmp3 = hi2c->State;
+ if((tmp1 == RESET) && (tmp2 == 0) && (tmp3 == HAL_I2C_STATE_BUSY_TX))
+ {
+ I2C_Slave_AF(hi2c);
+ }
+ else
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
+ /* Clear AF flag */
+ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
+ }
+ }
+
+ tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_OVR);
+ tmp2 = __HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERR);
+ /* I2C Over-Run/Under-Run interrupt occurred -------------------------------*/
+ if((tmp1 == SET) && (tmp2 == SET))
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_OVR;
+ /* Clear OVR flag */
+ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR);
+ }
+
+ if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
+ {
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ HAL_I2C_ErrorCallback(hi2c);
+ }
+}
+
+/**
+ * @brief Master Tx Transfer completed callbacks.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+ __weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2C_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Master Rx Transfer completed callbacks.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2C_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/** @brief Slave Tx Transfer completed callbacks.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+ __weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2C_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Slave Rx Transfer completed callbacks.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2C_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Memory Tx Transfer completed callbacks.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+ __weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2C_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Memory Rx Transfer completed callbacks.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2C_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief I2C error callbacks.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+ __weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2C_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup I2C_Group3 Peripheral State and Errors functions
+ * @brief Peripheral State and Errors functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State and Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the I2C state.
+ * @param hi2c : I2C handle
+ * @retval HAL state
+ */
+HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c)
+{
+ return hi2c->State;
+}
+
+/**
+ * @brief Return the I2C error code
+ * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+* @retval I2C Error Code
+*/
+uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c)
+{
+ return hi2c->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Handle TXE flag for Master
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ /* Write data to DR */
+ hi2c->Instance->DR = (*hi2c->pBuffPtr++);
+ hi2c->XferCount--;
+
+ if(hi2c->XferCount == 0)
+ {
+ /* Disable BUF interrupt */
+ __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Handle BTF flag for Master transmitter
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ if(hi2c->XferCount != 0)
+ {
+ /* Write data to DR */
+ hi2c->Instance->DR = (*hi2c->pBuffPtr++);
+ hi2c->XferCount--;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ }
+ else
+ {
+ /* Disable EVT, BUF and ERR interrupt */
+ __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ if(hi2c->State == HAL_I2C_STATE_MEM_BUSY_TX)
+ {
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ HAL_I2C_MemTxCpltCallback(hi2c);
+ }
+ else
+ {
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ HAL_I2C_MasterTxCpltCallback(hi2c);
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Handle RXNE flag for Master
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c)
+{
+ uint32_t tmp = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ tmp = hi2c->XferCount;
+ if(tmp > 3)
+ {
+ /* Read data from DR */
+ (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
+ hi2c->XferCount--;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ }
+ else if((tmp == 2) || (tmp == 3))
+ {
+ /* Disable BUF interrupt */
+ __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ }
+ else
+ {
+ /* Disable EVT, BUF and ERR interrupt */
+ __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ /* Read data from DR */
+ (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
+ hi2c->XferCount--;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ if(hi2c->State == HAL_I2C_STATE_MEM_BUSY_RX)
+ {
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ HAL_I2C_MemRxCpltCallback(hi2c);
+ }
+ else
+ {
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ HAL_I2C_MasterRxCpltCallback(hi2c);
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Handle BTF flag for Master receiver
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ if(hi2c->XferCount == 3)
+ {
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Read data from DR */
+ (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
+ hi2c->XferCount--;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ }
+ else if(hi2c->XferCount == 2)
+ {
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Read data from DR */
+ (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
+ hi2c->XferCount--;
+
+ /* Read data from DR */
+ (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
+ hi2c->XferCount--;
+
+ /* Disable EVT and ERR interrupt */
+ __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR);
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ if(hi2c->State == HAL_I2C_STATE_MEM_BUSY_RX)
+ {
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ HAL_I2C_MemRxCpltCallback(hi2c);
+ }
+ else
+ {
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ HAL_I2C_MasterRxCpltCallback(hi2c);
+ }
+ }
+ else
+ {
+ /* Read data from DR */
+ (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
+ hi2c->XferCount--;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Handle TXE flag for Slave
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_SlaveTransmit_TXE(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ if(hi2c->XferCount != 0)
+ {
+ /* Write data to DR */
+ hi2c->Instance->DR = (*hi2c->pBuffPtr++);
+ hi2c->XferCount--;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_OK;
+}
+
+/**
+ * @brief Handle BTF flag for Slave transmitter
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_SlaveTransmit_BTF(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ if(hi2c->XferCount != 0)
+ {
+ /* Write data to DR */
+ hi2c->Instance->DR = (*hi2c->pBuffPtr++);
+ hi2c->XferCount--;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_OK;
+}
+
+/**
+ * @brief Handle RXNE flag for Slave
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_SlaveReceive_RXNE(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ if(hi2c->XferCount != 0)
+ {
+ /* Read data from DR */
+ (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
+ hi2c->XferCount--;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_OK;
+}
+
+/**
+ * @brief Handle BTF flag for Slave receiver
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_SlaveReceive_BTF(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ if(hi2c->XferCount != 0)
+ {
+ /* Read data from DR */
+ (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
+ hi2c->XferCount--;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_OK;
+}
+
+/**
+ * @brief Handle ADD flag for Slave
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+ return HAL_OK;
+}
+
+/**
+ * @brief Handle STOPF flag for Slave
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ /* Disable EVT, BUF and ERR interrupt */
+ __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ /* Clear STOPF flag */
+ __HAL_I2C_CLEAR_STOPFLAG(hi2c);
+
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ HAL_I2C_SlaveRxCpltCallback(hi2c);
+
+ return HAL_OK;
+}
+
+/**
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_Slave_AF(I2C_HandleTypeDef *hi2c)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2c);
+
+ /* Disable EVT, BUF and ERR interrupt */
+ __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+
+ /* Clear AF flag */
+ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
+
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ HAL_I2C_SlaveTxCpltCallback(hi2c);
+
+ return HAL_OK;
+}
+
+/**
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout)
+{
+ /* Generate Start */
+ hi2c->Instance->CR1 |= I2C_CR1_START;
+
+ /* Wait until SB flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT)
+ {
+ /* Send slave address */
+ hi2c->Instance->DR = __HAL_I2C_7BIT_ADD_WRITE(DevAddress);
+ }
+ else
+ {
+ /* Send header of slave address */
+ hi2c->Instance->DR = __HAL_I2C_10BIT_HEADER_WRITE(DevAddress);
+
+ /* Wait until ADD10 flag is set */
+ if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Send slave address */
+ hi2c->Instance->DR = __HAL_I2C_10BIT_ADDRESS(DevAddress);
+ }
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Master sends target device address for read request.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout)
+{
+ /* Enable Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Generate Start */
+ hi2c->Instance->CR1 |= I2C_CR1_START;
+
+ /* Wait until SB flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT)
+ {
+ /* Send slave address */
+ hi2c->Instance->DR = __HAL_I2C_7BIT_ADD_READ(DevAddress);
+ }
+ else
+ {
+ /* Send header of slave address */
+ hi2c->Instance->DR = __HAL_I2C_10BIT_HEADER_WRITE(DevAddress);
+
+ /* Wait until ADD10 flag is set */
+ if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Send slave address */
+ hi2c->Instance->DR = __HAL_I2C_10BIT_ADDRESS(DevAddress);
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Generate Restart */
+ hi2c->Instance->CR1 |= I2C_CR1_START;
+
+ /* Wait until SB flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Send header of slave address */
+ hi2c->Instance->DR = __HAL_I2C_10BIT_HEADER_READ(DevAddress);
+ }
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Master sends target device address followed by internal memory address for write request.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param MemAddress: Internal memory address
+ * @param MemAddSize: Size of internal memory address
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout)
+{
+ /* Generate Start */
+ hi2c->Instance->CR1 |= I2C_CR1_START;
+
+ /* Wait until SB flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Send slave address */
+ hi2c->Instance->DR = __HAL_I2C_7BIT_ADD_WRITE(DevAddress);
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* If Memory address size is 8Bit */
+ if(MemAddSize == I2C_MEMADD_SIZE_8BIT)
+ {
+ /* Send Memory Address */
+ hi2c->Instance->DR = __HAL_I2C_MEM_ADD_LSB(MemAddress);
+ }
+ /* If Memory address size is 16Bit */
+ else
+ {
+ /* Send MSB of Memory Address */
+ hi2c->Instance->DR = __HAL_I2C_MEM_ADD_MSB(MemAddress);
+
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Send LSB of Memory Address */
+ hi2c->Instance->DR = __HAL_I2C_MEM_ADD_LSB(MemAddress);
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Master sends target device address followed by internal memory address for read request.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress: Target device address
+ * @param MemAddress: Internal memory address
+ * @param MemAddSize: Size of internal memory address
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout)
+{
+ /* Enable Acknowledge */
+ hi2c->Instance->CR1 |= I2C_CR1_ACK;
+
+ /* Generate Start */
+ hi2c->Instance->CR1 |= I2C_CR1_START;
+
+ /* Wait until SB flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Send slave address */
+ hi2c->Instance->DR = __HAL_I2C_7BIT_ADD_WRITE(DevAddress);
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Clear ADDR flag */
+ __HAL_I2C_CLEAR_ADDRFLAG(hi2c);
+
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* If Memory address size is 8Bit */
+ if(MemAddSize == I2C_MEMADD_SIZE_8BIT)
+ {
+ /* Send Memory Address */
+ hi2c->Instance->DR = __HAL_I2C_MEM_ADD_LSB(MemAddress);
+ }
+ /* If Memory address size is 16Bit */
+ else
+ {
+ /* Send MSB of Memory Address */
+ hi2c->Instance->DR = __HAL_I2C_MEM_ADD_MSB(MemAddress);
+
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Send LSB of Memory Address */
+ hi2c->Instance->DR = __HAL_I2C_MEM_ADD_LSB(MemAddress);
+ }
+
+ /* Wait until TXE flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Generate Restart */
+ hi2c->Instance->CR1 |= I2C_CR1_START;
+
+ /* Wait until SB flag is set */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Send slave address */
+ hi2c->Instance->DR = __HAL_I2C_7BIT_ADD_READ(DevAddress);
+
+ /* Wait until ADDR flag is set */
+ if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout) != HAL_OK)
+ {
+ if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DMA I2C master transmit process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma)
+{
+ I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Wait until BTF flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Disable DMA Request */
+ hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN;
+
+ hi2c->XferCount = 0;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Check if Errors has been detected during transfer */
+ if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
+ {
+ HAL_I2C_ErrorCallback(hi2c);
+ }
+ else
+ {
+ HAL_I2C_MasterTxCpltCallback(hi2c);
+ }
+}
+
+/**
+ * @brief DMA I2C slave transmit process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma)
+{
+ I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Wait until AF flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ /* Clear AF flag */
+ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
+
+ /* Disable Address Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Disable DMA Request */
+ hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN;
+
+ hi2c->XferCount = 0;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Check if Errors has been detected during transfer */
+ if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
+ {
+ HAL_I2C_ErrorCallback(hi2c);
+ }
+ else
+ {
+ HAL_I2C_SlaveTxCpltCallback(hi2c);
+ }
+}
+
+/**
+ * @brief DMA I2C master receive process complete callback
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma)
+{
+ I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Disable Last DMA */
+ hi2c->Instance->CR2 &= ~I2C_CR2_LAST;
+
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Disable DMA Request */
+ hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN;
+
+ hi2c->XferCount = 0;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Check if Errors has been detected during transfer */
+ if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
+ {
+ HAL_I2C_ErrorCallback(hi2c);
+ }
+ else
+ {
+ HAL_I2C_MasterRxCpltCallback(hi2c);
+ }
+}
+
+/**
+ * @brief DMA I2C slave receive process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma)
+{
+ I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Wait until STOPF flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ /* Clear STOPF flag */
+ __HAL_I2C_CLEAR_STOPFLAG(hi2c);
+
+ /* Disable Address Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Disable DMA Request */
+ hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN;
+
+ hi2c->XferCount = 0;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Check if Errors has been detected during transfer */
+ if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
+ {
+ HAL_I2C_ErrorCallback(hi2c);
+ }
+ else
+ {
+ HAL_I2C_SlaveRxCpltCallback(hi2c);
+ }
+}
+
+/**
+ * @brief DMA I2C Memory Write process complete callback
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void I2C_DMAMemTransmitCplt(DMA_HandleTypeDef *hdma)
+{
+ I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Wait until BTF flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Disable DMA Request */
+ hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN;
+
+ hi2c->XferCount = 0;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Check if Errors has been detected during transfer */
+ if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
+ {
+ HAL_I2C_ErrorCallback(hi2c);
+ }
+ else
+ {
+ HAL_I2C_MemTxCpltCallback(hi2c);
+ }
+}
+
+/**
+ * @brief DMA I2C Memory Read process complete callback
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void I2C_DMAMemReceiveCplt(DMA_HandleTypeDef *hdma)
+{
+ I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Disable Last DMA */
+ hi2c->Instance->CR2 &= ~I2C_CR2_LAST;
+
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ /* Disable DMA Request */
+ hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN;
+
+ hi2c->XferCount = 0;
+
+ /* Wait until BUSY flag is reset */
+ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_FLAG) != HAL_OK)
+ {
+ hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
+ }
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ /* Check if Errors has been detected during transfer */
+ if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
+ {
+ HAL_I2C_ErrorCallback(hi2c);
+ }
+ else
+ {
+ HAL_I2C_MemRxCpltCallback(hi2c);
+ }
+}
+
+/**
+ * @brief DMA I2C communication error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void I2C_DMAError(DMA_HandleTypeDef *hdma)
+{
+ I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Disable Acknowledge */
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+
+ hi2c->XferCount = 0;
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
+
+ HAL_I2C_ErrorCallback(hi2c);
+}
+
+/**
+ * @brief This function handles I2C Communication Timeout.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param Flag: specifies the I2C flag to check.
+ * @param Status: The new Flag status (SET or RESET).
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Wait until flag is set */
+ if(Status == RESET)
+ {
+ while(__HAL_I2C_GET_FLAG(hi2c, Flag) == RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hi2c->State= HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ else
+ {
+ while(__HAL_I2C_GET_FLAG(hi2c, Flag) != RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hi2c->State= HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles I2C Communication Timeout for Master addressing phase.
+ * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param Flag: specifies the I2C flag to check.
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_I2C_GET_FLAG(hi2c, Flag) == RESET)
+ {
+ if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET)
+ {
+ /* Generate Stop */
+ hi2c->Instance->CR1 |= I2C_CR1_STOP;
+
+ /* Clear AF Flag */
+ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
+
+ hi2c->ErrorCode = HAL_I2C_ERROR_AF;
+ hi2c->State= HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_ERROR;
+ }
+
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hi2c->State= HAL_I2C_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2c);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_I2C_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c_ex.c
new file mode 100644
index 0000000..e6a7504
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c_ex.c
@@ -0,0 +1,204 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_i2c_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief I2C Extension HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of I2C extension peripheral:
+ * + Extension features functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### I2C peripheral extension features #####
+ ==============================================================================
+
+ [..] Comparing to other previous devices, the I2C interface for STM32F427X and
+ STM32F429X devices contains the following additional features
+
+ (+) Possibility to disable or enable Analog Noise Filter
+ (+) Use of a configured Digital Noise Filter
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..] This driver provides functions to configure Noise Filter
+ (#) Configure I2C Analog noise filter using the function HAL_I2C_AnalogFilter_Config()
+ (#) Configure I2C Digital noise filter using the function HAL_I2C_DigitalFilter_Config()
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup I2CEx
+ * @brief I2C HAL module driver
+ * @{
+ */
+
+#ifdef HAL_I2C_MODULE_ENABLED
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F401xC) || defined(STM32F401xE)
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup I2CEx_Private_Functions
+ * @{
+ */
+
+
+/** @defgroup I2CEx_Group1 Extension features functions
+ * @brief Extension features functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Extension features functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Configure Noise Filters
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Configures I2C Analog noise filter.
+ * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2Cx peripheral.
+ * @param AnalogFilter : new state of the Analog filter.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2CEx_AnalogFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter)
+{
+ uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
+ assert_param(IS_I2C_ANALOG_FILTER(AnalogFilter));
+
+ tmp = hi2c->State;
+ if((tmp == HAL_I2C_STATE_BUSY) || (tmp == HAL_I2C_STATE_BUSY_TX) || (tmp == HAL_I2C_STATE_BUSY_RX))
+ {
+ return HAL_BUSY;
+ }
+
+ hi2c->State = HAL_I2C_STATE_BUSY;
+
+ /* Disable the selected I2C peripheral */
+ __HAL_I2C_DISABLE(hi2c);
+
+ /* Reset I2Cx ANOFF bit */
+ hi2c->Instance->FLTR &= ~(I2C_FLTR_ANOFF);
+
+ /* Disable the analog filter */
+ hi2c->Instance->FLTR |= AnalogFilter;
+
+ __HAL_I2C_ENABLE(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures I2C Digital noise filter.
+ * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2Cx peripheral.
+ * @param DigitalFilter : Coefficient of digital noise filter between 0x00 and 0x0F.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2CEx_DigitalFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter)
+{
+ uint16_t tmpreg = 0;
+ uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
+ assert_param(IS_I2C_DIGITAL_FILTER(DigitalFilter));
+
+ tmp = hi2c->State;
+ if((tmp == HAL_I2C_STATE_BUSY) || (tmp == HAL_I2C_STATE_BUSY_TX) || (tmp == HAL_I2C_STATE_BUSY_RX))
+ {
+ return HAL_BUSY;
+ }
+
+ hi2c->State = HAL_I2C_STATE_BUSY;
+
+ /* Disable the selected I2C peripheral */
+ __HAL_I2C_DISABLE(hi2c);
+
+ /* Get the old register value */
+ tmpreg = hi2c->Instance->FLTR;
+
+ /* Reset I2Cx DNF bit [3:0] */
+ tmpreg &= ~(I2C_FLTR_DNF);
+
+ /* Set I2Cx DNF coefficient */
+ tmpreg |= DigitalFilter;
+
+ /* Store the new register value */
+ hi2c->Instance->FLTR = tmpreg;
+
+ __HAL_I2C_ENABLE(hi2c);
+
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+#endif /* STM32F427xx || STM32F429xx || STM32F437xx || STM32F439xx || STM32F401xC || STM32F401xE */
+
+#endif /* HAL_I2C_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s.c
new file mode 100644
index 0000000..1e7b41f
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s.c
@@ -0,0 +1,1638 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_i2s.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief I2S HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Integrated Interchip Sound (I2S) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral State and Errors functions
+ @verbatim
+ ===============================================================================
+ ##### How to use this driver #####
+ ===============================================================================
+ [..]
+ The I2S HAL driver can be used as follow:
+
+ (#) Declare a I2S_HandleTypeDef handle structure.
+ (#) Initialize the I2S low level resources by implement the HAL_I2S_MspInit() API:
+ (##) Enable the SPIx interface clock.
+ (##) I2S pins configuration:
+ (+++) Enable the clock for the I2S GPIOs.
+ (+++) Configure these I2S pins as alternate function pull-up.
+ (##) NVIC configuration if you need to use interrupt process (HAL_I2S_Transmit_IT()
+ and HAL_I2S_Receive_IT() APIs).
+ (+++) Configure the I2Sx interrupt priority.
+ (+++) Enable the NVIC I2S IRQ handle.
+ (##) DMA Configuration if you need to use DMA process (HAL_I2S_Transmit_DMA()
+ and HAL_I2S_Receive_DMA() APIs:
+ (+++) Declare a DMA handle structure for the Tx/Rx stream.
+ (+++) Enable the DMAx interface clock.
+ (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.
+ (+++) Configure the DMA Tx/Rx Stream.
+ (+++) Associate the initilalized DMA handle to the I2S DMA Tx/Rx handle.
+ (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the
+ DMA Tx/Rx Stream.
+
+ (#) Program the Mode, Standard, Data Format, MCLK Output, Audio frequency and Polarity
+ using HAL_I2S_Init() function.
+
+ -@- The specific I2S interrupts (Transmission complete interrupt,
+ RXNE interrupt and Error Interrupts) will be managed using the macros
+ __I2S_ENABLE_IT() and __I2S_DISABLE_IT() inside the transmit and receive process.
+ -@- Make sure that either:
+ (+@) I2S PLL is configured or
+ (+@) External clock source is configured after setting correctly
+ the define constant EXTERNAL_CLOCK_VALUE in the stm32f4xx_hal_conf.h file.
+
+ (#) Three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Send an amount of data in blocking mode using HAL_I2S_Transmit()
+ (+) Receive an amount of data in blocking mode using HAL_I2S_Receive()
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Send an amount of data in non blocking mode using HAL_I2S_Transmit_IT()
+ (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback
+ (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode using HAL_I2S_Receive_IT()
+ (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback
+ (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_RxCpltCallback
+ (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_I2S_ErrorCallback
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Send an amount of data in non blocking mode (DMA) using HAL_I2S_Transmit_DMA()
+ (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback
+ (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode (DMA) using HAL_I2S_Receive_DMA()
+ (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback
+ (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_RxCpltCallback
+ (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_I2S_ErrorCallback
+ (+) Pause the DMA Transfer using HAL_I2S_DMAPause()
+ (+) Resume the DMA Transfer using HAL_I2S_DMAResume()
+ (+) Stop the DMA Transfer using HAL_I2S_DMAStop()
+
+ *** I2S HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in USART HAL driver.
+
+ (+) __HAL_I2S_ENABLE: Enable the specified SPI peripheral (in I2S mode)
+ (+) __HAL_I2S_DISABLE: Disable the specified SPI peripheral (in I2S mode)
+ (+) __HAL_I2S_ENABLE_IT : Enable the specified I2S interrupts
+ (+) __HAL_I2S_DISABLE_IT : Disable the specified I2S interrupts
+ (+) __HAL_I2S_GET_FLAG: Check whether the specified I2S flag is set or not
+
+ [..]
+ (@) You can refer to the I2S HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup I2S
+ * @brief I2S HAL module driver
+ * @{
+ */
+
+#ifdef HAL_I2S_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static HAL_StatusTypeDef I2S_Transmit_IT(I2S_HandleTypeDef *hi2s);
+static HAL_StatusTypeDef I2S_Receive_IT(I2S_HandleTypeDef *hi2s);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup I2S_Private_Functions
+ * @{
+ */
+
+/** @defgroup I2S_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This subsection provides a set of functions allowing to initialize and
+ de-initialiaze the I2Sx peripheral in simplex mode:
+
+ (+) User must Implement HAL_I2S_MspInit() function in which he configures
+ all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ).
+
+ (+) Call the function HAL_I2S_Init() to configure the selected device with
+ the selected configuration:
+ (++) Mode
+ (++) Standard
+ (++) Data Format
+ (++) MCLK Output
+ (++) Audio frequency
+ (++) Polarity
+ (++) Full duplex mode
+
+ (+) Call the function HAL_I2S_DeInit() to restore the default configuration
+ of the selected I2Sx periperal.
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the I2S according to the specified parameters
+ * in the I2S_InitTypeDef and create the associated handle.
+ * @param hi2s: I2S handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s)
+{
+ uint32_t tmpreg = 0, i2sdiv = 2, i2sodd = 0, packetlength = 1;
+ uint32_t tmp = 0, i2sclk = 0;
+
+ /* Check the I2S handle allocation */
+ if(hi2s == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the I2S parameters */
+ assert_param(IS_I2S_MODE(hi2s->Init.Mode));
+ assert_param(IS_I2S_STANDARD(hi2s->Init.Standard));
+ assert_param(IS_I2S_DATA_FORMAT(hi2s->Init.DataFormat));
+ assert_param(IS_I2S_MCLK_OUTPUT(hi2s->Init.MCLKOutput));
+ assert_param(IS_I2S_AUDIO_FREQ(hi2s->Init.AudioFreq));
+ assert_param(IS_I2S_CPOL(hi2s->Init.CPOL));
+ assert_param(IS_I2S_CLOCKSOURCE(hi2s->Init.ClockSource));
+ assert_param(IS_I2S_FULLDUPLEX_MODE(hi2s->Init.FullDuplexMode));
+
+ if(hi2s->State == HAL_I2S_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
+ HAL_I2S_MspInit(hi2s);
+ }
+
+ hi2s->State = HAL_I2S_STATE_BUSY;
+
+ /*----------------------- SPIx I2SCFGR & I2SPR Configuration ---------------*/
+ /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */
+ hi2s->Instance->I2SCFGR &= ~(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CKPOL | \
+ SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG | \
+ SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD);
+ hi2s->Instance->I2SPR = 0x0002;
+
+ /* Get the I2SCFGR register value */
+ tmpreg = hi2s->Instance->I2SCFGR;
+
+ /* If the default frequency value has to be written, reinitialize i2sdiv and i2sodd */
+ /* If the requested audio frequency is not the default, compute the prescaler */
+ if(hi2s->Init.AudioFreq != I2S_AUDIOFREQ_DEFAULT)
+ {
+ /* Check the frame length (For the Prescaler computing) *******************/
+ if(hi2s->Init.DataFormat != I2S_DATAFORMAT_16B)
+ {
+ /* Packet length is 32 bits */
+ packetlength = 2;
+ }
+
+ /* Get I2S source Clock frequency ****************************************/
+ /* If an external I2S clock has to be used, the specific define should be set
+ in the project configuration or in the stm32f4xx_conf.h file */
+ if(hi2s->Init.ClockSource == I2S_CLOCK_EXTERNAL)
+ {
+ /* Set external clock as I2S clock source */
+ if((RCC->CFGR & RCC_CFGR_I2SSRC) == 0)
+ {
+ RCC->CFGR |= (uint32_t)RCC_CFGR_I2SSRC;
+ }
+
+ /* Set the I2S clock to the external clock value */
+ i2sclk = EXTERNAL_CLOCK_VALUE;
+ }
+ else
+ {
+ /* Check if PLLI2S is enabled or Not */
+ if((RCC->CR & RCC_CR_PLLI2SON) != RCC_CR_PLLI2SON)
+ {
+ hi2s->State= HAL_I2S_STATE_READY;
+
+ return HAL_ERROR;
+ }
+
+ /* Set PLLI2S as I2S clock source */
+ if((RCC->CFGR & RCC_CFGR_I2SSRC) != 0)
+ {
+ RCC->CFGR &= ~(uint32_t)RCC_CFGR_I2SSRC;
+ }
+
+ /* Get the PLLM value */
+ if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE)
+ {
+ /* Get the I2S source clock value */
+ i2sclk = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM));
+ }
+ else
+ {
+ /* Get the I2S source clock value */
+ i2sclk = (uint32_t)(HSI_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM));
+ }
+ i2sclk *= (uint32_t)(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6) & (RCC_PLLI2SCFGR_PLLI2SN >> 6));
+ i2sclk /= (uint32_t)(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28) & (RCC_PLLI2SCFGR_PLLI2SR >> 28));
+ }
+
+ /* Compute the Real divider depending on the MCLK output state, with a floating point */
+ if(hi2s->Init.MCLKOutput == I2S_MCLKOUTPUT_ENABLE)
+ {
+ /* MCLK output is enabled */
+ tmp = (uint32_t)(((((i2sclk / 256) * 10) / hi2s->Init.AudioFreq)) + 5);
+ }
+ else
+ {
+ /* MCLK output is disabled */
+ tmp = (uint32_t)(((((i2sclk / (32 * packetlength)) *10 ) / hi2s->Init.AudioFreq)) + 5);
+ }
+
+ /* Remove the flatting point */
+ tmp = tmp / 10;
+
+ /* Check the parity of the divider */
+ i2sodd = (uint32_t)(tmp & (uint32_t)1);
+
+ /* Compute the i2sdiv prescaler */
+ i2sdiv = (uint32_t)((tmp - i2sodd) / 2);
+
+ /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */
+ i2sodd = (uint32_t) (i2sodd << 8);
+ }
+
+ /* Test if the divider is 1 or 0 or greater than 0xFF */
+ if((i2sdiv < 2) || (i2sdiv > 0xFF))
+ {
+ /* Set the default values */
+ i2sdiv = 2;
+ i2sodd = 0;
+ }
+
+ /* Write to SPIx I2SPR register the computed value */
+ hi2s->Instance->I2SPR = (uint32_t)((uint32_t)i2sdiv | (uint32_t)(i2sodd | (uint32_t)hi2s->Init.MCLKOutput));
+
+ /* Configure the I2S with the I2S_InitStruct values */
+ tmpreg |= (uint32_t)(SPI_I2SCFGR_I2SMOD | hi2s->Init.Mode | hi2s->Init.Standard | hi2s->Init.DataFormat | hi2s->Init.CPOL);
+
+ /* Write to SPIx I2SCFGR */
+ hi2s->Instance->I2SCFGR = tmpreg;
+
+ /* Configure the I2S extended if the full duplex mode is enabled */
+ if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE)
+ {
+ /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */
+ I2SxEXT(hi2s->Instance)->I2SCFGR &= ~(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CKPOL | \
+ SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG | \
+ SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD);
+ I2SxEXT(hi2s->Instance)->I2SPR = 2;
+
+ /* Get the I2SCFGR register value */
+ tmpreg = I2SxEXT(hi2s->Instance)->I2SCFGR;
+
+ /* Get the mode to be configured for the extended I2S */
+ if((hi2s->Init.Mode == I2S_MODE_MASTER_TX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_TX))
+ {
+ tmp = I2S_MODE_SLAVE_RX;
+ }
+ else
+ {
+ if((hi2s->Init.Mode == I2S_MODE_MASTER_RX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_RX))
+ {
+ tmp = I2S_MODE_SLAVE_TX;
+ }
+ }
+
+ /* Configure the I2S Slave with the I2S Master parameter values */
+ tmpreg |= (uint32_t)(SPI_I2SCFGR_I2SMOD | tmp | hi2s->Init.Standard | hi2s->Init.DataFormat | hi2s->Init.CPOL);
+
+ /* Write to SPIx I2SCFGR */
+ I2SxEXT(hi2s->Instance)->I2SCFGR = tmpreg;
+ }
+
+ hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
+ hi2s->State= HAL_I2S_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the I2S peripheral
+ * @param hi2s: I2S handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s)
+{
+ /* Check the I2S handle allocation */
+ if(hi2s == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ hi2s->State = HAL_I2S_STATE_BUSY;
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */
+ HAL_I2S_MspDeInit(hi2s);
+
+ hi2s->State = HAL_I2S_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief I2S MSP Init
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+ __weak void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2S_MspInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief I2S MSP DeInit
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+ __weak void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2S_MspDeInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup I2S_Group2 IO operation functions
+ * @brief Data transfers functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the I2S data
+ transfers.
+
+ (#) There is two mode of transfer:
+ (++) Blocking mode : The communication is performed in the polling mode.
+ The status of all data processing is returned by the same function
+ after finishing transfer.
+ (++) No-Blocking mode : The communication is performed using Interrupts
+ or DMA. These functions return the status of the transfer startup.
+ The end of the data processing will be indicated through the
+ dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when
+ using DMA mode.
+
+ (#) Blocking mode functions are :
+ (++) HAL_I2S_Transmit()
+ (++) HAL_I2S_Receive()
+
+ (#) No-Blocking mode functions with Interrupt are :
+ (++) HAL_I2S_Transmit_IT()
+ (++) HAL_I2S_Receive_IT()
+
+ (#) No-Blocking mode functions with DMA are :
+ (++) HAL_I2S_Transmit_DMA()
+ (++) HAL_I2S_Receive_DMA()
+
+ (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode:
+ (++) HAL_I2S_TxCpltCallback()
+ (++) HAL_I2S_RxCpltCallback()
+ (++) HAL_I2S_ErrorCallback()
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Transmit an amount of data in blocking mode
+ * @param hi2s: I2S handle
+ * @param pData: a 16-bit pointer to data buffer.
+ * @param Size: number of data sample to be sent:
+ * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
+ * configuration phase, the Size parameter means the number of 16-bit data length
+ * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
+ * the Size parameter means the number of 16-bit data length.
+ * @param Timeout: Timeout duration
+ * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
+ * between Master and Slave(example: audio streaming).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(hi2s->State == HAL_I2S_STATE_READY)
+ {
+ tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ if((tmp1 == I2S_DATAFORMAT_24B)|| \
+ (tmp2 == I2S_DATAFORMAT_32B))
+ {
+ hi2s->TxXferSize = Size*2;
+ hi2s->TxXferCount = Size*2;
+ }
+ else
+ {
+ hi2s->TxXferSize = Size;
+ hi2s->TxXferCount = Size;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ hi2s->State = HAL_I2S_STATE_BUSY_TX;
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2S peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+
+ while(hi2s->TxXferCount > 0)
+ {
+ hi2s->Instance->DR = (*pData++);
+ hi2s->TxXferCount--;
+ /* Wait until TXE flag is set */
+ if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Wait until Busy flag is reset */
+ if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_BSY, SET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hi2s->State = HAL_I2S_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in blocking mode
+ * @param hi2s: I2S handle
+ * @param pData: a 16-bit pointer to data buffer.
+ * @param Size: number of data sample to be sent:
+ * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
+ * configuration phase, the Size parameter means the number of 16-bit data length
+ * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
+ * the Size parameter means the number of 16-bit data length.
+ * @param Timeout: Timeout duration
+ * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
+ * between Master and Slave(example: audio streaming).
+ * @note In I2S Master Receiver mode, just after enabling the peripheral the clock will be generate
+ * in continouse way and as the I2S is not disabled at the end of the I2S transaction.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(hi2s->State == HAL_I2S_STATE_READY)
+ {
+ tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ if((tmp1 == I2S_DATAFORMAT_24B)|| \
+ (tmp2 == I2S_DATAFORMAT_32B))
+ {
+ hi2s->RxXferSize = Size*2;
+ hi2s->RxXferCount = Size*2;
+ }
+ else
+ {
+ hi2s->RxXferSize = Size;
+ hi2s->RxXferCount = Size;
+ }
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ hi2s->State = HAL_I2S_STATE_BUSY_RX;
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2S peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+
+ /* Check if Master Receiver mode is selected */
+ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX)
+ {
+ /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read
+ access to the SPI_SR register. */
+ __HAL_I2S_CLEAR_OVRFLAG(hi2s);
+ }
+
+ /* Receive data */
+ while(hi2s->RxXferCount > 0)
+ {
+ /* Wait until RXNE flag is set */
+ if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ (*pData++) = hi2s->Instance->DR;
+ hi2s->RxXferCount--;
+ }
+
+ hi2s->State = HAL_I2S_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit an amount of data in non-blocking mode with Interrupt
+ * @param hi2s: I2S handle
+ * @param pData: a 16-bit pointer to data buffer.
+ * @param Size: number of data sample to be sent:
+ * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
+ * configuration phase, the Size parameter means the number of 16-bit data length
+ * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
+ * the Size parameter means the number of 16-bit data length.
+ * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
+ * between Master and Slave(example: audio streaming).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+ if(hi2s->State == HAL_I2S_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ hi2s->pTxBuffPtr = pData;
+ tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ if((tmp1 == I2S_DATAFORMAT_24B)|| \
+ (tmp2 == I2S_DATAFORMAT_32B))
+ {
+ hi2s->TxXferSize = Size*2;
+ hi2s->TxXferCount = Size*2;
+ }
+ else
+ {
+ hi2s->TxXferSize = Size;
+ hi2s->TxXferCount = Size;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ hi2s->State = HAL_I2S_STATE_BUSY_TX;
+ hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
+
+ /* Enable TXE and ERR interrupt */
+ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR));
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2S peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in non-blocking mode with Interrupt
+ * @param hi2s: I2S handle
+ * @param pData: a 16-bit pointer to the Receive data buffer.
+ * @param Size: number of data sample to be sent:
+ * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
+ * configuration phase, the Size parameter means the number of 16-bit data length
+ * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
+ * the Size parameter means the number of 16-bit data length.
+ * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
+ * between Master and Slave(example: audio streaming).
+ * @note It is recommended to use DMA for the I2S receiver to avoid de-synchronisation
+ * between Master and Slave otherwise the I2S interrupt should be optimized.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+ if(hi2s->State == HAL_I2S_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ hi2s->pRxBuffPtr = pData;
+ tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ if((tmp1 == I2S_DATAFORMAT_24B)||\
+ (tmp2 == I2S_DATAFORMAT_32B))
+ {
+ hi2s->RxXferSize = Size*2;
+ hi2s->RxXferCount = Size*2;
+ }
+ else
+ {
+ hi2s->RxXferSize = Size;
+ hi2s->RxXferCount = Size;
+ }
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ hi2s->State = HAL_I2S_STATE_BUSY_RX;
+ hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
+
+ /* Enable TXE and ERR interrupt */
+ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR));
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2S peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit an amount of data in non-blocking mode with DMA
+ * @param hi2s: I2S handle
+ * @param pData: a 16-bit pointer to the Transmit data buffer.
+ * @param Size: number of data sample to be sent:
+ * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
+ * configuration phase, the Size parameter means the number of 16-bit data length
+ * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
+ * the Size parameter means the number of 16-bit data length.
+ * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
+ * between Master and Slave(example: audio streaming).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(hi2s->State == HAL_I2S_STATE_READY)
+ {
+ hi2s->pTxBuffPtr = pData;
+ tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ if((tmp1 == I2S_DATAFORMAT_24B)|| \
+ (tmp2 == I2S_DATAFORMAT_32B))
+ {
+ hi2s->TxXferSize = Size*2;
+ hi2s->TxXferCount = Size*2;
+ }
+ else
+ {
+ hi2s->TxXferSize = Size;
+ hi2s->TxXferCount = Size;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ hi2s->State = HAL_I2S_STATE_BUSY_TX;
+ hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
+
+ /* Set the I2S Tx DMA Half transfert complete callback */
+ hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt;
+
+ /* Set the I2S Tx DMA transfert complete callback */
+ hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt;
+
+ /* Set the DMA error callback */
+ hi2s->hdmatx->XferErrorCallback = I2S_DMAError;
+
+ /* Enable the Tx DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t*)tmp, (uint32_t)&hi2s->Instance->DR, hi2s->TxXferSize);
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2S peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+
+ /* Check if the I2S Tx request is already enabled */
+ if((hi2s->Instance->CR2 & SPI_CR2_TXDMAEN) != SPI_CR2_TXDMAEN)
+ {
+ /* Enable Tx DMA Request */
+ hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in non-blocking mode with DMA
+ * @param hi2s: I2S handle
+ * @param pData: a 16-bit pointer to the Receive data buffer.
+ * @param Size: number of data sample to be sent:
+ * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
+ * configuration phase, the Size parameter means the number of 16-bit data length
+ * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
+ * the Size parameter means the number of 16-bit data length.
+ * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
+ * between Master and Slave(example: audio streaming).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(hi2s->State == HAL_I2S_STATE_READY)
+ {
+ hi2s->pRxBuffPtr = pData;
+ tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ if((tmp1 == I2S_DATAFORMAT_24B)|| \
+ (tmp2 == I2S_DATAFORMAT_32B))
+ {
+ hi2s->RxXferSize = Size*2;
+ hi2s->RxXferCount = Size*2;
+ }
+ else
+ {
+ hi2s->RxXferSize = Size;
+ hi2s->RxXferCount = Size;
+ }
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ hi2s->State = HAL_I2S_STATE_BUSY_RX;
+ hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
+
+ /* Set the I2S Rx DMA Half transfert complete callback */
+ hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt;
+
+ /* Set the I2S Rx DMA transfert complete callback */
+ hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt;
+
+ /* Set the DMA error callback */
+ hi2s->hdmarx->XferErrorCallback = I2S_DMAError;
+
+ /* Check if Master Receiver mode is selected */
+ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX)
+ {
+ /* Clear the Overrun Flag by a read operation to the SPI_DR register followed by a read
+ access to the SPI_SR register. */
+ __HAL_I2S_CLEAR_OVRFLAG(hi2s);
+ }
+
+ /* Enable the Rx DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DR, *(uint32_t*)tmp, hi2s->RxXferSize);
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2S peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+
+ /* Check if the I2S Rx request is already enabled */
+ if((hi2s->Instance->CR2 &SPI_CR2_RXDMAEN) != SPI_CR2_RXDMAEN)
+ {
+ /* Enable Rx DMA Request */
+ hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Pauses the audio stream playing from the Media.
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ if(hi2s->State == HAL_I2S_STATE_BUSY_TX)
+ {
+ /* Disable the I2S DMA Tx request */
+ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
+ }
+ else if(hi2s->State == HAL_I2S_STATE_BUSY_RX)
+ {
+ /* Disable the I2S DMA Rx request */
+ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
+ }
+ else if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX)
+ {
+ if((hi2s->Init.Mode == I2S_MODE_SLAVE_TX)||(hi2s->Init.Mode == I2S_MODE_MASTER_TX))
+ {
+ /* Disable the I2S DMA Tx request */
+ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
+ /* Disable the I2SEx Rx DMA Request */
+ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
+ }
+ else
+ {
+ /* Disable the I2S DMA Rx request */
+ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
+ /* Disable the I2SEx Tx DMA Request */
+ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
+ }
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Resumes the audio stream playing from the Media.
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ if(hi2s->State == HAL_I2S_STATE_BUSY_TX)
+ {
+ /* Enable the I2S DMA Tx request */
+ hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN;
+ }
+ else if(hi2s->State == HAL_I2S_STATE_BUSY_RX)
+ {
+ /* Enable the I2S DMA Rx request */
+ hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN;
+ }
+ else if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX)
+ {
+ if((hi2s->Init.Mode == I2S_MODE_SLAVE_TX)||(hi2s->Init.Mode == I2S_MODE_MASTER_TX))
+ {
+ /* Enable the I2S DMA Tx request */
+ hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN;
+ /* Disable the I2SEx Rx DMA Request */
+ I2SxEXT(hi2s->Instance)->CR2 |= SPI_CR2_RXDMAEN;
+ }
+ else
+ {
+ /* Enable the I2S DMA Rx request */
+ hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN;
+ /* Enable the I2SEx Tx DMA Request */
+ I2SxEXT(hi2s->Instance)->CR2 |= SPI_CR2_TXDMAEN;
+ }
+ }
+
+ /* If the I2S peripheral is still not enabled, enable it */
+ if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) == 0)
+ {
+ /* Enable I2S peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Resumes the audio stream playing from the Media.
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s)
+{
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ /* Disable the I2S Tx/Rx DMA requests */
+ hi2s->Instance->CR2 &= ~SPI_CR2_TXDMAEN;
+ hi2s->Instance->CR2 &= ~SPI_CR2_RXDMAEN;
+
+ if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE)
+ {
+ /* Disable the I2S extended Tx/Rx DMA requests */
+ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
+ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
+ }
+
+ /* Abort the I2S DMA Stream tx */
+ if(hi2s->hdmatx != NULL)
+ {
+ HAL_DMA_Abort(hi2s->hdmatx);
+ }
+ /* Abort the I2S DMA Stream rx */
+ if(hi2s->hdmarx != NULL)
+ {
+ HAL_DMA_Abort(hi2s->hdmarx);
+ }
+
+ /* Disable I2S peripheral */
+ __HAL_I2S_DISABLE(hi2s);
+
+ if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE)
+ {
+ /* Disable the I2Sext peripheral */
+ I2SxEXT(hi2s->Instance)->I2SCFGR &= ~SPI_I2SCFGR_I2SE;
+ }
+
+ hi2s->State = HAL_I2S_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles I2S interrupt request.
+ * @param hi2s: I2S handle
+ * @retval HAL status
+ */
+void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+ if(hi2s->Init.FullDuplexMode != I2S_FULLDUPLEXMODE_ENABLE)
+ {
+ if(hi2s->State == HAL_I2S_STATE_BUSY_RX)
+ {
+ tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXNE);
+ tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_RXNE);
+ /* I2S in mode Receiver ------------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ I2S_Receive_IT(hi2s);
+ }
+
+ tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR);
+ tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR);
+ /* I2S Overrun error interrupt occured ---------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_I2S_CLEAR_OVRFLAG(hi2s);
+ hi2s->ErrorCode |= HAL_I2S_ERROR_OVR;
+ }
+ }
+
+ if(hi2s->State == HAL_I2S_STATE_BUSY_TX)
+ {
+ tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXE);
+ tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_TXE);
+ /* I2S in mode Tramitter -----------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ I2S_Transmit_IT(hi2s);
+ }
+
+ tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR);
+ tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR);
+ /* I2S Underrun error interrupt occured --------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_I2S_CLEAR_UDRFLAG(hi2s);
+ hi2s->ErrorCode |= HAL_I2S_ERROR_UDR;
+ }
+ }
+ }
+ else
+ {
+ tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */
+ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX))
+ {
+ tmp1 = I2SxEXT(hi2s->Instance)->SR & SPI_SR_RXNE;
+ tmp2 = I2SxEXT(hi2s->Instance)->CR2 & I2S_IT_RXNE;
+ /* I2Sext in mode Receiver ---------------------------------------------*/
+ if((tmp1 == SPI_SR_RXNE) && (tmp2 == I2S_IT_RXNE))
+ {
+ tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ /* When the I2S mode is configured as I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX,
+ the I2Sext RXNE interrupt will be generated to manage the full-duplex receive phase. */
+ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX))
+ {
+ I2SEx_TransmitReceive_IT(hi2s);
+ }
+ }
+
+ tmp1 = I2SxEXT(hi2s->Instance)->SR & SPI_SR_OVR;
+ tmp2 = I2SxEXT(hi2s->Instance)->CR2 & I2S_IT_ERR;
+ /* I2Sext Overrun error interrupt occured ------------------------------*/
+ if((tmp1 == SPI_SR_OVR) && (tmp2 == I2S_IT_ERR))
+ {
+ /* Clear I2Sext OVR Flag */
+ I2SxEXT(hi2s->Instance)->DR;
+ I2SxEXT(hi2s->Instance)->SR;
+ hi2s->ErrorCode |= HAL_I2SEX_ERROR_OVR;
+ }
+
+ tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXE);
+ tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_TXE);
+ /* I2S in mode Tramitter -----------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ /* When the I2S mode is configured as I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX,
+ the I2S TXE interrupt will be generated to manage the full-duplex transmit phase. */
+ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX))
+ {
+ I2SEx_TransmitReceive_IT(hi2s);
+ }
+ }
+
+ tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR);
+ tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR);
+ /* I2S Underrun error interrupt occured --------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_I2S_CLEAR_UDRFLAG(hi2s);
+ hi2s->ErrorCode |= HAL_I2S_ERROR_UDR;
+ }
+ }
+ /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */
+ else
+ {
+ tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXNE);
+ tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_RXNE);
+ /* I2S in mode Receiver ------------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ /* When the I2S mode is configured as I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX,
+ the I2S RXNE interrupt will be generated to manage the full-duplex receive phase. */
+ if((tmp1 == I2S_MODE_MASTER_RX) || (tmp2 == I2S_MODE_SLAVE_RX))
+ {
+ I2SEx_TransmitReceive_IT(hi2s);
+ }
+ }
+
+ tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR);
+ tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR);
+ /* I2S Overrun error interrupt occured ---------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_I2S_CLEAR_OVRFLAG(hi2s);
+ hi2s->ErrorCode |= HAL_I2S_ERROR_OVR;
+ }
+
+ tmp1 = I2SxEXT(hi2s->Instance)->SR & SPI_SR_TXE;
+ tmp2 = I2SxEXT(hi2s->Instance)->CR2 & I2S_IT_TXE;
+ /* I2Sext in mode Tramitter --------------------------------------------*/
+ if((tmp1 == SPI_SR_TXE) && (tmp2 == I2S_IT_TXE))
+ {
+ tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ /* When the I2S mode is configured as I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX,
+ the I2Sext TXE interrupt will be generated to manage the full-duplex transmit phase. */
+ if((tmp1 == I2S_MODE_MASTER_RX) || (tmp2 == I2S_MODE_SLAVE_RX))
+ {
+ I2SEx_TransmitReceive_IT(hi2s);
+ }
+ }
+
+ tmp1 = I2SxEXT(hi2s->Instance)->SR & SPI_SR_UDR;
+ tmp2 = I2SxEXT(hi2s->Instance)->CR2 & I2S_IT_ERR;
+ /* I2Sext Underrun error interrupt occured -----------------------------*/
+ if((tmp1 == SPI_SR_UDR) && (tmp2 == I2S_IT_ERR))
+ {
+ /* Clear I2Sext UDR Flag */
+ I2SxEXT(hi2s->Instance)->SR;
+ hi2s->ErrorCode |= HAL_I2SEX_ERROR_UDR;
+ }
+ }
+ }
+
+ /* Call the Error call Back in case of Errors */
+ if(hi2s->ErrorCode != HAL_I2S_ERROR_NONE)
+ {
+ /* Set the I2S state ready to be able to start again the process */
+ hi2s->State= HAL_I2S_STATE_READY;
+ HAL_I2S_ErrorCallback(hi2s);
+ }
+}
+
+/**
+ * @brief Tx Transfer Half completed callbacks
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+ __weak void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2S_TxHalfCpltCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Tx Transfer completed callbacks
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+ __weak void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2S_TxCpltCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer half completed callbacks
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+__weak void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2S_RxCpltCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer completed callbacks
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+__weak void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2S_RxCpltCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief I2S error callbacks
+ * @param hi2s: I2S handle
+ * @retval None
+ */
+ __weak void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_I2S_ErrorCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup I2S_Group3 Peripheral State and Errors functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State and Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the I2S state
+ * @param hi2s : I2S handle
+ * @retval HAL state
+ */
+HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s)
+{
+ return hi2s->State;
+}
+
+/**
+ * @brief Return the I2S error code
+ * @param hi2s : I2S handle
+ * @retval I2S Error Code
+ */
+HAL_I2S_ErrorTypeDef HAL_I2S_GetError(I2S_HandleTypeDef *hi2s)
+{
+ return hi2s->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief DMA I2S transmit process complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+void I2S_DMATxCplt(DMA_HandleTypeDef *hdma)
+{
+ I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
+ {
+ hi2s->TxXferCount = 0;
+
+ /* Disable Tx DMA Request */
+ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
+
+ if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE)
+ {
+ /* Disable Rx DMA Request for the slave*/
+ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
+ }
+
+ if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX)
+ {
+ if(hi2s->RxXferCount == 0)
+ {
+ hi2s->State = HAL_I2S_STATE_READY;
+ }
+ }
+ else
+ {
+ hi2s->State = HAL_I2S_STATE_READY;
+ }
+ }
+ HAL_I2S_TxCpltCallback(hi2s);
+}
+
+/**
+ * @brief DMA I2S transmit process half complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma)
+{
+ I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ HAL_I2S_TxHalfCpltCallback(hi2s);
+}
+
+/**
+ * @brief DMA I2S receive process complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+void I2S_DMARxCplt(DMA_HandleTypeDef *hdma)
+{
+ I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
+ {
+ /* Disable Rx DMA Request */
+ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
+
+ if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE)
+ {
+ /* Disable Tx DMA Request for the slave*/
+ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
+ }
+
+ hi2s->RxXferCount = 0;
+ if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX)
+ {
+ if(hi2s->TxXferCount == 0)
+ {
+ hi2s->State = HAL_I2S_STATE_READY;
+ }
+ }
+ else
+ {
+ hi2s->State = HAL_I2S_STATE_READY;
+ }
+ }
+ HAL_I2S_RxCpltCallback(hi2s);
+}
+
+/**
+ * @brief DMA I2S receive process half complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
+{
+ I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ HAL_I2S_RxHalfCpltCallback(hi2s);
+}
+
+/**
+ * @brief DMA I2S communication error callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+void I2S_DMAError(DMA_HandleTypeDef *hdma)
+{
+ I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ hi2s->TxXferCount = 0;
+ hi2s->RxXferCount = 0;
+
+ hi2s->State= HAL_I2S_STATE_READY;
+
+ hi2s->ErrorCode |= HAL_I2S_ERROR_DMA;
+ HAL_I2S_ErrorCallback(hi2s);
+}
+
+/**
+ * @brief Transmit an amount of data in non-blocking mode with Interrupt
+ * @param hi2s: I2S handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2S_Transmit_IT(I2S_HandleTypeDef *hi2s)
+{
+ if(hi2s->State == HAL_I2S_STATE_BUSY_TX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ /* Transmit data */
+ hi2s->Instance->DR = (*hi2s->pTxBuffPtr++);
+
+ hi2s->TxXferCount--;
+
+ if(hi2s->TxXferCount == 0)
+ {
+ /* Disable TXE and ERR interrupt */
+ __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR));
+
+ hi2s->State = HAL_I2S_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+ HAL_I2S_TxCpltCallback(hi2s);
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+ }
+
+ return HAL_OK;
+ }
+
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in non-blocking mode with Interrupt
+ * @param hi2s: I2S handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2S_Receive_IT(I2S_HandleTypeDef *hi2s)
+{
+ if(hi2s->State == HAL_I2S_STATE_BUSY_RX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ /* Receive data */
+ (*hi2s->pRxBuffPtr++) = hi2s->Instance->DR;
+
+ hi2s->RxXferCount--;
+
+ /* Check if Master Receiver mode is selected */
+ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX)
+ {
+ /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read
+ access to the SPI_SR register. */
+ __HAL_I2S_CLEAR_OVRFLAG(hi2s);
+ }
+
+ if(hi2s->RxXferCount == 0)
+ {
+ /* Disable RXNE and ERR interrupt */
+ __HAL_I2S_DISABLE_IT(hi2s, I2S_IT_RXNE | I2S_IT_ERR);
+
+ hi2s->State = HAL_I2S_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ HAL_I2S_RxCpltCallback(hi2s);
+ }
+ else
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+ }
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief This function handles I2S Communication Timeout.
+ * @param hi2s: I2S handle
+ * @param Flag: Flag checked
+ * @param State: Value of the flag expected
+ * @param Timeout: Duration of the timeout
+ * @retval HAL status
+ */
+HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t Status, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Wait until flag is set */
+ if(Status == RESET)
+ {
+ while(__HAL_I2S_GET_FLAG(hi2s, Flag) == RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Set the I2S State ready */
+ hi2s->State= HAL_I2S_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ else
+ {
+ while(__HAL_I2S_GET_FLAG(hi2s, Flag) != RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Set the I2S State ready */
+ hi2s->State= HAL_I2S_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_I2S_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s_ex.c
new file mode 100644
index 0000000..eb24725
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s_ex.c
@@ -0,0 +1,748 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_i2s_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief I2S HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of I2S extension peripheral:
+ * + Extension features Functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### I2S Extension features #####
+ ==============================================================================
+ [..]
+ (#) In I2S full duplex mode, each SPI peripheral is able to manage sending and receiving
+ data simultaneously using two data lines. Each SPI peripheral has an extended block
+ called I2Sxext ie. I2S2ext for SPI2 and I2S3ext for SPI3).
+ (#) The extension block is not a full SPI IP, it is used only as I2S slave to
+ implement full duplex mode. The extension block uses the same clock sources
+ as its master.
+
+ (#) Both I2Sx and I2Sx_ext can be configured as transmitters or receivers.
+
+ -@- Only I2Sx can deliver SCK and WS to I2Sx_ext in full duplex mode, where
+ I2Sx can be I2S2 or I2S3.
+
+ ===============================================================================
+ ##### How to use this driver #####
+ ===============================================================================
+ [..]
+ Three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Send and receive in the same time an amount of data in blocking mode using HAL_I2S_TransmitReceive()
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Send and receive in the same time an amount of data in non blocking mode using HAL_I2S_TransmitReceive_IT()
+ (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback
+ (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_TxCpltCallback
+ (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback
+ (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_RxCpltCallback
+ (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_I2S_ErrorCallback
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Send and receive an amount of data in non blocking mode (DMA) using HAL_I2S_TransmitReceive_DMA()
+ (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback
+ (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_TxCpltCallback
+ (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback
+ (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_I2S_RxCpltCallback
+ (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_I2S_ErrorCallback
+ (+) Pause the DMA Transfer using HAL_I2S_DMAPause()
+ (+) Resume the DMA Transfer using HAL_I2S_DMAResume()
+ (+) Stop the DMA Transfer using HAL_I2S_DMAStop()
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup I2SEx
+ * @brief I2S HAL module driver
+ * @{
+ */
+
+#ifdef HAL_I2S_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup I2SEx_Private_Functions
+ * @{
+ */
+
+/** @defgroup I2SEx_Group1 Extension features functions
+ * @brief Extension features functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Extension features Functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the I2S data
+ transfers.
+
+ (#) There is two mode of transfer:
+ (++) Blocking mode : The communication is performed in the polling mode.
+ The status of all data processing is returned by the same function
+ after finishing transfer.
+ (++) No-Blocking mode : The communication is performed using Interrupts
+ or DMA. These functions return the status of the transfer startup.
+ The end of the data processing will be indicated through the
+ dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when
+ using DMA mode.
+
+ (#) Blocking mode functions are :
+ (++) HAL_I2S_TransmitReceive()
+
+ (#) No-Blocking mode functions with Interrupt are :
+ (++) HAL_I2S_TransmitReceive_IT()
+
+ (#) No-Blocking mode functions with DMA are :
+ (++) HAL_I2S_TransmitReceive_DMA()
+
+ (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode:
+ (++) HAL_I2S_TxCpltCallback()
+ (++) HAL_I2S_RxCpltCallback()
+ (++) HAL_I2S_ErrorCallback()
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Full-Duplex Transmit/Receive data in blocking mode.
+ * @param hi2s: I2S handle
+ * @param pTxData: a 16-bit pointer to the Transmit data buffer.
+ * @param pRxData: a 16-bit pointer to the Receive data buffer.
+ * @param Size: number of data sample to be sent:
+ * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
+ * configuration phase, the Size parameter means the number of 16-bit data length
+ * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
+ * the Size parameter means the number of 16-bit data length.
+ * @param Timeout: Timeout duration
+ * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
+ * between Master and Slave(example: audio streaming).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the I2S State */
+ if(hi2s->State == HAL_I2S_STATE_READY)
+ {
+ tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ /* Check the Data format: When a 16-bit data frame or a 16-bit data frame extended
+ is selected during the I2S configuration phase, the Size parameter means the number
+ of 16-bit data length in the transaction and when a 24-bit data frame or a 32-bit data
+ frame is selected the Size parameter means the number of 16-bit data length. */
+ if((tmp1 == I2S_DATAFORMAT_24B)|| \
+ (tmp2 == I2S_DATAFORMAT_32B))
+ {
+ hi2s->TxXferSize = Size*2;
+ hi2s->TxXferCount = Size*2;
+ hi2s->RxXferSize = Size*2;
+ hi2s->RxXferCount = Size*2;
+ }
+ else
+ {
+ hi2s->TxXferSize = Size;
+ hi2s->TxXferCount = Size;
+ hi2s->RxXferSize = Size;
+ hi2s->RxXferCount = Size;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ /* Set the I2S State busy TX/RX */
+ hi2s->State = HAL_I2S_STATE_BUSY_TX_RX;
+
+ tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */
+ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX))
+ {
+ /* Check if the I2S is already enabled: The I2S is kept enabled at the end of transaction
+ to avoid the clock de-synchronization between Master and Slave. */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2Sext(receiver) before enabling I2Sx peripheral */
+ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE;
+
+ /* Enable I2Sx peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+
+ while(hi2s->TxXferCount > 0)
+ {
+ /* Wait until TXE flag is set */
+ if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ hi2s->Instance->DR = (*pTxData++);
+
+ /* Wait until RXNE flag is set */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((I2SxEXT(hi2s->Instance)->SR & SPI_SR_RXNE) != SPI_SR_RXNE)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ (*pRxData++) = I2SxEXT(hi2s->Instance)->DR;
+
+ hi2s->TxXferCount--;
+ hi2s->RxXferCount--;
+ }
+ }
+ /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */
+ else
+ {
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2S peripheral before the I2Sext*/
+ __HAL_I2S_ENABLE(hi2s);
+
+ /* Enable I2Sext(transmitter) after enabling I2Sx peripheral */
+ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE;
+ }
+ else
+ {
+ /* Check if Master Receiver mode is selected */
+ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX)
+ {
+ /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read
+ access to the SPI_SR register. */
+ __HAL_I2S_CLEAR_OVRFLAG(hi2s);
+ }
+ }
+ while(hi2s->TxXferCount > 0)
+ {
+ /* Wait until TXE flag is set */
+ timeout = HAL_GetTick() + Timeout;
+
+ while((I2SxEXT(hi2s->Instance)->SR & SPI_SR_TXE) != SPI_SR_TXE)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ I2SxEXT(hi2s->Instance)->DR = (*pTxData++);
+
+ /* Wait until RXNE flag is set */
+ if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ (*pRxData++) = hi2s->Instance->DR;
+
+ hi2s->TxXferCount--;
+ hi2s->RxXferCount--;
+ }
+ }
+
+ /* Set the I2S State ready */
+ hi2s->State = HAL_I2S_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Full-Duplex Transmit/Receive data in non-blocking mode using Interrupt
+ * @param hi2s: I2S handle
+ * @param pTxData: a 16-bit pointer to the Transmit data buffer.
+ * @param pRxData: a 16-bit pointer to the Receive data buffer.
+ * @param Size: number of data sample to be sent:
+ * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
+ * configuration phase, the Size parameter means the number of 16-bit data length
+ * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
+ * the Size parameter means the number of 16-bit data length.
+ * @param Timeout: Timeout duration
+ * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
+ * between Master and Slave(example: audio streaming).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ if(hi2s->State == HAL_I2S_STATE_READY)
+ {
+ if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ hi2s->pTxBuffPtr = pTxData;
+ hi2s->pRxBuffPtr = pRxData;
+
+ tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ /* Check the Data format: When a 16-bit data frame or a 16-bit data frame extended
+ is selected during the I2S configuration phase, the Size parameter means the number
+ of 16-bit data length in the transaction and when a 24-bit data frame or a 32-bit data
+ frame is selected the Size parameter means the number of 16-bit data length. */
+ if((tmp1 == I2S_DATAFORMAT_24B)||\
+ (tmp2 == I2S_DATAFORMAT_32B))
+ {
+ hi2s->TxXferSize = Size*2;
+ hi2s->TxXferCount = Size*2;
+ hi2s->RxXferSize = Size*2;
+ hi2s->RxXferCount = Size*2;
+ }
+ else
+ {
+ hi2s->TxXferSize = Size;
+ hi2s->TxXferCount = Size;
+ hi2s->RxXferSize = Size;
+ hi2s->RxXferCount = Size;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ hi2s->State = HAL_I2S_STATE_BUSY_TX_RX;
+ hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
+
+ tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */
+ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX))
+ {
+ /* Enable I2Sext RXNE and ERR interrupts */
+ I2SxEXT(hi2s->Instance)->CR2 |= (I2S_IT_RXNE | I2S_IT_ERR);
+
+ /* Enable I2Sx TXE and ERR interrupts */
+ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR));
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2Sext(receiver) before enabling I2Sx peripheral */
+ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE;
+
+ /* Enable I2Sx peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+ }
+ /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */
+ else
+ {
+ /* Enable I2Sext TXE and ERR interrupts */
+ I2SxEXT(hi2s->Instance)->CR2 |= (I2S_IT_TXE |I2S_IT_ERR);
+
+ /* Enable I2Sext RXNE and ERR interrupts */
+ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR));
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Check if the I2S_MODE_MASTER_RX is selected */
+ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX)
+ {
+ /* Prepare the First Data before enabling the I2S */
+ if(hi2s->TxXferCount != 0)
+ {
+ /* Transmit First data */
+ I2SxEXT(hi2s->Instance)->DR = (*hi2s->pTxBuffPtr++);
+ hi2s->TxXferCount--;
+
+ if(hi2s->TxXferCount == 0)
+ {
+ /* Disable I2Sext TXE interrupt */
+ I2SxEXT(hi2s->Instance)->CR2 &= ~I2S_IT_TXE;
+ }
+ }
+ }
+ /* Enable I2S peripheral */
+ __HAL_I2S_ENABLE(hi2s);
+
+ /* Enable I2Sext(transmitter) after enabling I2Sx peripheral */
+ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE;
+ }
+ }
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+
+/**
+ * @brief Full-Duplex Transmit/Receive data in non-blocking mode using DMA
+ * @param hi2s: I2S handle
+ * @param pTxData: a 16-bit pointer to the Transmit data buffer.
+ * @param pRxData: a 16-bit pointer to the Receive data buffer.
+ * @param Size: number of data sample to be sent:
+ * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
+ * configuration phase, the Size parameter means the number of 16-bit data length
+ * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
+ * the Size parameter means the number of 16-bit data length.
+ * @param Timeout: Timeout duration
+ * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
+ * between Master and Slave(example: audio streaming).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size)
+{
+ uint32_t *tmp;
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(hi2s->State == HAL_I2S_STATE_READY)
+ {
+ hi2s->pTxBuffPtr = pTxData;
+ hi2s->pRxBuffPtr = pRxData;
+
+ tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
+ /* Check the Data format: When a 16-bit data frame or a 16-bit data frame extended
+ is selected during the I2S configuration phase, the Size parameter means the number
+ of 16-bit data length in the transaction and when a 24-bit data frame or a 32-bit data
+ frame is selected the Size parameter means the number of 16-bit data length. */
+ if((tmp1 == I2S_DATAFORMAT_24B)||\
+ (tmp2 == I2S_DATAFORMAT_32B))
+ {
+ hi2s->TxXferSize = Size*2;
+ hi2s->TxXferCount = Size*2;
+ hi2s->RxXferSize = Size*2;
+ hi2s->RxXferCount = Size*2;
+ }
+ else
+ {
+ hi2s->TxXferSize = Size;
+ hi2s->TxXferCount = Size;
+ hi2s->RxXferSize = Size;
+ hi2s->RxXferCount = Size;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ hi2s->State = HAL_I2S_STATE_BUSY_TX_RX;
+ hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
+
+ /* Set the I2S Rx DMA Half transfert complete callback */
+ hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt;
+
+ /* Set the I2S Rx DMA transfert complete callback */
+ hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt;
+
+ /* Set the I2S Rx DMA error callback */
+ hi2s->hdmarx->XferErrorCallback = I2S_DMAError;
+
+ /* Set the I2S Tx DMA Half transfert complete callback */
+ hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt;
+
+ /* Set the I2S Tx DMA transfert complete callback */
+ hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt;
+
+ /* Set the I2S Tx DMA error callback */
+ hi2s->hdmatx->XferErrorCallback = I2S_DMAError;
+
+ tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */
+ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX))
+ {
+ /* Enable the Rx DMA Stream */
+ tmp = (uint32_t*)&pRxData;
+ HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&I2SxEXT(hi2s->Instance)->DR, *(uint32_t*)tmp, hi2s->RxXferSize);
+
+ /* Enable Rx DMA Request */
+ I2SxEXT(hi2s->Instance)->CR2 |= SPI_CR2_RXDMAEN;
+
+ /* Enable the Tx DMA Stream */
+ tmp = (uint32_t*)&pTxData;
+ HAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t*)tmp, (uint32_t)&hi2s->Instance->DR, hi2s->TxXferSize);
+
+ /* Enable Tx DMA Request */
+ hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN;
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2Sext(receiver) before enabling I2Sx peripheral */
+ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE;
+
+ /* Enable I2S peripheral after the I2Sext */
+ __HAL_I2S_ENABLE(hi2s);
+ }
+ }
+ else
+ {
+ /* Enable the Tx DMA Stream */
+ tmp = (uint32_t*)&pTxData;
+ HAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t*)tmp, (uint32_t)&I2SxEXT(hi2s->Instance)->DR, hi2s->TxXferSize);
+
+ /* Enable Tx DMA Request */
+ I2SxEXT(hi2s->Instance)->CR2 |= SPI_CR2_TXDMAEN;
+
+ /* Enable the Rx DMA Stream */
+ tmp = (uint32_t*)&pRxData;
+ HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DR, *(uint32_t*)tmp, hi2s->RxXferSize);
+
+ /* Enable Rx DMA Request */
+ hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN;
+
+ /* Check if the I2S is already enabled */
+ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
+ {
+ /* Enable I2S peripheral before the I2Sext */
+ __HAL_I2S_ENABLE(hi2s);
+
+ /* Enable I2Sext(transmitter) after enabling I2Sx peripheral */
+ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE;
+ }
+ else
+ {
+ /* Check if Master Receiver mode is selected */
+ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX)
+ {
+ /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read
+ access to the SPI_SR register. */
+ __HAL_I2S_CLEAR_OVRFLAG(hi2s);
+ }
+ }
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Full-Duplex Transmit/Receive data in non-blocking mode using Interrupt
+ * @param hi2s: I2S handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hi2s);
+
+ tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG;
+ /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */
+ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX))
+ {
+ if(hi2s->TxXferCount != 0)
+ {
+ if(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXE) != RESET)
+ {
+ /* Transmit data */
+ hi2s->Instance->DR = (*hi2s->pTxBuffPtr++);
+ hi2s->TxXferCount--;
+
+ if(hi2s->TxXferCount == 0)
+ {
+ /* Disable TXE interrupt */
+ __HAL_I2S_DISABLE_IT(hi2s, I2S_IT_TXE);
+ }
+ }
+ }
+
+ if(hi2s->RxXferCount != 0)
+ {
+ if((I2SxEXT(hi2s->Instance)->SR & SPI_SR_RXNE) == SPI_SR_RXNE)
+ {
+ /* Receive data */
+ (*hi2s->pRxBuffPtr++) = I2SxEXT(hi2s->Instance)->DR;
+ hi2s->RxXferCount--;
+
+ if(hi2s->RxXferCount == 0)
+ {
+ /* Disable I2Sext RXNE interrupt */
+ I2SxEXT(hi2s->Instance)->CR2 &= ~I2S_IT_RXNE;
+ }
+ }
+ }
+ }
+ /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */
+ else
+ {
+ if(hi2s->TxXferCount != 0)
+ {
+ if((I2SxEXT(hi2s->Instance)->SR & SPI_SR_TXE) == SPI_SR_TXE)
+ {
+ /* Transmit data */
+ I2SxEXT(hi2s->Instance)->DR = (*hi2s->pTxBuffPtr++);
+ hi2s->TxXferCount--;
+
+ if(hi2s->TxXferCount == 0)
+ {
+ /* Disable I2Sext TXE interrupt */
+ I2SxEXT(hi2s->Instance)->CR2 &= ~I2S_IT_TXE;
+
+ HAL_I2S_TxCpltCallback(hi2s);
+ }
+ }
+ }
+ if(hi2s->RxXferCount != 0)
+ {
+ if(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXNE) != RESET)
+ {
+ /* Receive data */
+ (*hi2s->pRxBuffPtr++) = hi2s->Instance->DR;
+ hi2s->RxXferCount--;
+
+ if(hi2s->RxXferCount == 0)
+ {
+ /* Disable RXNE interrupt */
+ __HAL_I2S_DISABLE_IT(hi2s, I2S_IT_RXNE);
+
+ HAL_I2S_RxCpltCallback(hi2s);
+ }
+ }
+ }
+ }
+
+ tmp1 = hi2s->RxXferCount;
+ tmp2 = hi2s->TxXferCount;
+ if((tmp1 == 0) && (tmp2 == 0))
+ {
+ /* Disable I2Sx ERR interrupt */
+ __HAL_I2S_DISABLE_IT(hi2s, I2S_IT_ERR);
+ /* Disable I2Sext ERR interrupt */
+ I2SxEXT(hi2s->Instance)->CR2 &= ~I2S_IT_ERR;
+
+ hi2s->State = HAL_I2S_STATE_READY;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hi2s);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_I2S_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_irda.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_irda.c
new file mode 100644
index 0000000..bc0b384
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_irda.c
@@ -0,0 +1,1302 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_irda.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief IRDA HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the IrDA SIR ENDEC block (IrDA):
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral State and Errors functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The IRDA HAL driver can be used as follow:
+
+ (#) Declare a IRDA_HandleTypeDef handle structure.
+ (#) Initialize the IRDA low level resources by implement the HAL_IRDA_MspInit() API:
+ (##) Enable the USARTx interface clock.
+ (##) IRDA pins configuration:
+ (+++) Enable the clock for the IRDA GPIOs.
+ (+++) Configure these IRDA pins as alternate function pull-up.
+ (##) NVIC configuration if you need to use interrupt process (HAL_IRDA_Transmit_IT()
+ and HAL_IRDA_Receive_IT() APIs):
+ (+++) Configure the USARTx interrupt priority.
+ (+++) Enable the NVIC USART IRQ handle.
+ (##) DMA Configuration if you need to use DMA process (HAL_IRDA_Transmit_DMA()
+ and HAL_IRDA_Receive_DMA() APIs):
+ (+++) Declare a DMA handle structure for the Tx/Rx stream.
+ (+++) Enable the DMAx interface clock.
+ (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.
+ (+++) Configure the DMA Tx/Rx Stream.
+ (+++) Associate the initilalized DMA handle to the IRDA DMA Tx/Rx handle.
+ (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream.
+
+ (#) Program the Baud Rate, Word Length, Parity, IrDA Mode, Prescaler
+ and Mode(Receiver/Transmitter) in the hirda Init structure.
+
+ (#) Initialize the IRDA registers by calling the HAL_IRDA_Init() API:
+ (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc)
+ by calling the customed HAL_IRDA_MspInit() API.
+ -@@- The specific IRDA interrupts (Transmission complete interrupt,
+ RXNE interrupt and Error Interrupts) will be managed using the macros
+ __HAL_IRDA_ENABLE_IT() and __HAL_IRDA_DISABLE_IT() inside the transmit and receive process.
+
+ (#) Three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Send an amount of data in blocking mode using HAL_IRDA_Transmit()
+ (+) Receive an amount of data in blocking mode using HAL_IRDA_Receive()
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Send an amount of data in non blocking mode using HAL_IRDA_Transmit_IT()
+ (+) At transmission end of transfer HAL_IRDA_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_IRDA_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode using HAL_IRDA_Receive_IT()
+ (+) At reception end of transfer HAL_IRDA_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_IRDA_RxCpltCallback
+ (+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_IRDA_ErrorCallback
+
+ *** DMA mode IO operation ***
+ =============================
+ [..]
+ (+) Send an amount of data in non blocking mode (DMA) using HAL_IRDA_Transmit_DMA()
+ (+) At transmission end of transfer HAL_IRDA_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_IRDA_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode (DMA) using HAL_IRDA_Receive_DMA()
+ (+) At reception end of transfer HAL_IRDA_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_IRDA_RxCpltCallback
+ (+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_IRDA_ErrorCallback
+
+ *** IRDA HAL driver macros list ***
+ ===================================
+ [..]
+ Below the list of most used macros in IRDA HAL driver.
+
+ (+) __HAL_IRDA_ENABLE: Enable the IRDA peripheral
+ (+) __HAL_IRDA_DISABLE: Disable the IRDA peripheral
+ (+) __HAL_IRDA_GET_FLAG : Checks whether the specified IRDA flag is set or not
+ (+) __HAL_IRDA_CLEAR_FLAG : Clears the specified IRDA pending flag
+ (+) __HAL_IRDA_ENABLE_IT: Enables the specified IRDA interrupt
+ (+) __HAL_IRDA_DISABLE_IT: Disables the specified IRDA interrupt
+
+ (@) You can refer to the IRDA HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup IRDA
+ * @brief HAL IRDA module driver
+ * @{
+ */
+
+#ifdef HAL_IRDA_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define IRDA_TIMEOUT_VALUE 22000
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void IRDA_SetConfig (IRDA_HandleTypeDef *hirda);
+static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda);
+static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda);
+static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma);
+static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
+static void IRDA_DMAError(DMA_HandleTypeDef *hdma);
+static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup IRDA_Private_Functions
+ * @{
+ */
+
+/** @defgroup IRDA_Group1 IrDA Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+
+===============================================================================
+ ##### Initialization and Configuration functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to initialize the USARTx or the UARTy
+ in IrDA mode.
+ (+) For the asynchronous mode only these parameters can be configured:
+ (++) BaudRate
+ (++) WordLength
+ (++) Parity: If the parity is enabled, then the MSB bit of the data written
+ in the data register is transmitted but is changed by the parity bit.
+ Depending on the frame length defined by the M bit (8-bits or 9-bits),
+ the possible IRDA frame formats are as listed in the following table:
+ +-------------------------------------------------------------+
+ | M bit | PCE bit | IRDA frame |
+ |---------------------|---------------------------------------|
+ | 0 | 0 | | SB | 8 bit data | STB | |
+ |---------|-----------|---------------------------------------|
+ | 0 | 1 | | SB | 7 bit data | PB | STB | |
+ |---------|-----------|---------------------------------------|
+ | 1 | 0 | | SB | 9 bit data | STB | |
+ |---------|-----------|---------------------------------------|
+ | 1 | 1 | | SB | 8 bit data | PB | STB | |
+ +-------------------------------------------------------------+
+ (++) Prescaler: A pulse of width less than two and greater than one PSC period(s) may or may
+ not be rejected. The receiver set up time should be managed by software. The IrDA physical layer
+ specification specifies a minimum of 10 ms delay between transmission and
+ reception (IrDA is a half duplex protocol).
+ (++) Mode: Receiver/transmitter modes
+ (++) IrDAMode: the IrDA can operate in the Normal mode or in the Low power mode.
+ [..]
+ The HAL_IRDA_Init() API follows IRDA configuration procedures (details for the procedures
+ are available in reference manual).
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the IRDA mode according to the specified
+ * parameters in the IRDA_InitTypeDef and create the associated handle.
+ * @param hirda: IRDA handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda)
+{
+ /* Check the IRDA handle allocation */
+ if(hirda == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the IRDA instance parameters */
+ assert_param(IS_IRDA_INSTANCE(hirda->Instance));
+ /* Check the IRDA mode parameter in the IRDA handle */
+ assert_param(IS_IRDA_POWERMODE(hirda->Init.IrDAMode));
+
+ if(hirda->State == HAL_IRDA_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
+ HAL_IRDA_MspInit(hirda);
+ }
+
+ hirda->State = HAL_IRDA_STATE_BUSY;
+
+ /* Disable the IRDA peripheral */
+ __IRDA_DISABLE(hirda);
+
+ /* Set the IRDA communication parameters */
+ IRDA_SetConfig(hirda);
+
+ /* In IrDA mode, the following bits must be kept cleared:
+ - LINEN, STOP and CLKEN bits in the USART_CR2 register,
+ - SCEN and HDSEL bits in the USART_CR3 register.*/
+ hirda->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_STOP | USART_CR2_CLKEN);
+ hirda->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL);
+
+ /* Enable the IRDA peripheral */
+ __IRDA_ENABLE(hirda);
+
+ /* Set the prescaler */
+ MODIFY_REG(hirda->Instance->GTPR, USART_GTPR_PSC, hirda->Init.Prescaler);
+
+ /* Configure the IrDA mode */
+ MODIFY_REG(hirda->Instance->CR3, USART_CR3_IRLP, hirda->Init.IrDAMode);
+
+ /* Enable the IrDA mode by setting the IREN bit in the CR3 register */
+ hirda->Instance->CR3 |= USART_CR3_IREN;
+
+ /* Initialize the IRDA state*/
+ hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
+ hirda->State= HAL_IRDA_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the IRDA peripheral
+ * @param hirda: IRDA handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda)
+{
+ /* Check the IRDA handle allocation */
+ if(hirda == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_IRDA_INSTANCE(hirda->Instance));
+
+ hirda->State = HAL_IRDA_STATE_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_IRDA_MspDeInit(hirda);
+
+ hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
+
+ hirda->State = HAL_IRDA_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief IRDA MSP Init.
+ * @param hirda: IRDA handle
+ * @retval None
+ */
+ __weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_IRDA_MspInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief IRDA MSP DeInit.
+ * @param hirda: IRDA handle
+ * @retval None
+ */
+ __weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_IRDA_MspDeInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup IRDA_Group2 IO operation functions
+ * @brief IRDA Transmit/Receive functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ This subsection provides a set of functions allowing to manage the IRDA data transfers.
+ [..]
+ IrDA is a half duplex communication protocol. If the Transmitter is busy, any data
+ on the IrDA receive line will be ignored by the IrDA decoder and if the Receiver
+ is busy, data on the TX from the USART to IrDA will not be encoded by IrDA.
+ While receiving data, transmission should be avoided as the data to be transmitted
+ could be corrupted.
+
+ (#) There are two mode of transfer:
+ (++) Blocking mode: The communication is performed in polling mode.
+ The HAL status of all data processing is returned by the same function
+ after finishing transfer.
+ (++) No-Blocking mode: The communication is performed using Interrupts
+ or DMA, These API's return the HAL status.
+ The end of the data processing will be indicated through the
+ dedicated IRDA IRQ when using Interrupt mode or the DMA IRQ when
+ using DMA mode.
+ The HAL_IRDA_TxCpltCallback(), HAL_IRDA_RxCpltCallback() user callbacks
+ will be executed respectivelly at the end of the transmit or Receive process
+ The HAL_IRDA_ErrorCallback()user callback will be executed when a communication error is detected
+
+ (#) Blocking mode API's are :
+ (++) HAL_IRDA_Transmit()
+ (++) HAL_IRDA_Receive()
+
+ (#) Non-Blocking mode API's with Interrupt are :
+ (++) HAL_IRDA_Transmit_IT()
+ (++) HAL_IRDA_Receive_IT()
+ (++) HAL_IRDA_IRQHandler()
+
+ (#) No-Blocking mode functions with DMA are :
+ (++) HAL_IRDA_Transmit_DMA()
+ (++) HAL_IRDA_Receive_DMA()
+
+ (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode:
+ (++) HAL_IRDA_TxCpltCallback()
+ (++) HAL_IRDA_RxCpltCallback()
+ (++) HAL_IRDA_ErrorCallback()
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Sends an amount of data in blocking mode.
+ * @param hirda: IRDA handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @param Timeout: Specify timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ uint16_t* tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = hirda->State;
+ if((tmp1 == HAL_IRDA_STATE_READY) || (tmp1 == HAL_IRDA_STATE_BUSY_RX))
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hirda);
+
+ hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
+ if(hirda->State == HAL_IRDA_STATE_BUSY_RX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX;
+ }
+
+ hirda->TxXferSize = Size;
+ hirda->TxXferCount = Size;
+ while(hirda->TxXferCount > 0)
+ {
+ hirda->TxXferCount--;
+ if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B)
+ {
+ if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pData;
+ hirda->Instance->DR = (*tmp & (uint16_t)0x01FF);
+ if(hirda->Init.Parity == IRDA_PARITY_NONE)
+ {
+ pData +=2;
+ }
+ else
+ {
+ pData +=1;
+ }
+ }
+ else
+ {
+ if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ hirda->Instance->DR = (*pData++ & (uint8_t)0xFF);
+ }
+ }
+
+ if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_RX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_READY;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in blocking mode.
+ * @param hirda: IRDA handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @param Timeout: Specify timeout value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ uint16_t* tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = hirda->State;
+ if((tmp1 == HAL_IRDA_STATE_READY) || (tmp1 == HAL_IRDA_STATE_BUSY_TX))
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hirda);
+
+ hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
+ if(hirda->State == HAL_IRDA_STATE_BUSY_TX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_RX;
+ }
+ hirda->RxXferSize = Size;
+ hirda->RxXferCount = Size;
+ /* Check the remain data to be received */
+ while(hirda->RxXferCount > 0)
+ {
+ hirda->RxXferCount--;
+ if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B)
+ {
+ if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pData ;
+ if(hirda->Init.Parity == IRDA_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(hirda->Instance->DR & (uint16_t)0x01FF);
+ pData +=2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(hirda->Instance->DR & (uint16_t)0x00FF);
+ pData +=1;
+ }
+ }
+ else
+ {
+ if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ if(hirda->Init.Parity == IRDA_PARITY_NONE)
+ {
+ *pData++ = (uint8_t)(hirda->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ *pData++ = (uint8_t)(hirda->Instance->DR & (uint8_t)0x007F);
+ }
+ }
+ }
+ if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_READY;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Send an amount of data in non blocking mode.
+ * @param hirda: IRDA handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
+{
+ uint32_t tmp1 = 0;
+
+ tmp1 = hirda->State;
+ if((tmp1 == HAL_IRDA_STATE_READY) || (tmp1 == HAL_IRDA_STATE_BUSY_RX))
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+ /* Process Locked */
+ __HAL_LOCK(hirda);
+
+ hirda->pTxBuffPtr = pData;
+ hirda->TxXferSize = Size;
+ hirda->TxXferCount = Size;
+ hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
+ if(hirda->State == HAL_IRDA_STATE_BUSY_RX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX;
+ }
+
+ /* Enable the IRDA Parity Error Interrupt */
+ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_PE);
+
+ /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
+ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_ERR);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ /* Enable the IRDA Transmit Complete Interrupt */
+ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_TC);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receives an amount of data in non blocking mode.
+ * @param hirda: IRDA handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
+{
+ uint32_t tmp1 = 0;
+
+ tmp1 = hirda->State;
+ if((tmp1 == HAL_IRDA_STATE_READY) || (tmp1 == HAL_IRDA_STATE_BUSY_TX))
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hirda);
+
+ hirda->pRxBuffPtr = pData;
+ hirda->RxXferSize = Size;
+ hirda->RxXferCount = Size;
+ hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
+ if(hirda->State == HAL_IRDA_STATE_BUSY_TX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_RX;
+ }
+
+ /* Enable the IRDA Data Register not empty Interrupt */
+ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_RXNE);
+
+ /* Enable the IRDA Parity Error Interrupt */
+ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_PE);
+
+ /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
+ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_ERR);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Sends an amount of data in non blocking mode.
+ * @param hirda: IRDA handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = hirda->State;
+ if((tmp1 == HAL_IRDA_STATE_READY) || (tmp1 == HAL_IRDA_STATE_BUSY_RX))
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hirda);
+
+ hirda->pTxBuffPtr = pData;
+ hirda->TxXferSize = Size;
+ hirda->TxXferCount = Size;
+ hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
+
+ if(hirda->State == HAL_IRDA_STATE_BUSY_RX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX;
+ }
+
+ /* Set the IRDA DMA transfert complete callback */
+ hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt;
+
+ /* Set the DMA error callback */
+ hirda->hdmatx->XferErrorCallback = IRDA_DMAError;
+
+ /* Enable the IRDA transmit DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(hirda->hdmatx, *(uint32_t*)tmp, (uint32_t)&hirda->Instance->DR, Size);
+
+ /* Enable the DMA transfer for transmit request by setting the DMAT bit
+ in the USART CR3 register */
+ hirda->Instance->CR3 |= USART_CR3_DMAT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receives an amount of data in non blocking mode.
+ * @param hirda: IRDA handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @note When the IRDA parity is enabled (PCE = 1) the data received contain the parity bit.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = hirda->State;
+ if((tmp1 == HAL_IRDA_STATE_READY) || (tmp1 == HAL_IRDA_STATE_BUSY_TX))
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hirda);
+
+ hirda->pRxBuffPtr = pData;
+ hirda->RxXferSize = Size;
+ hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
+ if(hirda->State == HAL_IRDA_STATE_BUSY_TX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_RX;
+ }
+
+ /* Set the IRDA DMA transfert complete callback */
+ hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt;
+
+ /* Set the DMA error callback */
+ hirda->hdmarx->XferErrorCallback = IRDA_DMAError;
+
+ /* Enable the DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->DR, *(uint32_t*)tmp, Size);
+
+ /* Enable the DMA transfer for the receiver request by setting the DMAR bit
+ in the USART CR3 register */
+ hirda->Instance->CR3 |= USART_CR3_DMAR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief This function handles IRDA interrupt request.
+ * @param hirda: IRDA handle
+ * @retval None
+ */
+void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda)
+{
+ uint32_t tmp1 = 0, tmp2 =0;
+
+ tmp1 = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_PE);
+ tmp2 = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_PE);
+ /* IRDA parity error interrupt occured -------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_FLAG_PE);
+ hirda->ErrorCode |= HAL_IRDA_ERROR_PE;
+ }
+
+ tmp1 = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_FE);
+ tmp2 = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR);
+ /* IRDA frame error interrupt occured --------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_FLAG_FE);
+ hirda->ErrorCode |= HAL_IRDA_ERROR_FE;
+ }
+
+ tmp1 = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_NE);
+ tmp2 = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR);
+ /* IRDA noise error interrupt occured --------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_FLAG_NE);
+ hirda->ErrorCode |= HAL_IRDA_ERROR_NE;
+ }
+
+ tmp1 = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_ORE);
+ tmp2 = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR);
+ /* IRDA Over-Run interrupt occured -----------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_FLAG_ORE);
+ hirda->ErrorCode |= HAL_IRDA_ERROR_ORE;
+ }
+
+ /* Call the Error call Back in case of Errors */
+ if(hirda->ErrorCode != HAL_IRDA_ERROR_NONE)
+ {
+ /* Set the IRDA state ready to be able to start again the process */
+ hirda->State = HAL_IRDA_STATE_READY;
+ HAL_IRDA_ErrorCallback(hirda);
+ }
+
+ tmp1 = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_RXNE);
+ tmp2 = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_RXNE);
+ /* IRDA in mode Receiver ---------------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ IRDA_Receive_IT(hirda);
+ __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_IT_RXNE);
+ }
+
+ tmp1 = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_TC);
+ tmp2 = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_TC);
+ /* IRDA in mode Transmitter ------------------------------------------------*/
+ if((tmp1 != RESET) &&(tmp2 != RESET))
+ {
+ IRDA_Transmit_IT(hirda);
+ __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_IT_TC);
+ }
+}
+
+/**
+ * @brief Tx Transfer complete callbacks.
+ * @param hirda: IRDA handle
+ * @retval None
+ */
+ __weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_IRDA_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer complete callbacks.
+ * @param hirda: IRDA handle
+ * @retval None
+ */
+__weak void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_IRDA_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief IRDA error callbacks.
+ * @param hirda: IRDA handle
+ * @retval None
+ */
+ __weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_IRDA_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup IRDA_Group3 Peripheral State and Errors functions
+ * @brief IRDA State and Errors functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State and Errors functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to return the State of IrDA
+ communication process, return Peripheral Errors occured during communication process
+ (+) HAL_IRDA_GetState() API can be helpful to check in run-time the state of the IrDA peripheral.
+ (+) HAL_IRDA_GetError() check in run-time errors that could be occured durung communication.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the IRDA state.
+ * @param hirda: IRDA handle
+ * @retval HAL state
+ */
+HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda)
+{
+ return hirda->State;
+}
+
+/**
+ * @brief Return the IARDA error code
+ * @param hirda : pointer to a IRDA_HandleTypeDef structure that contains
+ * the configuration information for the specified IRDA.
+ * @retval IRDA Error Code
+ */
+uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda)
+{
+ return hirda->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief DMA IRDA transmit process complete callback.
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma)
+{
+ IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ hirda->TxXferCount = 0;
+
+ /* Wait for IRDA TC Flag */
+ if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, IRDA_TIMEOUT_VALUE) != HAL_OK)
+ {
+ /* Timeout Occured */
+ hirda->State = HAL_IRDA_STATE_TIMEOUT;
+ HAL_IRDA_ErrorCallback(hirda);
+ }
+ else
+ {
+ /* No Timeout */
+ /* Check if a receive process is ongoing or not */
+ if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_RX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_READY;
+ }
+ HAL_IRDA_TxCpltCallback(hirda);
+ }
+}
+
+/**
+ * @brief DMA IRDA receive process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
+{
+ IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ hirda->RxXferCount = 0;
+
+ if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX;
+ }
+ else
+ {
+ hirda->State = HAL_IRDA_STATE_READY;
+ }
+
+ HAL_IRDA_RxCpltCallback(hirda);
+}
+
+/**
+ * @brief DMA IRDA communication error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void IRDA_DMAError(DMA_HandleTypeDef *hdma)
+{
+ IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ hirda->RxXferCount = 0;
+ hirda->TxXferCount = 0;
+ hirda->ErrorCode |= HAL_IRDA_ERROR_DMA;
+ hirda->State= HAL_IRDA_STATE_READY;
+
+ HAL_IRDA_ErrorCallback(hirda);
+}
+
+/**
+ * @brief This function handles IRDA Communication Timeout.
+ * @param hirda: IRDA handle
+ * @param Flag: specifies the IRDA flag to check.
+ * @param Status: The new Flag status (SET or RESET).
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Wait until flag is set */
+ if(Status == RESET)
+ {
+ while(__HAL_IRDA_GET_FLAG(hirda, Flag) == RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE);
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE);
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE);
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR);
+
+ hirda->State= HAL_IRDA_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ else
+ {
+ while(__HAL_IRDA_GET_FLAG(hirda, Flag) != RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE);
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE);
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE);
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR);
+
+ hirda->State= HAL_IRDA_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ return HAL_OK;
+}
+
+ /**
+ * @brief Send an amount of data in non blocking mode.
+ * @param hirda: IRDA handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda)
+{
+ uint16_t* tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = hirda->State;
+ if((tmp1 == HAL_IRDA_STATE_BUSY_TX) || (tmp1 == HAL_IRDA_STATE_BUSY_TX_RX))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hirda);
+
+ if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) hirda->pTxBuffPtr;
+ hirda->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF);
+ if(hirda->Init.Parity == IRDA_PARITY_NONE)
+ {
+ hirda->pTxBuffPtr += 2;
+ }
+ else
+ {
+ hirda->pTxBuffPtr += 1;
+ }
+ }
+ else
+ {
+ hirda->Instance->DR = (uint8_t)(*hirda->pTxBuffPtr++ & (uint8_t)0x00FF);
+ }
+
+ if(--hirda->TxXferCount == 0)
+ {
+ /* Disable the IRDA Transmit Complete Interrupt */
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TC);
+
+ if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_RX;
+ }
+ else
+ {
+ /* Disable the IRDA Parity Error Interrupt */
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE);
+
+ /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR);
+
+ hirda->State = HAL_IRDA_STATE_READY;
+ }
+ /* Call the Process Unlocked before calling the Tx call back API to give the possibiity to
+ start again the Transmission under the Tx call back API */
+ __HAL_UNLOCK(hirda);
+
+ HAL_IRDA_TxCpltCallback(hirda);
+
+ return HAL_OK;
+ }
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receives an amount of data in non blocking mode.
+ * @param hirda: IRDA handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda)
+{
+ uint16_t* tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = hirda->State;
+ if((tmp1 == HAL_IRDA_STATE_BUSY_RX) || (tmp1 == HAL_IRDA_STATE_BUSY_TX_RX))
+ {
+ /* Process Locked */
+ __HAL_LOCK(hirda);
+
+ if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) hirda->pRxBuffPtr;
+ if(hirda->Init.Parity == IRDA_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(hirda->Instance->DR & (uint16_t)0x01FF);
+ hirda->pRxBuffPtr += 2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(hirda->Instance->DR & (uint16_t)0x00FF);
+ hirda->pRxBuffPtr += 1;
+ }
+ }
+ else
+ {
+ if(hirda->Init.Parity == IRDA_PARITY_NONE)
+ {
+ *hirda->pRxBuffPtr++ = (uint8_t)(hirda->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ *hirda->pRxBuffPtr++ = (uint8_t)(hirda->Instance->DR & (uint8_t)0x007F);
+ }
+ }
+
+ if(--hirda->RxXferCount == 0)
+ {
+ while(HAL_IS_BIT_SET(hirda->Instance->SR, IRDA_FLAG_RXNE))
+ {
+ }
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE);
+
+ if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
+ {
+ hirda->State = HAL_IRDA_STATE_BUSY_TX;
+ }
+ else
+ {
+ /* Disable the IRDA Parity Error Interrupt */
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE);
+
+ /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
+ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR);
+
+ hirda->State = HAL_IRDA_STATE_READY;
+ }
+ /* Call the Process Unlocked before calling the Rx call back API to give the possibiity to
+ start again the receiption under the Rx call back API */
+ __HAL_UNLOCK(hirda);
+
+ HAL_IRDA_RxCpltCallback(hirda);
+
+ return HAL_OK;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hirda);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Configures the IRDA peripheral.
+ * @param hirda: IRDA handle
+ * @retval None
+ */
+static void IRDA_SetConfig(IRDA_HandleTypeDef *hirda)
+{
+ uint32_t tmpreg = 0x00;
+
+ /* Check the parameters */
+ assert_param(IS_IRDA_INSTANCE(hirda->Instance));
+ assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate));
+ assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength));
+ assert_param(IS_IRDA_PARITY(hirda->Init.Parity));
+ assert_param(IS_IRDA_MODE(hirda->Init.Mode));
+
+ /*-------------------------- IRDA CR2 Configuration ------------------------*/
+ /* Clear STOP[13:12] bits */
+ hirda->Instance->CR2 &= (uint32_t)~((uint32_t)USART_CR2_STOP);
+
+ /*-------------------------- USART CR1 Configuration -----------------------*/
+ tmpreg = hirda->Instance->CR1;
+
+ /* Clear M, PCE, PS, TE and RE bits */
+ tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | \
+ USART_CR1_RE));
+
+ /* Configure the USART Word Length, Parity and mode:
+ Set the M bits according to hirda->Init.WordLength value
+ Set PCE and PS bits according to hirda->Init.Parity value
+ Set TE and RE bits according to hirda->Init.Mode value */
+ tmpreg |= (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode;
+
+ /* Write to USART CR1 */
+ hirda->Instance->CR1 = (uint32_t)tmpreg;
+
+ /*-------------------------- USART CR3 Configuration -----------------------*/
+ /* Clear CTSE and RTSE bits */
+ hirda->Instance->CR3 &= (uint32_t)~((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE));
+
+ /*-------------------------- USART BRR Configuration -----------------------*/
+ if((hirda->Instance == USART1) || (hirda->Instance == USART6))
+ {
+ hirda->Instance->BRR = __IRDA_BRR(HAL_RCC_GetPCLK2Freq(), hirda->Init.BaudRate);
+ }
+ else
+ {
+ hirda->Instance->BRR = __IRDA_BRR(HAL_RCC_GetPCLK1Freq(), hirda->Init.BaudRate);
+ }
+}
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_IRDA_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_iwdg.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_iwdg.c
new file mode 100644
index 0000000..391f3a2
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_iwdg.c
@@ -0,0 +1,342 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_iwdg.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief IWDG HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Independent Watchdog (IWDG) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### IWDG Generic features #####
+ ==============================================================================
+ [..]
+ (+) The IWDG can be started by either software or hardware (configurable
+ through option byte).
+
+ (+) The IWDG is clocked by its own dedicated Low-Speed clock (LSI) and
+ thus stays active even if the main clock fails.
+ Once the IWDG is started, the LSI is forced ON and cannot be disabled
+ (LSI cannot be disabled too), and the counter starts counting down from
+ the reset value of 0xFFF. When it reaches the end of count value (0x000)
+ a system reset is generated.
+
+ (+) The IWDG counter should be refreshed at regular intervals, otherwise the
+ watchdog generates an MCU reset when the counter reaches 0.
+
+ (+) The IWDG is implemented in the VDD voltage domain that is still functional
+ in STOP and STANDBY mode (IWDG reset can wake-up from STANDBY).
+ IWDGRST flag in RCC_CSR register can be used to inform when an IWDG
+ reset occurs.
+
+ (+) Min-max timeout value @32KHz (LSI): ~125us / ~32.7s
+ The IWDG timeout may vary due to LSI frequency dispersion. STM32F4xx
+ devices provide the capability to measure the LSI frequency (LSI clock
+ connected internally to TIM5 CH4 input capture). The measured value
+ can be used to have an IWDG timeout with an acceptable accuracy.
+
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (+) Use IWDG using HAL_IWDG_Start() function to:
+ (++) Enable write access to IWDG_PR and IWDG_RLR registers.
+ (++) Configure the IWDG prescaler and counter reload values.
+ (++) Reload IWDG counter with value defined in the IWDG_RLR register.
+ (++) Start the IWDG, when the IWDG is used in software mode (no need
+ to enable the LSI, it will be enabled by hardware).
+ (+) Then the application program must refresh the IWDG counter at regular
+ intervals during normal operation to prevent an MCU reset, using
+ HAL_IWDG_Refresh() function.
+
+ *** IWDG HAL driver macros list ***
+ ====================================
+ [..]
+ Below the list of most used macros in IWDG HAL driver.
+
+ (+) __HAL_IWDG_START: Enable the IWDG peripheral
+ (+) __HAL_IWDG_RELOAD_COUNTER: Reloads IWDG counter with value defined in the reload register
+ (+) __HAL_IWDG_ENABLE_WRITE_ACCESS : Enable write access to IWDG_PR and IWDG_RLR registers
+ (+) __HAL_IWDG_DISABLE_WRITE_ACCESS : Disable write access to IWDG_PR and IWDG_RLR registers
+ (+) __HAL_IWDG_GET_FLAG: Get the selected IWDG's flag status
+ (+) __HAL_IWDG_CLEAR_FLAG: Clear the IWDG's pending flags
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup IWDG
+ * @brief IWDG HAL module driver.
+ * @{
+ */
+
+#ifdef HAL_IWDG_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup IWDG_Private_Functions
+ * @{
+ */
+
+/** @defgroup IWDG_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions.
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize the IWDG according to the specified parameters
+ in the IWDG_InitTypeDef and create the associated handle
+ (+) Initialize the IWDG MSP
+ (+) DeInitialize IWDG MSP
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the IWDG according to the specified
+ * parameters in the IWDG_InitTypeDef and creates the associated handle.
+ * @param hiwdg: IWDG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg)
+{
+ uint32_t tmp;
+
+ /* Check the IWDG handle allocation */
+ if(hiwdg == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler));
+ assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload));
+
+ if(hiwdg->State == HAL_IWDG_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_IWDG_MspInit(hiwdg);
+ }
+
+ /* Change IWDG peripheral state */
+ hiwdg->State = HAL_IWDG_STATE_BUSY;
+
+ /* Set IWDG counter clock prescaler */
+ /* Get the PR register value */
+ tmp = hiwdg->Instance->PR;
+
+ /* Clear PR[2:0] bits */
+ tmp &= ((uint32_t)~(IWDG_PR_PR));
+
+ /* Prepare the IWDG Prescaler parameter */
+ tmp |= hiwdg->Init.Prescaler;
+
+ /* Enable write access to IWDG_PR and IWDG_RLR registers */
+ __HAL_IWDG_ENABLE_WRITE_ACCESS(hiwdg);
+
+ /* Write to IWDG PR */
+ hiwdg->Instance->PR = tmp;
+
+ /* Set IWDG counter reload value */
+ /* Get the RLR register value */
+ tmp = hiwdg->Instance->RLR;
+
+ /* Clear RL[11:0] bits */
+ tmp &= ((uint32_t)~(IWDG_RLR_RL));
+
+ /* Prepare the IWDG Prescaler parameter */
+ tmp |= hiwdg->Init.Reload;
+
+ /* Write to IWDG RLR */
+ hiwdg->Instance->RLR = tmp;
+
+ /* Change IWDG peripheral state */
+ hiwdg->State = HAL_IWDG_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the IWDG MSP.
+ * @param hiwdg: IWDG handle
+ * @retval None
+ */
+__weak void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_IWDG_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup IWDG_Group2 IO operation functions
+ * @brief IO operation functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Start the IWDG.
+ (+) Refresh the IWDG.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Starts the IWDG.
+ * @param hiwdg: IWDG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg)
+{
+ /* Process Locked */
+ __HAL_LOCK(hiwdg);
+
+ /* Change IWDG peripheral state */
+ hiwdg->State = HAL_IWDG_STATE_BUSY;
+
+ /* Start the IWDG peripheral */
+ __HAL_IWDG_START(hiwdg);
+
+ /* Reload IWDG counter with value defined in the RLR register */
+ __HAL_IWDG_RELOAD_COUNTER(hiwdg);
+
+ /* Change IWDG peripheral state */
+ hiwdg->State = HAL_IWDG_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hiwdg);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Refreshes the IWDG.
+ * @param hiwdg: IWDG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg)
+{
+ /* Process Locked */
+ __HAL_LOCK(hiwdg);
+
+ /* Change IWDG peripheral state */
+ hiwdg->State = HAL_IWDG_STATE_BUSY;
+
+ /* Clear the RVU flag */
+ __HAL_IWDG_CLEAR_FLAG(hiwdg, IWDG_FLAG_RVU);
+
+ /* Reload IWDG counter with value defined in the reload register */
+ __HAL_IWDG_RELOAD_COUNTER(hiwdg);
+
+ /* Change IWDG peripheral state */
+ hiwdg->State = HAL_IWDG_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hiwdg);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup IWDG_Group3 Peripheral State functions
+ * @brief Peripheral State functions.
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State functions #####
+ ===============================================================================
+ [..]
+ This subsection permits to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the IWDG state.
+ * @param hiwdg: IWDG handle
+ * @retval HAL state
+ */
+HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg)
+{
+ return hiwdg->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_IWDG_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_ltdc.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_ltdc.c
new file mode 100644
index 0000000..d264a8b
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_ltdc.c
@@ -0,0 +1,1182 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_ltdc.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief LTDC HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the LTDC peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State and Errors functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#) Program the required configuration through following parameters:
+ the LTDC timing, the horizontal and vertical polarity,
+ the pixel clock polarity, Data Enable polarity and the LTDC background color value
+ using HAL_LTDC_Init() function
+
+ (#) Program the required configuration through following parameters:
+ the pixel format, the blending factors, input alpha value, the window size
+ and the image size using HAL_LTDC_ConfigLayer() function for foreground
+ or/and background layer.
+
+ (#) Optionally, configure and enable the CLUT using HAL_LTDC_ConfigCLUT() and
+ HAL_LTDC_EnableCLUT functions.
+
+ (#) Optionally, enable the Dither using HAL_LTDC_EnableDither().
+
+ (#) Optionally, configure and enable the Color keying using HAL_LTDC_ConfigColorKeying()
+ and HAL_LTDC_EnableColorKeying functions.
+
+ (#) Optionally, configure LineInterrupt using HAL_LTDC_ProgramLineInterrupt()
+ function
+
+ (#) If needed, Reconfigure and change the pixel format value, the alpha value
+ value, the window size, the window position and the layer start address
+ for foreground or/and background layer using respectively the following
+ functions: HAL_LTDC_SetPixelFormat(), HAL_LTDC_SetAlpha(), HAL_LTDC_SetWindowSize(),
+ HAL_LTDC_SetWindowPosition(), HAL_LTDC_SetAddress.
+
+ (#) To control LTDC state you can use the following function: HAL_LTDC_GetState()
+
+ *** LTDC HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in LTDC HAL driver.
+
+ (+) __HAL_LTDC_ENABLE: Enable the LTDC.
+ (+) __HAL_LTDC_DISABLE: Disable the LTDC.
+ (+) __HAL_LTDC_LAYER_ENABLE: Enable the LTDC Layer.
+ (+) __HAL_LTDC_LAYER_DISABLE: Disable the LTDC Layer.
+ (+) __HAL_LTDC_RELOAD_CONFIG: Reload Layer Configuration.
+ (+) __HAL_LTDC_GET_FLAG: Get the LTDC pending flags.
+ (+) __HAL_LTDC_CLEAR_FLAG: Clears the LTDC pending flags.
+ (+) __HAL_LTDC_ENABLE_IT: Enables the specified LTDC interrupts.
+ (+) __HAL_LTDC_DISABLE_IT: Disables the specified LTDC interrupts.
+ (+) __HAL_LTDC_GET_IT_SOURCE: Checks whether the specified LTDC interrupt has occurred or not.
+
+ [..]
+ (@) You can refer to the LTDC HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+/** @defgroup LTDC
+ * @brief LTDC HAL module driver
+ * @{
+ */
+
+#ifdef HAL_LTDC_MODULE_ENABLED
+
+#if defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void LTDC_SetConfig(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup LTDC_Private_Functions
+ * @{
+ */
+
+/** @defgroup LTDC_Group1 Initialization and Configuration functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and Configuration functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize and configure the LTDC
+ (+) De-initialize the LTDC
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the LTDC according to the specified
+ * parameters in the LTDC_InitTypeDef and create the associated handle.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_LTDC_Init(LTDC_HandleTypeDef *hltdc)
+{
+ uint32_t tmp = 0, tmp1 = 0;
+
+ /* Check the LTDC peripheral state */
+ if(hltdc == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check function parameters */
+ assert_param(IS_LTDC_ALL_INSTANCE(hltdc->Instance));
+ assert_param(IS_LTDC_HSYNC(hltdc->Init.HorizontalSync));
+ assert_param(IS_LTDC_VSYNC(hltdc->Init.VerticalSync));
+ assert_param(IS_LTDC_AHBP(hltdc->Init.AccumulatedHBP));
+ assert_param(IS_LTDC_AVBP(hltdc->Init.AccumulatedVBP));
+ assert_param(IS_LTDC_AAH(hltdc->Init.AccumulatedActiveH));
+ assert_param(IS_LTDC_AAW(hltdc->Init.AccumulatedActiveW));
+ assert_param(IS_LTDC_TOTALH(hltdc->Init.TotalHeigh));
+ assert_param(IS_LTDC_TOTALW(hltdc->Init.TotalWidth));
+ assert_param(IS_LTDC_HSPOL(hltdc->Init.HSPolarity));
+ assert_param(IS_LTDC_VSPOL(hltdc->Init.VSPolarity));
+ assert_param(IS_LTDC_DEPOL(hltdc->Init.DEPolarity));
+ assert_param(IS_LTDC_PCPOL(hltdc->Init.PCPolarity));
+
+ if(hltdc->State == HAL_LTDC_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_LTDC_MspInit(hltdc);
+ }
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Configures the HS, VS, DE and PC polarity */
+ hltdc->Instance->GCR &= ~(LTDC_GCR_HSPOL | LTDC_GCR_VSPOL | LTDC_GCR_DEPOL | LTDC_GCR_PCPOL);
+ hltdc->Instance->GCR |= (uint32_t)(hltdc->Init.HSPolarity | hltdc->Init.VSPolarity | \
+ hltdc->Init.DEPolarity | hltdc->Init.PCPolarity);
+
+ /* Sets Synchronization size */
+ hltdc->Instance->SSCR &= ~(LTDC_SSCR_VSH | LTDC_SSCR_HSW);
+ tmp = (hltdc->Init.HorizontalSync << 16);
+ hltdc->Instance->SSCR |= (tmp | hltdc->Init.VerticalSync);
+
+ /* Sets Accumulated Back porch */
+ hltdc->Instance->BPCR &= ~(LTDC_BPCR_AVBP | LTDC_BPCR_AHBP);
+ tmp = (hltdc->Init.AccumulatedHBP << 16);
+ hltdc->Instance->BPCR |= (tmp | hltdc->Init.AccumulatedVBP);
+
+ /* Sets Accumulated Active Width */
+ hltdc->Instance->AWCR &= ~(LTDC_AWCR_AAH | LTDC_AWCR_AAW);
+ tmp = (hltdc->Init.AccumulatedActiveW << 16);
+ hltdc->Instance->AWCR |= (tmp | hltdc->Init.AccumulatedActiveH);
+
+ /* Sets Total Width */
+ hltdc->Instance->TWCR &= ~(LTDC_TWCR_TOTALH | LTDC_TWCR_TOTALW);
+ tmp = (hltdc->Init.TotalWidth << 16);
+ hltdc->Instance->TWCR |= (tmp | hltdc->Init.TotalHeigh);
+
+ /* Sets the background color value */
+ tmp = ((uint32_t)(hltdc->Init.Backcolor.Green) << 8);
+ tmp1 = ((uint32_t)(hltdc->Init.Backcolor.Red) << 16);
+ hltdc->Instance->BCCR &= ~(LTDC_BCCR_BCBLUE | LTDC_BCCR_BCGREEN | LTDC_BCCR_BCRED);
+ hltdc->Instance->BCCR |= (tmp1 | tmp | hltdc->Init.Backcolor.Blue);
+
+ /* Enable the transfer Error interrupt */
+ __HAL_LTDC_ENABLE_IT(hltdc, LTDC_IT_TE);
+
+ /* Enable the FIFO underrun interrupt */
+ __HAL_LTDC_ENABLE_IT(hltdc, LTDC_IT_FU);
+
+ /* Enable LTDC by setting LTDCEN bit */
+ __HAL_LTDC_ENABLE(hltdc);
+
+ /* Initialise the error code */
+ hltdc->ErrorCode = HAL_LTDC_ERROR_NONE;
+
+ /* Initialize the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Deinitializes the LTDC peripheral registers to their default reset
+ * values.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval None
+ */
+
+HAL_StatusTypeDef HAL_LTDC_DeInit(LTDC_HandleTypeDef *hltdc)
+{
+ /* DeInit the low level hardware */
+ HAL_LTDC_MspDeInit(hltdc);
+
+ /* Initialise the error code */
+ hltdc->ErrorCode = HAL_LTDC_ERROR_NONE;
+
+ /* Initialize the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the LTDC MSP.
+ * @param hltdc : pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval None
+ */
+__weak void HAL_LTDC_MspInit(LTDC_HandleTypeDef* hltdc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_LTDC_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the LTDC MSP.
+ * @param hltdc : pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval None
+ */
+__weak void HAL_LTDC_MspDeInit(LTDC_HandleTypeDef* hltdc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_LTDC_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup LTDC_Group2 IO operation functions
+ * @brief IO operation functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..] This section provides function allowing to:
+ (+) Handle LTDC interrupt request
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Handles LTDC interrupt request.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval HAL status
+ */
+void HAL_LTDC_IRQHandler(LTDC_HandleTypeDef *hltdc)
+{
+ /* Transfer Error Interrupt management ***************************************/
+ if(__HAL_LTDC_GET_FLAG(hltdc, LTDC_FLAG_TE) != RESET)
+ {
+ if(__HAL_LTDC_GET_IT_SOURCE(hltdc, LTDC_IT_TE) != RESET)
+ {
+ /* Disable the transfer Error interrupt */
+ __HAL_LTDC_DISABLE_IT(hltdc, LTDC_IT_TE);
+
+ /* Clear the transfer error flag */
+ __HAL_LTDC_CLEAR_FLAG(hltdc, LTDC_FLAG_TE);
+
+ /* Update error code */
+ hltdc->ErrorCode |= HAL_LTDC_ERROR_TE;
+
+ /* Change LTDC state */
+ hltdc->State = HAL_LTDC_STATE_ERROR;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ /* Transfer error Callback */
+ HAL_LTDC_ErrorCallback(hltdc);
+ }
+ }
+ /* FIFO underrun Interrupt management ***************************************/
+ if(__HAL_LTDC_GET_FLAG(hltdc, LTDC_FLAG_FU) != RESET)
+ {
+ if(__HAL_LTDC_GET_IT_SOURCE(hltdc, LTDC_IT_FU) != RESET)
+ {
+ /* Disable the FIFO underrun interrupt */
+ __HAL_LTDC_DISABLE_IT(hltdc, LTDC_IT_FU);
+
+ /* Clear the FIFO underrun flag */
+ __HAL_LTDC_CLEAR_FLAG(hltdc, LTDC_FLAG_FU);
+
+ /* Update error code */
+ hltdc->ErrorCode |= HAL_LTDC_ERROR_FU;
+
+ /* Change LTDC state */
+ hltdc->State = HAL_LTDC_STATE_ERROR;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ /* Transfer error Callback */
+ HAL_LTDC_ErrorCallback(hltdc);
+ }
+ }
+ /* Line Interrupt management ************************************************/
+ if(__HAL_LTDC_GET_FLAG(hltdc, LTDC_FLAG_LI) != RESET)
+ {
+ if(__HAL_LTDC_GET_IT_SOURCE(hltdc, LTDC_IT_LI) != RESET)
+ {
+ /* Disable the Line interrupt */
+ __HAL_LTDC_DISABLE_IT(hltdc, LTDC_IT_LI);
+
+ /* Clear the Line interrupt flag */
+ __HAL_LTDC_CLEAR_FLAG(hltdc, LTDC_FLAG_LI);
+
+ /* Change LTDC state */
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ /* Line interrupt Callback */
+ HAL_LTDC_LineEvenCallback(hltdc);
+ }
+ }
+}
+
+/**
+ * @brief Error LTDC callback.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval None
+ */
+__weak void HAL_LTDC_ErrorCallback(LTDC_HandleTypeDef *hltdc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_LTDC_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Line Event callback.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval None
+ */
+__weak void HAL_LTDC_LineEvenCallback(LTDC_HandleTypeDef *hltdc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_LTDC_LineEvenCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup LTDC_Group3 Peripheral Control functions
+ * @brief Peripheral Control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Configure the LTDC foreground or/and background parameters.
+ (+) Set the active layer.
+ (+) Configure the color keying.
+ (+) Configure the C-LUT.
+ (+) Enable / Disable the color keying.
+ (+) Enable / Disable the C-LUT.
+ (+) Update the layer position.
+ (+) Update the layer size.
+ (+) update pixel format on the fly the.
+ (+) update transparency on the fly the.
+ (+) update address on the fly.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Configure the LTDC Layer according to the specified
+ * parameters in the LTDC_InitTypeDef and create the associated handle.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param pLayerCfg: pointer to a LTDC_LayerCfgTypeDef structure that contains
+ * the configuration information for the Layer.
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_LTDC_ConfigLayer(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx)
+{
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+ assert_param(IS_LTDC_PIXEL_FORMAT(pLayerCfg->PixelFormat));
+ assert_param(IS_LTDC_BLENDING_FACTOR1(pLayerCfg->BlendingFactor1));
+ assert_param(IS_LTDC_BLENDING_FACTOR2(pLayerCfg->BlendingFactor2));
+ assert_param(IS_LTDC_HCONFIGST(pLayerCfg->WindowX0));
+ assert_param(IS_LTDC_HCONFIGSP(pLayerCfg->WindowX1));
+ assert_param(IS_LTDC_VCONFIGST(pLayerCfg->WindowY0));
+ assert_param(IS_LTDC_VCONFIGSP(pLayerCfg->WindowY1));
+ assert_param(IS_LTDC_ALPHA(pLayerCfg->Alpha0));
+ assert_param(IS_LTDC_CFBLL(pLayerCfg->ImageWidth));
+ assert_param(IS_LTDC_CFBLNBR(pLayerCfg->ImageHeight));
+
+ /* Copy new layer configuration into handle structure */
+ hltdc->LayerCfg[LayerIdx] = *pLayerCfg;
+
+ /* Configure the LTDC Layer */
+ LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx);
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Initialize the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configure the color keying.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param RGBValue: the color key value
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_ConfigColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t RGBValue, uint32_t LayerIdx)
+{
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+
+ /* Configures the default color values */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CKCR &= ~(LTDC_LxCKCR_CKBLUE | LTDC_LxCKCR_CKGREEN | LTDC_LxCKCR_CKRED);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CKCR = RGBValue;
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Load the color lookup table.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param pCLUT: pointer to the color lookup table address.
+ * @param CLUTSize: the color lookup table size.
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_ConfigCLUT(LTDC_HandleTypeDef *hltdc, uint32_t *pCLUT, uint32_t CLUTSize, uint32_t LayerIdx)
+{
+ uint32_t tmp = 0;
+ uint32_t counter = 0;
+ uint32_t pcounter = 0;
+
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+
+ for(counter = 0; (counter < CLUTSize); counter++)
+ {
+ tmp = ((counter << 24) | ((uint32_t)(*pCLUT) & 0xFF) | ((uint32_t)(*pCLUT) & 0xFF00) | ((uint32_t)(*pCLUT) & 0xFF0000));
+ pcounter = (uint32_t)pCLUT + sizeof(*pCLUT);
+ pCLUT = (uint32_t *)pcounter;
+
+ /* Specifies the C-LUT address and RGB value */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CLUTWR = tmp;
+ }
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enable the color keying.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_EnableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx)
+{
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+
+ /* Enable LTDC color keying by setting COLKEN bit */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_COLKEN;
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disable the color keying.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_DisableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx)
+{
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+
+ /* Disable LTDC color keying by setting COLKEN bit */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_COLKEN;
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enable the color lookup table.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_EnableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx)
+{
+
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+
+ /* Disable LTDC color lookup table by setting CLUTEN bit */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_CLUTEN;
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disable the color lookup table.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_DisableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx)
+{
+
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+
+ /* Disable LTDC color lookup table by setting CLUTEN bit */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_CLUTEN;
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enables Dither.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval None
+ */
+
+HAL_StatusTypeDef HAL_LTDC_EnableDither(LTDC_HandleTypeDef *hltdc)
+{
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Enable Dither by setting DTEN bit */
+ LTDC->GCR |= (uint32_t)LTDC_GCR_DTEN;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables Dither.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval None
+ */
+
+HAL_StatusTypeDef HAL_LTDC_DisableDither(LTDC_HandleTypeDef *hltdc)
+{
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Disable Dither by setting DTEN bit */
+ LTDC->GCR &= ~(uint32_t)LTDC_GCR_DTEN;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Set the LTDC window size.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param XSize: LTDC Pixel per line
+ * @param YSize: LTDC Line number
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_SetWindowSize(LTDC_HandleTypeDef *hltdc, uint32_t XSize, uint32_t YSize, uint32_t LayerIdx)
+{
+ LTDC_LayerCfgTypeDef *pLayerCfg;
+
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Get layer configuration from handle structure */
+ pLayerCfg = &hltdc->LayerCfg[LayerIdx];
+
+ /* Check the parameters (Layers parameters)*/
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+ assert_param(IS_LTDC_HCONFIGST(pLayerCfg->WindowX0));
+ assert_param(IS_LTDC_HCONFIGSP(pLayerCfg->WindowX1));
+ assert_param(IS_LTDC_VCONFIGST(pLayerCfg->WindowY0));
+ assert_param(IS_LTDC_VCONFIGSP(pLayerCfg->WindowY1));
+ assert_param(IS_LTDC_CFBLL(XSize));
+ assert_param(IS_LTDC_CFBLNBR(YSize));
+
+ /* update horizontal start/stop */
+ pLayerCfg->WindowX0 = 0;
+ pLayerCfg->WindowX1 = XSize + pLayerCfg->WindowX0;
+
+ /* update vertical start/stop */
+ pLayerCfg->WindowY0 = 0;
+ pLayerCfg->WindowY1 = YSize + pLayerCfg->WindowY0;
+
+ /* Reconfigures the color frame buffer pitch in byte */
+ pLayerCfg->ImageWidth = XSize;
+
+ /* Reconfigures the frame buffer line number */
+ pLayerCfg->ImageHeight = YSize;
+
+ /* Set LTDC parameters */
+ LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx);
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Set the LTDC window position.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param X0: LTDC window X offset
+ * @param Y0: LTDC window Y offset
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_SetWindowPosition(LTDC_HandleTypeDef *hltdc, uint32_t X0, uint32_t Y0, uint32_t LayerIdx)
+{
+ LTDC_LayerCfgTypeDef *pLayerCfg;
+
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Get layer configuration from handle structure */
+ pLayerCfg = &hltdc->LayerCfg[LayerIdx];
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+ assert_param(IS_LTDC_HCONFIGST(pLayerCfg->WindowX0));
+ assert_param(IS_LTDC_HCONFIGSP(pLayerCfg->WindowX1));
+ assert_param(IS_LTDC_VCONFIGST(pLayerCfg->WindowY0));
+ assert_param(IS_LTDC_VCONFIGSP(pLayerCfg->WindowY1));
+
+ /* update horizontal start/stop */
+ pLayerCfg->WindowX0 = X0;
+ pLayerCfg->WindowX1 = X0 + pLayerCfg->ImageWidth;
+
+ /* update vertical start/stop */
+ pLayerCfg->WindowY0 = Y0;
+ pLayerCfg->WindowY1 = Y0 + pLayerCfg->ImageHeight;
+
+ /* Set LTDC parameters */
+ LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx);
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Reconfigure the pixel format.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param Pixelformat: new pixel format value.
+ * @param LayerIdx: LTDC Layer index.
+ * This parameter can be one of the following values:
+ * 0 or 1.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_SetPixelFormat(LTDC_HandleTypeDef *hltdc, uint32_t Pixelformat, uint32_t LayerIdx)
+{
+ LTDC_LayerCfgTypeDef *pLayerCfg;
+
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+ assert_param(IS_LTDC_PIXEL_FORMAT(Pixelformat));
+
+ /* Get layer configuration from handle structure */
+ pLayerCfg = &hltdc->LayerCfg[LayerIdx];
+
+ /* Reconfigure the pixel format */
+ pLayerCfg->PixelFormat = Pixelformat;
+
+ /* Set LTDC parameters */
+ LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx);
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Reconfigure the layer alpha value.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param Alpha: new alpha value.
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values:
+ * 0 or 1
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_SetAlpha(LTDC_HandleTypeDef *hltdc, uint32_t Alpha, uint32_t LayerIdx)
+{
+ LTDC_LayerCfgTypeDef *pLayerCfg;
+
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_ALPHA(Alpha));
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+
+ /* Get layer configuration from handle structure */
+ pLayerCfg = &hltdc->LayerCfg[LayerIdx];
+
+ /* Reconfigure the Alpha value */
+ pLayerCfg->Alpha = Alpha;
+
+ /* Set LTDC parameters */
+ LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx);
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+/**
+ * @brief Reconfigure the frame buffer Address.
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param Address: new address value.
+ * @param LayerIdx: LTDC Layer index.
+ * This parameter can be one of the following values:
+ * 0 or 1.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_SetAddress(LTDC_HandleTypeDef *hltdc, uint32_t Address, uint32_t LayerIdx)
+{
+ LTDC_LayerCfgTypeDef *pLayerCfg;
+
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LAYER(LayerIdx));
+
+ /* Get layer configuration from handle structure */
+ pLayerCfg = &hltdc->LayerCfg[LayerIdx];
+
+ /* Reconfigure the Address */
+ pLayerCfg->FBStartAdress = Address;
+
+ /* Set LTDC parameters */
+ LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx);
+
+ /* Sets the Reload type */
+ hltdc->Instance->SRCR = LTDC_SRCR_IMR;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Define the position of the line interrupt .
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param Line: Line Interrupt Position.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_LTDC_ProgramLineEvent(LTDC_HandleTypeDef *hltdc, uint32_t Line)
+{
+ /* Process locked */
+ __HAL_LOCK(hltdc);
+
+ /* Change LTDC peripheral state */
+ hltdc->State = HAL_LTDC_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_LTDC_LIPOS(Line));
+
+ /* Enable the Line interrupt */
+ __HAL_LTDC_ENABLE_IT(hltdc, LTDC_IT_LI);
+
+ /* Sets the Line Interrupt position */
+ LTDC->LIPCR = (uint32_t)Line;
+
+ /* Change the LTDC state*/
+ hltdc->State = HAL_LTDC_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hltdc);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup LTDC_Group4 Peripheral State and Errors functions
+ * @brief Peripheral State and Errors functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State and Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Check the LTDC state.
+ (+) Get error code.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the LTDC state
+ * @param hltdc: pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @retval HAL state
+ */
+HAL_LTDC_StateTypeDef HAL_LTDC_GetState(LTDC_HandleTypeDef *hltdc)
+{
+ return hltdc->State;
+}
+
+/**
+* @brief Return the LTDC error code
+* @param hltdc : pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+* @retval LTDC Error Code
+*/
+uint32_t HAL_LTDC_GetError(LTDC_HandleTypeDef *hltdc)
+{
+ return hltdc->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Configures the LTDC peripheral
+ * @param hltdc : Pointer to a LTDC_HandleTypeDef structure that contains
+ * the configuration information for the LTDC.
+ * @param pLayerCfg: Pointer LTDC Layer Configuration strusture
+ * @param LayerIdx: LTDC Layer index
+ * This parameter can be one of the following values: 0 or 1
+ * @retval None
+ */
+static void LTDC_SetConfig(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx)
+{
+ uint32_t tmp = 0;
+ uint32_t tmp1 = 0;
+ uint32_t tmp2 = 0;
+
+ /* Configures the horizontal start and stop position */
+ tmp = ((pLayerCfg->WindowX1 + ((hltdc->Instance->BPCR & LTDC_BPCR_AHBP) >> 16)) << 16);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->WHPCR &= ~(LTDC_LxWHPCR_WHSTPOS | LTDC_LxWHPCR_WHSPPOS);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->WHPCR = ((pLayerCfg->WindowX0 + ((hltdc->Instance->BPCR & LTDC_BPCR_AHBP) >> 16) + 1) | tmp);
+
+ /* Configures the vertical start and stop position */
+ tmp = ((pLayerCfg->WindowY1 + (hltdc->Instance->BPCR & LTDC_BPCR_AVBP)) << 16);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->WVPCR &= ~(LTDC_LxWVPCR_WVSTPOS | LTDC_LxWVPCR_WVSPPOS);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->WVPCR = ((pLayerCfg->WindowY0 + (hltdc->Instance->BPCR & LTDC_BPCR_AVBP) + 1) | tmp);
+
+ /* Specifies the pixel format */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->PFCR &= ~(LTDC_LxPFCR_PF);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->PFCR = (pLayerCfg->PixelFormat);
+
+ /* Configures the default color values */
+ tmp = ((uint32_t)(pLayerCfg->Backcolor.Green) << 8);
+ tmp1 = ((uint32_t)(pLayerCfg->Backcolor.Red) << 16);
+ tmp2 = (pLayerCfg->Alpha0 << 24);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->DCCR &= ~(LTDC_LxDCCR_DCBLUE | LTDC_LxDCCR_DCGREEN | LTDC_LxDCCR_DCRED | LTDC_LxDCCR_DCALPHA);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->DCCR = (pLayerCfg->Backcolor.Blue | tmp | tmp1 | tmp2);
+
+ /* Specifies the constant alpha value */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CACR &= ~(LTDC_LxCACR_CONSTA);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CACR = (pLayerCfg->Alpha);
+
+ /* Specifies the blending factors */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->BFCR &= ~(LTDC_LxBFCR_BF2 | LTDC_LxBFCR_BF1);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->BFCR = (pLayerCfg->BlendingFactor1 | pLayerCfg->BlendingFactor2);
+
+ /* Configures the color frame buffer start address */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CFBAR &= ~(LTDC_LxCFBAR_CFBADD);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CFBAR = (pLayerCfg->FBStartAdress);
+
+ if(pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_ARGB8888)
+ {
+ tmp = 4;
+ }
+ else if (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_RGB888)
+ {
+ tmp = 3;
+ }
+ else if((pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_ARGB4444) || \
+ (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_RGB565) || \
+ (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_ARGB1555) || \
+ (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_AL88))
+ {
+ tmp = 2;
+ }
+ else
+ {
+ tmp = 1;
+ }
+
+ /* Configures the color frame buffer pitch in byte */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CFBLR &= ~(LTDC_LxCFBLR_CFBLL | LTDC_LxCFBLR_CFBP);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CFBLR = (((pLayerCfg->ImageWidth * tmp) << 16) | ((pLayerCfg->ImageWidth * tmp) + 3));
+
+ /* Configures the frame buffer line number */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CFBLNR &= ~(LTDC_LxCFBLNR_CFBLNBR);
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CFBLNR = (pLayerCfg->ImageHeight);
+
+ /* Enable LTDC_Layer by setting LEN bit */
+ __HAL_LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_LEN;
+}
+
+/**
+ * @}
+ */
+#endif /* STM32F429xx || STM32F439xx */
+#endif /* HAL_LTDC_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_msp_template.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_msp_template.c
new file mode 100644
index 0000000..b464571
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_msp_template.c
@@ -0,0 +1,133 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_msp_template.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief HAL MSP module.
+ * This file template is located in the HAL folder and should be copied
+ * to the user folder.
+ *
+ @verbatim
+ ===============================================================================
+ ##### How to use this driver #####
+ ===============================================================================
+ [..]
+ This file is generated automatically by MicroXplorer and eventually modified
+ by the user
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup HAL_MSP
+ * @brief HAL MSP module.
+ * @{
+ */
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup HAL_MSP_Private_Functions
+ * @{
+ */
+
+/**
+ * @brief Initializes the Global MSP.
+ * @param None
+ * @retval None
+ */
+void HAL_MspInit(void)
+{
+ /* NOTE : This function is generated automatically by MicroXplorer and eventually
+ modified by the user
+ */
+}
+
+/**
+ * @brief DeInitializes the Global MSP.
+ * @param None
+ * @retval None
+ */
+void HAL_MspDeInit(void)
+{
+ /* NOTE : This function is generated automatically by MicroXplorer and eventually
+ modified by the user
+ */
+}
+
+/**
+ * @brief Initializes the PPP MSP.
+ * @param None
+ * @retval None
+ */
+void HAL_PPP_MspInit(void)
+{
+ /* NOTE : This function is generated automatically by MicroXplorer and eventually
+ modified by the user
+ */
+}
+
+/**
+ * @brief DeInitializes the PPP MSP.
+ * @param None
+ * @retval None
+ */
+void HAL_PPP_MspDeInit(void)
+{
+ /* NOTE : This function is generated automatically by MicroXplorer and eventually
+ modified by the user
+ */
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_nand.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_nand.c
new file mode 100644
index 0000000..c0ef40e
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_nand.c
@@ -0,0 +1,1050 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_nand.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief NAND HAL module driver.
+ * This file provides a generic firmware to drive NAND memories mounted
+ * as external device.
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ This driver is a generic layered driver which contains a set of APIs used to
+ control NAND flash memories. It uses the FMC/FSMC layer functions to interface
+ with NAND devices. This driver is used as follows:
+
+ (+) NAND flash memory configuration sequence using the function HAL_NAND_Init()
+ with control and timing parameters for both common and attribute spaces.
+
+ (+) Read NAND flash memory maker and device IDs using the function
+ HAL_NAND_Read_ID(). The read information is stored in the NAND_ID_TypeDef
+ structure declared by the function caller.
+
+ (+) Access NAND flash memory by read/write operations using the functions
+ HAL_NAND_Read_Page()/HAL_NAND_Read_SpareArea(), HAL_NAND_Write_Page()/HAL_NAND_Write_SpareArea()
+ to read/write page(s)/spare area(s). These functions use specific device
+ information (Block, page size..) predefined by the user in the HAL_NAND_Info_TypeDef
+ structure. The read/write address information is contained by the Nand_Address_Typedef
+ structure passed as parameter.
+
+ (+) Perform NAND flash Reset chip operation using the function HAL_NAND_Reset().
+
+ (+) Perform NAND flash erase block operation using the function HAL_NAND_Erase_Block().
+ The erase block address information is contained in the Nand_Address_Typedef
+ structure passed as parameter.
+
+ (+) Read the NAND flash status operation using the function HAL_NAND_Read_Status().
+
+ (+) You can also control the NAND device by calling the control APIs HAL_NAND_ECC_Enable()/
+ HAL_NAND_ECC_Disable() to respectively enable/disable the ECC code correction
+ feature or the function HAL_NAND_GetECC() to get the ECC correction code.
+
+ (+) You can monitor the NAND device HAL state by calling the function
+ HAL_NAND_GetState()
+
+ [..]
+ (@) This driver is a set of generic APIs which handle standard NAND flash operations.
+ If a NAND flash device contains different operations and/or implementations,
+ it should be implemented separately.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup NAND
+ * @brief NAND driver modules
+ * @{
+ */
+#ifdef HAL_NAND_MODULE_ENABLED
+
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup NAND_Private_Functions
+ * @{
+ */
+
+/** @defgroup NAND_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### NAND Initialization and de-initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to initialize/de-initialize
+ the NAND memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Perform NAND memory Initialization sequence
+ * @param hnand: pointer to NAND handle
+ * @param ComSpace_Timing: pointer to Common space timing structure
+ * @param AttSpace_Timing: pointer to Attribute space timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_Init(NAND_HandleTypeDef *hnand, FMC_NAND_PCC_TimingTypeDef *ComSpace_Timing, FMC_NAND_PCC_TimingTypeDef *AttSpace_Timing)
+{
+ /* Check the NAND handle state */
+ if(hnand == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ if(hnand->State == HAL_NAND_STATE_RESET)
+ {
+ /* Initialize the low level hardware (MSP) */
+ HAL_NAND_MspInit(hnand);
+ }
+
+ /* Initialize NAND control Interface */
+ FMC_NAND_Init(hnand->Instance, &(hnand->Init));
+
+ /* Initialize NAND common space timing Interface */
+ FMC_NAND_CommonSpace_Timing_Init(hnand->Instance, ComSpace_Timing, hnand->Init.NandBank);
+
+ /* Initialize NAND attribute space timing Interface */
+ FMC_NAND_AttributeSpace_Timing_Init(hnand->Instance, AttSpace_Timing, hnand->Init.NandBank);
+
+ /* Enable the NAND device */
+ __FMC_NAND_ENABLE(hnand->Instance, hnand->Init.NandBank);
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Perform NAND memory De-Initialization sequence
+ * @param hnand: pointer to NAND handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand)
+{
+ /* Initialize the low level hardware (MSP) */
+ HAL_NAND_MspDeInit(hnand);
+
+ /* Configure the NAND registers with their reset values */
+ FMC_NAND_DeInit(hnand->Instance, hnand->Init.NandBank);
+
+ /* Reset the NAND controller state */
+ hnand->State = HAL_NAND_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hnand);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief NAND MSP Init
+ * @param hnand: pointer to NAND handle
+ * @retval None
+ */
+__weak void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_NAND_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief NAND MSP DeInit
+ * @param hnand: pointer to NAND handle
+ * @retval None
+ */
+__weak void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_NAND_MspDeInit could be implemented in the user file
+ */
+}
+
+
+/**
+ * @brief This function handles NAND device interrupt request.
+ * @param hnand: pointer to NAND handle
+ * @retval HAL status
+*/
+void HAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand)
+{
+ /* Check NAND interrupt Rising edge flag */
+ if(__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_RISING_EDGE))
+ {
+ /* NAND interrupt callback*/
+ HAL_NAND_ITCallback(hnand);
+
+ /* Clear NAND interrupt Rising edge pending bit */
+ __FMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_RISING_EDGE);
+ }
+
+ /* Check NAND interrupt Level flag */
+ if(__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_LEVEL))
+ {
+ /* NAND interrupt callback*/
+ HAL_NAND_ITCallback(hnand);
+
+ /* Clear NAND interrupt Level pending bit */
+ __FMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_LEVEL);
+ }
+
+ /* Check NAND interrupt Falling edge flag */
+ if(__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FALLING_EDGE))
+ {
+ /* NAND interrupt callback*/
+ HAL_NAND_ITCallback(hnand);
+
+ /* Clear NAND interrupt Falling edge pending bit */
+ __FMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FALLING_EDGE);
+ }
+
+ /* Check NAND interrupt FIFO empty flag */
+ if(__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FEMPT))
+ {
+ /* NAND interrupt callback*/
+ HAL_NAND_ITCallback(hnand);
+
+ /* Clear NAND interrupt FIFO empty pending bit */
+ __FMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FEMPT);
+ }
+
+}
+
+/**
+ * @brief NAND interrupt feature callback
+ * @param hnand: pointer to NAND handle
+ * @retval None
+ */
+__weak void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_NAND_ITCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup NAND_Group2 Input and Output functions
+ * @brief Input Output and memory control functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### NAND Input and Output functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to use and control the NAND
+ memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Read the NAND memory electronic signature
+ * @param hnand: pointer to NAND handle
+ * @param pNAND_ID: NAND ID structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID)
+{
+ __IO uint32_t data = 0;
+ uint32_t deviceAddress = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hnand);
+
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Identify the device address */
+ if(hnand->Init.NandBank == FMC_NAND_BANK2)
+ {
+ deviceAddress = NAND_DEVICE1;
+ }
+ else
+ {
+ deviceAddress = NAND_DEVICE2;
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* Send Read ID command sequence */
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = 0x90;
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
+
+ /* Read the electronic signature from NAND flash */
+ data = *(__IO uint32_t *)deviceAddress;
+
+ /* Return the data read */
+ pNAND_ID->Maker_Id = ADDR_1st_CYCLE(data);
+ pNAND_ID->Device_Id = ADDR_2nd_CYCLE(data);
+ pNAND_ID->Third_Id = ADDR_3rd_CYCLE(data);
+ pNAND_ID->Fourth_Id = ADDR_4th_CYCLE(data);
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnand);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief NAND memory reset
+ * @param hnand: pointer to NAND handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand)
+{
+ uint32_t deviceAddress = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hnand);
+
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Identify the device address */
+ if(hnand->Init.NandBank == FMC_NAND_BANK2)
+ {
+ deviceAddress = NAND_DEVICE1;
+ }
+ else
+ {
+ deviceAddress = NAND_DEVICE2;
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* Send NAND reset command */
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = 0xFF;
+
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnand);
+
+ return HAL_OK;
+
+}
+
+
+/**
+ * @brief Read Page(s) from NAND memory block
+ * @param hnand: pointer to NAND handle
+ * @param pAddress : pointer to NAND address structure
+ * @param pBuffer : pointer to destination read buffer
+ * @param NumPageToRead : number of pages to read from block
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_Read_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypedef *pAddress, uint8_t *pBuffer, uint32_t NumPageToRead)
+{
+ __IO uint32_t index = 0;
+ uint32_t deviceAddress = 0, size = 0, numPagesRead = 0, nandAddress = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hnand);
+
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Identify the device address */
+ if(hnand->Init.NandBank == FMC_NAND_BANK2)
+ {
+ deviceAddress = NAND_DEVICE1;
+ }
+ else
+ {
+ deviceAddress = NAND_DEVICE2;
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* NAND raw address calculation */
+ nandAddress = ARRAY_ADDRESS(pAddress, hnand);
+
+ /* Page(s) read loop */
+ while((NumPageToRead != 0) && (nandAddress < (hnand->Info.BlockSize) * (hnand->Info.PageSize)))
+ {
+ /* update the buffer size */
+ size = (hnand->Info.PageSize) + ((hnand->Info.PageSize) * numPagesRead);
+
+ /* Send read page command sequence */
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
+
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1st_CYCLE(nandAddress);
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2nd_CYCLE(nandAddress);
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3rd_CYCLE(nandAddress);
+
+ /* for 512 and 1 GB devices, 4th cycle is required */
+ if(hnand->Info.BlockNbr >= 1024)
+ {
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_4th_CYCLE(nandAddress);
+ }
+
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = 0x30;
+
+ /* Get Data into Buffer */
+ for(; index < size; index++)
+ {
+ *(uint8_t *)pBuffer++ = *(uint8_t *)deviceAddress;
+ }
+
+ /* Increment read pages number */
+ numPagesRead++;
+
+ /* Decrement pages to read */
+ NumPageToRead--;
+
+ /* Increment the NAND address */
+ nandAddress = (uint32_t)(nandAddress + (hnand->Info.PageSize * 8));
+
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnand);
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Write Page(s) to NAND memory block
+ * @param hnand: pointer to NAND handle
+ * @param pAddress : pointer to NAND address structure
+ * @param pBuffer : pointer to source buffer to write
+ * @param NumPageToWrite : number of pages to write to block
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_Write_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypedef *pAddress, uint8_t *pBuffer, uint32_t NumPageToWrite)
+{
+ __IO uint32_t index = 0;
+ uint32_t timeout = 0;
+ uint32_t deviceAddress = 0, size = 0 , numPagesWritten = 0, nandAddress = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hnand);
+
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Identify the device address */
+ if(hnand->Init.NandBank == FMC_NAND_BANK2)
+ {
+ deviceAddress = NAND_DEVICE1;
+ }
+ else
+ {
+ deviceAddress = NAND_DEVICE2;
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* NAND raw address calculation */
+ nandAddress = ARRAY_ADDRESS(pAddress, hnand);
+
+ /* Page(s) write loop */
+ while((NumPageToWrite != 0) && (nandAddress < (hnand->Info.BlockSize) * (hnand->Info.PageSize)))
+ {
+ /* update the buffer size */
+ size = (hnand->Info.PageSize) + ((hnand->Info.PageSize) * numPagesWritten);
+
+ /* Send write page command sequence */
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = 0x80;
+
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1st_CYCLE(nandAddress);
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2nd_CYCLE(nandAddress);
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3rd_CYCLE(nandAddress);
+
+ /* for 512 and 1 GB devices, 4th cycle is required */
+ if(hnand->Info.BlockNbr >= 1024)
+ {
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_4th_CYCLE(nandAddress);
+ }
+
+ /* Write data to memory */
+ for(; index < size; index++)
+ {
+ *(__IO uint8_t *)deviceAddress = *(uint8_t *)pBuffer++;
+ }
+
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = 0x10;
+
+ /* Read status until NAND is ready */
+ while(HAL_NAND_Read_Status(hnand) != NAND_READY)
+ {
+ /* Check for timeout value */
+ timeout = HAL_GetTick() + NAND_WRITE_TIMEOUT;
+
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Increment written pages number */
+ numPagesWritten++;
+
+ /* Decrement pages to write */
+ NumPageToWrite--;
+
+ /* Increment the NAND address */
+ nandAddress = (uint32_t)(nandAddress + (hnand->Info.PageSize * 8));
+
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnand);
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Read Spare area(s) from NAND memory
+ * @param hnand: pointer to NAND handle
+ * @param pAddress : pointer to NAND address structure
+ * @param pBuffer: pointer to source buffer to write
+ * @param NumSpareAreaToRead: Number of spare area to read
+ * @retval HAL status
+*/
+HAL_StatusTypeDef HAL_NAND_Read_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypedef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaToRead)
+{
+ __IO uint32_t index = 0;
+ uint32_t deviceAddress = 0, size = 0, numSpareAreaRead = 0, nandAddress = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hnand);
+
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Identify the device address */
+ if(hnand->Init.NandBank == FMC_NAND_BANK2)
+ {
+ deviceAddress = NAND_DEVICE1;
+ }
+ else
+ {
+ deviceAddress = NAND_DEVICE2;
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* NAND raw address calculation */
+ nandAddress = ARRAY_ADDRESS(pAddress, hnand);
+
+ /* Spare area(s) read loop */
+ while((NumSpareAreaToRead != 0) && (nandAddress < (hnand->Info.BlockSize) * (hnand->Info.SpareAreaSize)))
+ {
+
+ /* update the buffer size */
+ size = (hnand->Info.PageSize) + ((hnand->Info.PageSize) * numSpareAreaRead);
+
+ /* Send read spare area command sequence */
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_C;
+
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1st_CYCLE(nandAddress);
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2nd_CYCLE(nandAddress);
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3rd_CYCLE(nandAddress);
+
+ /* for 512 and 1 GB devices, 4th cycle is required */
+ if(hnand->Info.BlockNbr >= 1024)
+ {
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_4th_CYCLE(nandAddress);
+ }
+
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = 0x30;
+
+ /* Get Data into Buffer */
+ for ( ;index < size; index++)
+ {
+ *(uint8_t *)pBuffer++ = *(uint8_t *)deviceAddress;
+ }
+
+ /* Increment read spare areas number */
+ numSpareAreaRead++;
+
+ /* Decrement spare areas to read */
+ NumSpareAreaToRead--;
+
+ /* Increment the NAND address */
+ nandAddress = (uint32_t)(nandAddress + (hnand->Info.SpareAreaSize));
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnand);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Write Spare area(s) to NAND memory
+ * @param hnand: pointer to NAND handle
+ * @param pAddress : pointer to NAND address structure
+ * @param pBuffer : pointer to source buffer to write
+ * @param NumSpareAreaTowrite : number of spare areas to write to block
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_Write_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypedef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaTowrite)
+{
+ __IO uint32_t index = 0;
+ uint32_t timeout = 0;
+ uint32_t deviceAddress = 0, size = 0, numSpareAreaWritten = 0, nandAddress = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hnand);
+
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Identify the device address */
+ if(hnand->Init.NandBank == FMC_NAND_BANK2)
+ {
+ deviceAddress = NAND_DEVICE1;
+ }
+ else
+ {
+ deviceAddress = NAND_DEVICE2;
+ }
+
+ /* Update the FMC_NAND controller state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* NAND raw address calculation */
+ nandAddress = ARRAY_ADDRESS(pAddress, hnand);
+
+ /* Spare area(s) write loop */
+ while((NumSpareAreaTowrite != 0) && (nandAddress < (hnand->Info.BlockSize) * (hnand->Info.SpareAreaSize)))
+ {
+ /* update the buffer size */
+ size = (hnand->Info.PageSize) + ((hnand->Info.PageSize) * numSpareAreaWritten);
+
+ /* Send write Spare area command sequence */
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_C;
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = 0x80;
+
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1st_CYCLE(nandAddress);
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2nd_CYCLE(nandAddress);
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3rd_CYCLE(nandAddress);
+
+ /* for 512 and 1 GB devices, 4th cycle is required */
+ if(hnand->Info.BlockNbr >= 1024)
+ {
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_4th_CYCLE(nandAddress);
+ }
+
+ /* Write data to memory */
+ for(; index < size; index++)
+ {
+ *(__IO uint8_t *)deviceAddress = *(uint8_t *)pBuffer++;
+ }
+
+ *(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = 0x10;
+
+
+ /* Read status until NAND is ready */
+ while(HAL_NAND_Read_Status(hnand) != NAND_READY)
+ {
+ /* Check for timeout value */
+ timeout = HAL_GetTick() + NAND_WRITE_TIMEOUT;
+
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Increment written spare areas number */
+ numSpareAreaWritten++;
+
+ /* Decrement spare areas to write */
+ NumSpareAreaTowrite--;
+
+ /* Increment the NAND address */
+ nandAddress = (uint32_t)(nandAddress + (hnand->Info.PageSize));
+
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnand);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief NAND memory Block erase
+ * @param hnand: pointer to NAND handle
+ * @param pAddress : pointer to NAND address structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypedef *pAddress)
+{
+ uint32_t DeviceAddress = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hnand);
+
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Identify the device address */
+ if(hnand->Init.NandBank == FMC_NAND_BANK2)
+ {
+ DeviceAddress = NAND_DEVICE1;
+ }
+ else
+ {
+ DeviceAddress = NAND_DEVICE2;
+ }
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* Send Erase block command sequence */
+ *(__IO uint8_t *)((uint32_t)(DeviceAddress | CMD_AREA)) = 0x60;
+
+ *(__IO uint8_t *)((uint32_t)(DeviceAddress | ADDR_AREA)) = ADDR_1st_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
+ *(__IO uint8_t *)((uint32_t)(DeviceAddress | ADDR_AREA)) = ADDR_2nd_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
+ *(__IO uint8_t *)((uint32_t)(DeviceAddress | ADDR_AREA)) = ADDR_3rd_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
+
+ /* for 512 and 1 GB devices, 4th cycle is required */
+ if(hnand->Info.BlockNbr >= 1024)
+ {
+ *(__IO uint8_t *)((uint32_t)(DeviceAddress | ADDR_AREA)) = ADDR_4th_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
+ }
+
+ *(__IO uint8_t *)((uint32_t)(DeviceAddress | CMD_AREA)) = 0xD0;
+
+ /* Update the NAND controller state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnand);
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief NAND memory read status
+ * @param hnand: pointer to NAND handle
+ * @retval NAND status
+ */
+uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand)
+{
+ uint32_t data = 0;
+ uint32_t DeviceAddress = 0;
+
+ /* Identify the device address */
+ if(hnand->Init.NandBank == FMC_NAND_BANK2)
+ {
+ DeviceAddress = NAND_DEVICE1;
+ }
+ else
+ {
+ DeviceAddress = NAND_DEVICE2;
+ }
+
+ /* Send Read status operation command */
+ *(__IO uint8_t *)((uint32_t)(DeviceAddress | CMD_AREA)) = 0x70;
+
+ /* Read status register data */
+ data = *(__IO uint8_t *)DeviceAddress;
+
+ /* Return the status */
+ if((data & NAND_ERROR) == NAND_ERROR)
+ {
+ return NAND_ERROR;
+ }
+ else if((data & NAND_READY) == NAND_READY)
+ {
+ return NAND_READY;
+ }
+
+ return NAND_BUSY;
+
+}
+
+/**
+ * @brief Increment the NAND memory address
+ * @param hnand: pointer to NAND handle
+ * @param pAddress: pointer to NAND adress structure
+ * @retval The new status of the increment address operation. It can be:
+ * - NAND_VALID_ADDRESS: When the new address is valid address
+ * - NAND_INVALID_ADDRESS: When the new address is invalid address
+ */
+uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypedef *pAddress)
+{
+ uint32_t status = NAND_VALID_ADDRESS;
+
+ /* Increment page address */
+ pAddress->Page++;
+
+ /* Check NAND address is valid */
+ if(pAddress->Page == hnand->Info.BlockSize)
+ {
+ pAddress->Page = 0;
+ pAddress->Block++;
+
+ if(pAddress->Block == hnand->Info.ZoneSize)
+ {
+ pAddress->Block = 0;
+ pAddress->Zone++;
+
+ if(pAddress->Zone == (hnand->Info.ZoneSize/ hnand->Info.BlockNbr))
+ {
+ status = NAND_INVALID_ADDRESS;
+ }
+ }
+ }
+
+ return (status);
+}
+
+
+/**
+ * @}
+ */
+
+/** @defgroup NAND_Group3 Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### NAND Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control dynamically
+ the NAND interface.
+
+@endverbatim
+ * @{
+ */
+
+
+/**
+ * @brief Enables dynamically NAND ECC feature.
+ * @param hnand: pointer to NAND handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand)
+{
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NAND state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* Enable ECC feature */
+ FMC_NAND_ECC_Enable(hnand->Instance, hnand->Init.NandBank);
+
+ /* Update the NAND state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Disables dynamically FMC_NAND ECC feature.
+ * @param hnand: pointer to NAND handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand)
+{
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NAND state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* Disable ECC feature */
+ FMC_NAND_ECC_Disable(hnand->Instance, hnand->Init.NandBank);
+
+ /* Update the NAND state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables dynamically NAND ECC feature.
+ * @param hnand: pointer to NAND handle
+ * @param ECCval: pointer to ECC value
+ * @param Timeout: maximum timeout to wait
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout)
+{
+ HAL_StatusTypeDef status = HAL_OK;
+
+ /* Check the NAND controller state */
+ if(hnand->State == HAL_NAND_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NAND state */
+ hnand->State = HAL_NAND_STATE_BUSY;
+
+ /* Get NAND ECC value */
+ status = FMC_NAND_GetECC(hnand->Instance, ECCval, hnand->Init.NandBank, Timeout);
+
+ /* Update the NAND state */
+ hnand->State = HAL_NAND_STATE_READY;
+
+ return status;
+}
+
+/**
+ * @}
+ */
+
+
+/** @defgroup NAND_Group4 State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ==============================================================================
+ ##### NAND State functions #####
+ ==============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the NAND controller
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief return the NAND state
+ * @param hnand: pointer to NAND handle
+ * @retval HAL state
+ */
+HAL_NAND_StateTypeDef HAL_NAND_GetState(NAND_HandleTypeDef *hnand)
+{
+ return hnand->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_NAND_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_nor.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_nor.c
new file mode 100644
index 0000000..c1e85f7
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_nor.c
@@ -0,0 +1,782 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_nor.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief NOR HAL module driver.
+ * This file provides a generic firmware to drive NOR memories mounted
+ * as external device.
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ This driver is a generic layered driver which contains a set of APIs used to
+ control NOR flash memories. It uses the FMC/FSMC layer functions to interface
+ with NOR devices. This driver is used as follows:
+
+ (+) NOR flash memory configuration sequence using the function HAL_NOR_Init()
+ with control and timing parameters for both normal and extended mode.
+
+ (+) Read NOR flash memory manufacturer code and device IDs using the function
+ HAL_NOR_Read_ID(). The read information is stored in the NOR_ID_TypeDef
+ structure declared by the function caller.
+
+ (+) Access NOR flash memory by read/write data unit operations using the functions
+ HAL_NOR_Read(), HAL_NOR_Program().
+
+ (+) Perform NOR flash erase block/chip operations using the functions
+ HAL_NOR_Erase_Block() and HAL_NOR_Erase_Chip().
+
+ (+) Read the NOR flash CFI (common flash interface) IDs using the function
+ HAL_NOR_Read_CFI(). The read information is stored in the NOR_CFI_TypeDef
+ structure declared by the function caller.
+
+ (+) You can also control the NOR device by calling the control APIs HAL_NOR_WriteOperation_Enable()/
+ HAL_NOR_WriteOperation_Disable() to respectively enable/disable the NOR write operation
+
+ (+) You can monitor the NOR device HAL state by calling the function
+ HAL_NOR_GetState()
+ [..]
+ (@) This driver is a set of generic APIs which handle standard NOR flash operations.
+ If a NOR flash device contains different operations and/or implementations,
+ it should be implemented separately.
+
+ *** NOR HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in NOR HAL driver.
+
+ (+) __NOR_WRITE : NOR memory write data to specified address
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup NOR
+ * @brief NOR driver modules
+ * @{
+ */
+#ifdef HAL_NOR_MODULE_ENABLED
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup NOR_Private_Functions
+ * @{
+ */
+
+/** @defgroup NOR_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### NOR Initialization and de_initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to initialize/de-initialize
+ the NOR memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Perform the NOR memory Initialization sequence
+ * @param hnor: pointer to NOR handle
+ * @param Timing: pointer to NOR control timing structure
+ * @param ExtTiming: pointer to NOR extended mode timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_Init(NOR_HandleTypeDef *hnor, FMC_NORSRAM_TimingTypeDef *Timing, FMC_NORSRAM_TimingTypeDef *ExtTiming)
+{
+ /* Check the NOR handle parameter */
+ if(hnor == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ if(hnor->State == HAL_NOR_STATE_RESET)
+ {
+ /* Initialize the low level hardware (MSP) */
+ HAL_NOR_MspInit(hnor);
+ }
+
+ /* Initialize NOR control Interface */
+ FMC_NORSRAM_Init(hnor->Instance, &(hnor->Init));
+
+ /* Initialize NOR timing Interface */
+ FMC_NORSRAM_Timing_Init(hnor->Instance, Timing, hnor->Init.NSBank);
+
+ /* Initialize NOR extended mode timing Interface */
+ FMC_NORSRAM_Extended_Timing_Init(hnor->Extended, ExtTiming, hnor->Init.NSBank, hnor->Init.ExtendedMode);
+
+ /* Enable the NORSRAM device */
+ __FMC_NORSRAM_ENABLE(hnor->Instance, hnor->Init.NSBank);
+
+ /* Check the NOR controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Perform NOR memory De-Initialization sequence
+ * @param hnor: pointer to NOR handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_DeInit(NOR_HandleTypeDef *hnor)
+{
+ /* De-Initialize the low level hardware (MSP) */
+ HAL_NOR_MspDeInit(hnor);
+
+ /* Configure the NOR registers with their reset values */
+ FMC_NORSRAM_DeInit(hnor->Instance, hnor->Extended, hnor->Init.NSBank);
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief NOR MSP Init
+ * @param hnor: pointer to NOR handle
+ * @retval None
+ */
+__weak void HAL_NOR_MspInit(NOR_HandleTypeDef *hnor)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_NOR_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief NOR MSP DeInit
+ * @param hnor: pointer to NOR handle
+ * @retval None
+ */
+__weak void HAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_NOR_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief NOR BSP Wait fro Ready/Busy signal
+ * @param hnor: pointer to NOR handle
+ * @param Timeout: Maximum timeout value
+ * @retval None
+ */
+__weak void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_NOR_BspWait could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup NOR_Group2 Input and Output functions
+ * @brief Input Output and memory control functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### NOR Input and Output functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to use and control the NOR memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Read NOR flash IDs
+ * @param hnor: pointer to NOR handle
+ * @param pNOR_ID : pointer to NOR ID structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Check the NOR controller state */
+ if(hnor->State == HAL_NOR_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_BUSY;
+
+ /* Send read ID command */
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x00AA);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x02AA), 0x0055);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x0090);
+
+ /* Read the NOR IDs */
+ pNOR_ID->Manufacturer_Code = *(__IO uint16_t *) __NOR_ADDR_SHIFT(MC_ADDRESS);
+ pNOR_ID->Device_Code1 = *(__IO uint16_t *) __NOR_ADDR_SHIFT(DEVICE_CODE1_ADDR);
+ pNOR_ID->Device_Code2 = *(__IO uint16_t *) __NOR_ADDR_SHIFT(DEVICE_CODE2_ADDR);
+ pNOR_ID->Device_Code3 = *(__IO uint16_t *) __NOR_ADDR_SHIFT(DEVICE_CODE3_ADDR);
+
+ /* Check the NOR controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Returns the NOR memory to Read mode.
+ * @param hnor: pointer to NOR handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Check the NOR controller state */
+ if(hnor->State == HAL_NOR_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ __NOR_WRITE(NOR_MEMORY_ADRESS, 0x00F0);
+
+ /* Check the NOR controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Read data from NOR memory
+ * @param hnor: pointer to NOR handle
+ * @param pAddress: pointer to Device address
+ * @param pData : pointer to read data
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Check the NOR controller state */
+ if(hnor->State == HAL_NOR_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_BUSY;
+
+ /* Send read data command */
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x00555), 0x00AA);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x002AA), 0x0055);
+ __NOR_WRITE(*pAddress, 0x00F0);
+
+ /* Read the data */
+ *pData = *(__IO uint32_t *)pAddress;
+
+ /* Check the NOR controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Program data to NOR memory
+ * @param hnor: pointer to NOR handle
+ * @param pAddress: Device address
+ * @param pData : pointer to the data to write
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Check the NOR controller state */
+ if(hnor->State == HAL_NOR_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_BUSY;
+
+ /* Send program data command */
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x00AA);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x02AA), 0x0055);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x00A0);
+
+ /* Write the data */
+ __NOR_WRITE(pAddress, *pData);
+
+ /* Check the NOR controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Reads a block of data from the FMC NOR memory.
+ * @param hnor: pointer to NOR handle
+ * @param uwAddress: NOR memory internal address to read from.
+ * @param pData: pointer to the buffer that receives the data read from the
+ * NOR memory.
+ * @param uwBufferSize : number of Half word to read.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Check the NOR controller state */
+ if(hnor->State == HAL_NOR_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_BUSY;
+
+ /* Send read data command */
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x00555), 0x00AA);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x002AA), 0x0055);
+ __NOR_WRITE(uwAddress, 0x00F0);
+
+ /* Read buffer */
+ while( uwBufferSize > 0)
+ {
+ *pData++ = *(__IO uint16_t *)uwAddress;
+ uwAddress += 2;
+ uwBufferSize--;
+ }
+
+ /* Check the NOR controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Writes a half-word buffer to the FMC NOR memory. This function
+ * must be used only with S29GL128P NOR memory.
+ * @param hnor: pointer to NOR handle
+ * @param uwAddress: NOR memory internal address from which the data
+ * @param pData: pointer to source data buffer.
+ * @param uwBufferSize: number of Half words to write. The maximum allowed
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize)
+{
+ uint32_t lastloadedaddress = 0;
+ uint32_t currentaddress = 0;
+ uint32_t endaddress = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Check the NOR controller state */
+ if(hnor->State == HAL_NOR_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_BUSY;
+
+ /* Initialize variables */
+ currentaddress = uwAddress;
+ endaddress = uwAddress + uwBufferSize - 1;
+ lastloadedaddress = uwAddress;
+
+ /* Issue unlock command sequence */
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x00AA);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x02AA), 0x0055);
+
+ /* Write Buffer Load Command */
+ __NOR_WRITE(__NOR_ADDR_SHIFT(uwAddress), 0x25);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(uwAddress), (uwBufferSize - 1));
+
+ /* Load Data into NOR Buffer */
+ while(currentaddress <= endaddress)
+ {
+ /* Store last loaded address & data value (for polling) */
+ lastloadedaddress = currentaddress;
+
+ __NOR_WRITE(__NOR_ADDR_SHIFT(currentaddress), *pData++);
+
+ currentaddress += 1;
+ }
+
+ __NOR_WRITE(__NOR_ADDR_SHIFT(lastloadedaddress), 0x29);
+
+ /* Check the NOR controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Erase the specified block of the NOR memory
+ * @param hnor: pointer to NOR handle
+ * @param BlockAddress : Block to erase address
+ * @param Address: Device address
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAddress, uint32_t Address)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Check the NOR controller state */
+ if(hnor->State == HAL_NOR_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_BUSY;
+
+ /* Send block erase command sequence */
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x00AA);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x02AA), 0x0055);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x0080);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x00AA);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x02AA), 0x0055);
+ __NOR_WRITE((uint32_t)(BlockAddress + Address), 0x30);
+
+ /* Check the NOR memory status and update the controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Erase the entire NOR chip.
+ * @param hnor: pointer to NOR handle
+ * @param Address : Device address
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Check the NOR controller state */
+ if(hnor->State == HAL_NOR_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_BUSY;
+
+ /* Send NOR chip erase command sequence */
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x00AA);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x02AA), 0x0055);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x0080);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x00AA);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x02AA), 0x0055);
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0555), 0x0010);
+
+ /* Check the NOR memory status and update the controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Read NOR flash CFI IDs
+ * @param hnor: pointer to NOR handle
+ * @param pNOR_CFI : pointer to NOR CFI IDs structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_Read_CFI(NOR_HandleTypeDef *hnor, NOR_CFITypeDef *pNOR_CFI)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Check the NOR controller state */
+ if(hnor->State == HAL_NOR_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_BUSY;
+
+ /* Send read CFI query command */
+ __NOR_WRITE(__NOR_ADDR_SHIFT(0x0055), 0x0098);
+
+ /* read the NOR CFI information */
+ pNOR_CFI->CFI_1 = *(__IO uint16_t *) __NOR_ADDR_SHIFT(CFI1_ADDRESS);
+ pNOR_CFI->CFI_2 = *(__IO uint16_t *) __NOR_ADDR_SHIFT(CFI2_ADDRESS);
+ pNOR_CFI->CFI_3 = *(__IO uint16_t *) __NOR_ADDR_SHIFT(CFI3_ADDRESS);
+ pNOR_CFI->CFI_4 = *(__IO uint16_t *) __NOR_ADDR_SHIFT(CFI4_ADDRESS);
+
+ /* Check the NOR controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup NOR_Group3 Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### NOR Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control dynamically
+ the NOR interface.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables dynamically NOR write operation.
+ * @param hnor: pointer to NOR handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Enable write operation */
+ FMC_NORSRAM_WriteOperation_Enable(hnor->Instance, hnor->Init.NSBank);
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables dynamically NOR write operation.
+ * @param hnor: pointer to NOR handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor)
+{
+ /* Process Locked */
+ __HAL_LOCK(hnor);
+
+ /* Update the SRAM controller state */
+ hnor->State = HAL_NOR_STATE_BUSY;
+
+ /* Disable write operation */
+ FMC_NORSRAM_WriteOperation_Disable(hnor->Instance, hnor->Init.NSBank);
+
+ /* Update the NOR controller state */
+ hnor->State = HAL_NOR_STATE_PROTECTED;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hnor);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup NOR_Group4 State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ==============================================================================
+ ##### NOR State functions #####
+ ==============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the NOR controller
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief return the NOR controller state
+ * @param hnor: pointer to NOR handle
+ * @retval NOR controller state
+ */
+HAL_NOR_StateTypeDef HAL_NOR_GetState(NOR_HandleTypeDef *hnor)
+{
+ return hnor->State;
+}
+
+/**
+ * @brief Returns the NOR operation status.
+ * @param hnor: pointer to NOR handle
+ * @param Address: Device address
+ * @param Timeout: NOR progamming Timeout
+ * @retval NOR_Status: The returned value can be: NOR_SUCCESS, NOR_ERROR
+ * or NOR_TIMEOUT
+ */
+NOR_StatusTypedef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout)
+{
+ NOR_StatusTypedef status = NOR_ONGOING;
+ uint16_t tmpSR1 = 0, tmpSR2 = 0;
+ uint32_t timeout = 0;
+
+ /* Poll on NOR memory Ready/Busy signal ------------------------------------*/
+ HAL_NOR_MspWait(hnor, timeout);
+
+ /* Get the NOR memory operation status -------------------------------------*/
+ while(status != NOR_SUCCESS)
+ {
+ /* Check for timeout value */
+ timeout = HAL_GetTick() + Timeout;
+
+ if(HAL_GetTick() >= timeout)
+ {
+ status = NOR_TIMEOUT;
+ }
+
+ /* Read NOR status register (DQ6 and DQ5) */
+ tmpSR1 = *(__IO uint16_t *)Address;
+ tmpSR2 = *(__IO uint16_t *)Address;
+
+ /* If DQ6 did not toggle between the two reads then return NOR_Success */
+ if((tmpSR1 & 0x0040) == (tmpSR2 & 0x0040))
+ {
+ return NOR_SUCCESS;
+ }
+
+ if((tmpSR1 & 0x0020) == 0x0020)
+ {
+ return NOR_ONGOING;
+ }
+
+ tmpSR1 = *(__IO uint16_t *)Address;
+ tmpSR2 = *(__IO uint16_t *)Address;
+
+ /* If DQ6 did not toggle between the two reads then return NOR_Success */
+ if((tmpSR1 & 0x0040) == (tmpSR2 & 0x0040))
+ {
+ return NOR_SUCCESS;
+ }
+
+ if((tmpSR1 & 0x0020) == 0x0020)
+ {
+ return NOR_ERROR;
+ }
+ }
+
+ /* Return the operation status */
+ return status;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_NOR_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pccard.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pccard.c
new file mode 100644
index 0000000..99fd7ee
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pccard.c
@@ -0,0 +1,711 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_pccard.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief PCCARD HAL module driver.
+ * This file provides a generic firmware to drive PCCARD memories mounted
+ * as external device.
+ *
+ @verbatim
+ ===============================================================================
+ ##### How to use this driver #####
+ ===============================================================================
+ [..]
+ This driver is a generic layered driver which contains a set of APIs used to
+ control PCCARD/compact flash memories. It uses the FMC/FSMC layer functions
+ to interface with PCCARD devices. This driver is used for:
+
+ (+) PCCARD/compact flash memory configuration sequence using the function
+ HAL_PCCARD_Init() with control and timing parameters for both common and
+ attribute spaces.
+
+ (+) Read PCCARD/compact flash memory maker and device IDs using the function
+ HAL_CF_Read_ID(). The read information is stored in the CompactFlash_ID
+ structure declared by the function caller.
+
+ (+) Access PCCARD/compact flash memory by read/write operations using the functions
+ HAL_CF_Read_Sector()/HAL_CF_Write_Sector(), to read/write sector.
+
+ (+) Perform PCCARD/compact flash Reset chip operation using the function HAL_CF_Reset().
+
+ (+) Perform PCCARD/compact flash erase sector operation using the function
+ HAL_CF_Erase_Sector().
+
+ (+) Read the PCCARD/compact flash status operation using the function HAL_CF_ReadStatus().
+
+ (+) You can monitor the PCCARD/compact flash device HAL state by calling the function
+ HAL_PCCARD_GetState()
+
+ [..]
+ (@) This driver is a set of generic APIs which handle standard PCCARD/compact flash
+ operations. If a PCCARD/compact flash device contains different operations
+ and/or implementations, it should be implemented separately.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup PCCARD
+ * @brief PCCARD driver modules
+ * @{
+ */
+#ifdef HAL_PCCARD_MODULE_ENABLED
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup PCCARD_Private_Functions
+ * @{
+ */
+
+/** @defgroup PCCARD_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### PCCARD Initialization and de-initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to initialize/de-initialize
+ the PCCARD memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Perform the PCCARD memory Initialization sequence
+ * @param hpccard : pointer to PCCARD handle
+ * @param ComSpaceTiming: Common space timing structure
+ * @param AttSpaceTiming: Attribute space timing structure
+ * @param IOSpaceTiming: IO space timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FMC_NAND_PCC_TimingTypeDef *ComSpaceTiming, FMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, FMC_NAND_PCC_TimingTypeDef *IOSpaceTiming)
+{
+ /* Check the PCCARD controller state */
+ if(hpccard == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ if(hpccard->State == HAL_PCCARD_STATE_RESET)
+ {
+ /* Initialize the low level hardware (MSP) */
+ HAL_PCCARD_MspInit(hpccard);
+ }
+
+ /* Initialize the PCCARD state */
+ hpccard->State = HAL_PCCARD_STATE_BUSY;
+
+ /* Initialize PCCARD control Interface */
+ FMC_PCCARD_Init(hpccard->Instance, &(hpccard->Init));
+
+ /* Init PCCARD common space timing Interface */
+ FMC_PCCARD_CommonSpace_Timing_Init(hpccard->Instance, ComSpaceTiming);
+
+ /* Init PCCARD attribute space timing Interface */
+ FMC_PCCARD_AttributeSpace_Timing_Init(hpccard->Instance, AttSpaceTiming);
+
+ /* Init PCCARD IO space timing Interface */
+ FMC_PCCARD_IOSpace_Timing_Init(hpccard->Instance, IOSpaceTiming);
+
+ /* Enable the PCCARD device */
+ __FMC_PCCARD_ENABLE(hpccard->Instance);
+
+ /* Update the PCCARD state */
+ hpccard->State = HAL_PCCARD_STATE_READY;
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Perform the PCCARD memory De-initialization sequence
+ * @param hpccard : pointer to PCCARD handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCCARD_DeInit(PCCARD_HandleTypeDef *hpccard)
+{
+ /* De-Initialize the low level hardware (MSP) */
+ HAL_PCCARD_MspDeInit(hpccard);
+
+ /* Configure the PCCARD registers with their reset values */
+ FMC_PCCARD_DeInit(hpccard->Instance);
+
+ /* Update the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hpccard);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief PCCARD MSP Init
+ * @param hpccard : pointer to PCCARD handle
+ * @retval None
+ */
+__weak void HAL_PCCARD_MspInit(PCCARD_HandleTypeDef *hpccard)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCCARD_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief PCCARD MSP DeInit
+ * @param hpccard : pointer to PCCARD handle
+ * @retval None
+ */
+__weak void HAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCCARD_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup PCCARD_Group2 Input and Output functions
+ * @brief Input Output and memory control functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### PCCARD Input and Output functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to use and control the PCCARD memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Read Compact Flash's ID.
+ * @param hpccard : pointer to PCCARD handle
+ * @param CF_ID: Compact flash ID structure.
+ * @param pStatus: pointer to compact flash status
+ * @retval HAL status
+ *
+ */
+HAL_StatusTypeDef HAL_CF_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t CompactFlash_ID[], uint8_t *pStatus)
+{
+ uint32_t timeout = 0xFFFF, index;
+ uint8_t status;
+
+ /* Process Locked */
+ __HAL_LOCK(hpccard);
+
+ /* Check the PCCARD controller state */
+ if(hpccard->State == HAL_PCCARD_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_BUSY;
+
+ /* Initialize the CF status */
+ *pStatus = CF_READY;
+
+ /* Send the Identify Command */
+ *(__IO uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD) = 0xECEC;
+
+ /* Read CF IDs and timeout treatment */
+ do
+ {
+ /* Read the CF status */
+ status = *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+
+ timeout--;
+ }while((status != 0x58) && timeout);
+
+ if(timeout == 0)
+ {
+ *pStatus = CF_TIMEOUT_ERROR;
+ }
+ else
+ {
+ /* Read CF ID bytes */
+ for(index = 0; index < 16; index++)
+ {
+ CompactFlash_ID[index] = *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_DATA);
+ }
+ }
+
+ /* Update the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hpccard);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Read sector from PCCARD memory
+ * @param hpccard : pointer to PCCARD handle
+ * @param pBuffer : pointer to destination read buffer
+ * @param SectorAddress : Sector address to read
+ * @param pStatus : pointer to CF status
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CF_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus)
+{
+ uint32_t timeout = 0xFFFF, index = 0;
+ uint8_t status;
+
+ /* Process Locked */
+ __HAL_LOCK(hpccard);
+
+ /* Check the PCCARD controller state */
+ if(hpccard->State == HAL_PCCARD_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_BUSY;
+
+ /* Initialize CF status */
+ *pStatus = CF_READY;
+
+ /* Set the parameters to write a sector */
+ *(__IO uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_CYLINDER_HIGH) = (uint16_t)0x00;
+ *(__IO uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_SECTOR_COUNT) = ((uint16_t)0x0100 ) | ((uint16_t)SectorAddress);
+ *(__IO uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD) = (uint16_t)0xE4A0;
+
+ do
+ {
+ /* wait till the Status = 0x80 */
+ status = *(__IO uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+ timeout--;
+ }while((status == 0x80) && timeout);
+
+ if(timeout == 0)
+ {
+ *pStatus = CF_TIMEOUT_ERROR;
+ }
+
+ timeout = 0xFFFF;
+
+ do
+ {
+ /* wait till the Status = 0x58 */
+ status = *(__IO uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+ timeout--;
+ }while((status != 0x58) && timeout);
+
+ if(timeout == 0)
+ {
+ *pStatus = CF_TIMEOUT_ERROR;
+ }
+
+ /* Read bytes */
+ for(; index < CF_SECTOR_SIZE; index++)
+ {
+ *(uint16_t *)pBuffer++ = *(uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR);
+ }
+
+ /* Update the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hpccard);
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Write sector to PCCARD memory
+ * @param hpccard : pointer to PCCARD handle
+ * @param pBuffer : pointer to source write buffer
+ * @param SectorAddress : Sector address to write
+ * @param pStatus : pointer to CF status
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CF_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus)
+{
+ uint32_t timeout = 0xFFFF, index = 0;
+ uint8_t status;
+
+ /* Process Locked */
+ __HAL_LOCK(hpccard);
+
+ /* Check the PCCARD controller state */
+ if(hpccard->State == HAL_PCCARD_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_BUSY;
+
+ /* Initialize CF status */
+ *pStatus = CF_READY;
+
+ /* Set the parameters to write a sector */
+ *(__IO uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_CYLINDER_HIGH) = (uint16_t)0x00;
+ *(__IO uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_SECTOR_COUNT) = ((uint16_t)0x0100 ) | ((uint16_t)SectorAddress);
+ *(__IO uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD) = (uint16_t)0x30A0;
+
+ do
+ {
+ /* Wait till the Status = 0x58 */
+ status = *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+ timeout--;
+ }while((status != 0x58) && timeout);
+
+ if(timeout == 0)
+ {
+ *pStatus = CF_TIMEOUT_ERROR;
+ }
+
+ /* Write bytes */
+ for(; index < CF_SECTOR_SIZE; index++)
+ {
+ *(uint16_t *)(CF_IO_SPACE_PRIMARY_ADDR) = *(uint16_t *)pBuffer++;
+ }
+
+ do
+ {
+ /* Wait till the Status = 0x50 */
+ status = *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+ timeout--;
+ }while((status != 0x50) && timeout);
+
+ if(timeout == 0)
+ {
+ *pStatus = CF_TIMEOUT_ERROR;
+ }
+
+ /* Update the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hpccard);
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Erase sector from PCCARD memory
+ * @param hpccard : pointer to PCCARD handle
+ * @param SectorAddress : Sector address to erase
+ * @param pStatus : pointer to CF status
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CF_Erase_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t SectorAddress, uint8_t *pStatus)
+{
+ uint32_t timeout = 0x400;
+ uint8_t status;
+
+ /* Process Locked */
+ __HAL_LOCK(hpccard);
+
+ /* Check the PCCARD controller state */
+ if(hpccard->State == HAL_PCCARD_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_BUSY;
+
+ /* Initialize CF status */
+ *pStatus = CF_READY;
+
+ /* Set the parameters to write a sector */
+ *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_CYLINDER_LOW) = 0x00;
+ *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_CYLINDER_HIGH) = 0x00;
+ *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_SECTOR_NUMBER) = SectorAddress;
+ *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_SECTOR_COUNT) = 0x01;
+ *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_CARD_HEAD) = 0xA0;
+ *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD) = CF_ERASE_SECTOR_CMD;
+
+ /* wait till the CF is ready */
+ status = *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+
+ while((status != 0x50) && timeout)
+ {
+ status = *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+ timeout--;
+ }
+
+ if(timeout == 0)
+ {
+ *pStatus = CF_TIMEOUT_ERROR;
+ }
+
+ /* Check the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hpccard);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Reset the PCCARD memory
+ * @param hpccard : pointer to PCCARD handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_CF_Reset(PCCARD_HandleTypeDef *hpccard)
+{
+
+ /* Process Locked */
+ __HAL_LOCK(hpccard);
+
+ /* Check the PCCARD controller state */
+ if(hpccard->State == HAL_PCCARD_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Provide an SW reset and Read and verify the:
+ - CF Configuration Option Register at address 0x98000200 --> 0x80
+ - Card Configuration and Status Register at address 0x98000202 --> 0x00
+ - Pin Replacement Register at address 0x98000204 --> 0x0C
+ - Socket and Copy Register at address 0x98000206 --> 0x00
+ */
+
+ /* Check the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_BUSY;
+
+ *(__IO uint8_t *)(0x98000202) = 0x01;
+
+ /* Check the PCCARD controller state */
+ hpccard->State = HAL_PCCARD_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hpccard);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles PCCARD device interrupt request.
+ * @param hpccard : pointer to PCCARD handle
+ * @retval HAL status
+*/
+void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard)
+{
+ /* Check PCCARD interrupt Rising edge flag */
+ if(__FMC_PCCARD_GET_FLAG(hpccard->Instance, FMC_FLAG_RISING_EDGE))
+ {
+ /* PCCARD interrupt callback*/
+ HAL_PCCARD_ITCallback(hpccard);
+
+ /* Clear PCCARD interrupt Rising edge pending bit */
+ __FMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FMC_FLAG_RISING_EDGE);
+ }
+
+ /* Check PCCARD interrupt Level flag */
+ if(__FMC_PCCARD_GET_FLAG(hpccard->Instance, FMC_FLAG_LEVEL))
+ {
+ /* PCCARD interrupt callback*/
+ HAL_PCCARD_ITCallback(hpccard);
+
+ /* Clear PCCARD interrupt Level pending bit */
+ __FMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FMC_FLAG_LEVEL);
+ }
+
+ /* Check PCCARD interrupt Falling edge flag */
+ if(__FMC_PCCARD_GET_FLAG(hpccard->Instance, FMC_FLAG_FALLING_EDGE))
+ {
+ /* PCCARD interrupt callback*/
+ HAL_PCCARD_ITCallback(hpccard);
+
+ /* Clear PCCARD interrupt Falling edge pending bit */
+ __FMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FMC_FLAG_FALLING_EDGE);
+ }
+
+ /* Check PCCARD interrupt FIFO empty flag */
+ if(__FMC_PCCARD_GET_FLAG(hpccard->Instance, FMC_FLAG_FEMPT))
+ {
+ /* PCCARD interrupt callback*/
+ HAL_PCCARD_ITCallback(hpccard);
+
+ /* Clear PCCARD interrupt FIFO empty pending bit */
+ __FMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FMC_FLAG_FEMPT);
+ }
+
+}
+
+/**
+ * @brief PCCARD interrupt feature callback
+ * @param hpccard : pointer to PCCARD handle
+ * @retval None
+ */
+__weak void HAL_PCCARD_ITCallback(PCCARD_HandleTypeDef *hpccard)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCCARD_ITCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup PCCARD_Group4 State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ==============================================================================
+ ##### PCCARD State functions #####
+ ==============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the PCCARD controller
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief return the PCCARD controller state
+ * @param hpccard : pointer to PCCARD handle
+ * @retval PCCARD controller state
+ */
+HAL_PCCARD_StateTypeDef HAL_PCCARD_GetState(PCCARD_HandleTypeDef *hpccard)
+{
+ return hpccard->State;
+}
+
+/**
+ * @brief Get the compact flash memory status
+ * @param hpccard: PCCARD handle
+ * @retval New status of the CF operation. This parameter can be:
+ * - CompactFlash_TIMEOUT_ERROR: when the previous operation generate
+ * a Timeout error
+ * - CompactFlash_READY: when memory is ready for the next operation
+ *
+ */
+CF_StatusTypedef HAL_CF_GetStatus(PCCARD_HandleTypeDef *hpccard)
+{
+ uint32_t timeout = 0x1000000, status_CF;
+
+ /* Check the PCCARD controller state */
+ if(hpccard->State == HAL_PCCARD_STATE_BUSY)
+ {
+ return CF_ONGOING;
+ }
+
+ status_CF = *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+
+ while((status_CF == CF_BUSY) && timeout)
+ {
+ status_CF = *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+ timeout--;
+ }
+
+ if(timeout == 0)
+ {
+ status_CF = CF_TIMEOUT_ERROR;
+ }
+
+ /* Return the operation status */
+ return (CF_StatusTypedef) status_CF;
+}
+
+/**
+ * @brief Reads the Compact Flash memory status using the Read status command
+ * @param hpccard : pointer to PCCARD handle
+ * @retval The status of the Compact Flash memory. This parameter can be:
+ * - CompactFlash_BUSY: when memory is busy
+ * - CompactFlash_READY: when memory is ready for the next operation
+ * - CompactFlash_ERROR: when the previous operation gererates error
+ */
+CF_StatusTypedef HAL_CF_ReadStatus(PCCARD_HandleTypeDef *hpccard)
+{
+ uint8_t data = 0, status_CF = CF_BUSY;
+
+ /* Check the PCCARD controller state */
+ if(hpccard->State == HAL_PCCARD_STATE_BUSY)
+ {
+ return CF_ONGOING;
+ }
+
+ /* Read status operation */
+ data = *(__IO uint8_t *)(CF_IO_SPACE_PRIMARY_ADDR | CF_STATUS_CMD_ALTERNATE);
+
+ if((data & CF_TIMEOUT_ERROR) == CF_TIMEOUT_ERROR)
+ {
+ status_CF = CF_TIMEOUT_ERROR;
+ }
+ else if((data & CF_READY) == CF_READY)
+ {
+ status_CF = CF_READY;
+ }
+
+ return (CF_StatusTypedef) status_CF;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_PCCARD_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pcd.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pcd.c
new file mode 100644
index 0000000..7a72f2f
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pcd.c
@@ -0,0 +1,1212 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_pcd.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief PCD HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the USB Peripheral Controller:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The PCD HAL driver can be used as follows:
+
+ (#) Declare a PCD_HandleTypeDef handle structure, for example:
+ PCD_HandleTypeDef hpcd;
+
+ (#) Fill parameters of Init structure in HCD handle
+
+ (#) Call HAL_PCD_Init() API to initialize the HCD peripheral (Core, Device core, ...)
+
+ (#) Initialize the PCD low level resources through the HAL_PCD_MspInit() API:
+ (##) Enable the PCD/USB Low Level interface clock using
+ (+++) __OTGFS-OTG_CLK_ENABLE()/__OTGHS-OTG_CLK_ENABLE();
+ (+++) __OTGHSULPI_CLK_ENABLE(); (For High Speed Mode)
+
+ (##) Initialize the related GPIO clocks
+ (##) Configure PCD pin-out
+ (##) Configure PCD NVIC interrupt
+
+ (#)Associate the Upper USB device stack to the HAL PCD Driver:
+ (##) hpcd.pData = pdev;
+
+ (#)Enable HCD transmission and reception:
+ (##) HAL_PCD_Start();
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup PCD
+ * @brief PCD HAL module driver
+ * @{
+ */
+
+#ifdef HAL_PCD_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+#define PCD_MIN(a, b) (((a) < (b)) ? (a) : (b))
+#define PCD_MAX(a, b) (((a) > (b)) ? (a) : (b))
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup PCD_Private_Functions
+ * @{
+ */
+
+/** @defgroup PCD_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the PCD according to the specified
+ * parameters in the PCD_InitTypeDef and create the associated handle.
+ * @param hpcd: PCD handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd)
+{
+ uint32_t i = 0;
+
+ /* Check the PCD handle allocation */
+ if(hpcd == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance));
+
+ hpcd->State = PCD_BUSY;
+
+ /* Init the low level hardware : GPIO, CLOCK, NVIC... */
+ HAL_PCD_MspInit(hpcd);
+
+ /* Disable the Interrupts */
+ __HAL_PCD_DISABLE(hpcd);
+
+ /*Init the Core (common init.) */
+ USB_CoreInit(hpcd->Instance, hpcd->Init);
+
+ /* Force Device Mode*/
+ USB_SetCurrentMode(hpcd->Instance , USB_OTG_DEVICE_MODE);
+
+ /* Init endpoints structures */
+ for (i = 0; i < 15 ; i++)
+ {
+ /* Init ep structure */
+ hpcd->IN_ep[i].is_in = 1;
+ hpcd->IN_ep[i].num = i;
+ hpcd->IN_ep[i].tx_fifo_num = i;
+ /* Control until ep is actvated */
+ hpcd->IN_ep[i].type = EP_TYPE_CTRL;
+ hpcd->IN_ep[i].maxpacket = 0;
+ hpcd->IN_ep[i].xfer_buff = 0;
+ hpcd->IN_ep[i].xfer_len = 0;
+ }
+
+ for (i = 0; i < 15 ; i++)
+ {
+ hpcd->OUT_ep[i].is_in = 0;
+ hpcd->OUT_ep[i].num = i;
+ hpcd->IN_ep[i].tx_fifo_num = i;
+ /* Control until ep is activated */
+ hpcd->OUT_ep[i].type = EP_TYPE_CTRL;
+ hpcd->OUT_ep[i].maxpacket = 0;
+ hpcd->OUT_ep[i].xfer_buff = 0;
+ hpcd->OUT_ep[i].xfer_len = 0;
+
+ hpcd->Instance->DIEPTXF[i] = 0;
+ }
+
+ /* Init Device */
+ USB_DevInit(hpcd->Instance, hpcd->Init);
+
+ hpcd->State= PCD_READY;
+
+ USB_DevDisconnect (hpcd->Instance);
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the PCD peripheral
+ * @param hpcd: PCD handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_DeInit(PCD_HandleTypeDef *hpcd)
+{
+ /* Check the PCD handle allocation */
+ if(hpcd == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ hpcd->State = PCD_BUSY;
+
+ /* Stop Device */
+ HAL_PCD_Stop(hpcd);
+
+ /* DeInit the low level hardware */
+ HAL_PCD_MspDeInit(hpcd);
+
+ hpcd->State = PCD_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the PCD MSP.
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+__weak void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_MspInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes PCD MSP.
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+__weak void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_MspDeInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup PCD_Group2 IO operation functions
+ * @brief Data transfers functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the PCD data
+ transfers.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Start The USB OTG Device.
+ * @param hpcd: PCD handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd)
+{
+ __HAL_LOCK(hpcd);
+ USB_DevConnect (hpcd->Instance);
+ __HAL_PCD_ENABLE(hpcd);
+ __HAL_UNLOCK(hpcd);
+ return HAL_OK;
+}
+
+/**
+ * @brief Stop The USB OTG Device.
+ * @param hpcd: PCD handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd)
+{
+ __HAL_LOCK(hpcd);
+ __HAL_PCD_DISABLE(hpcd);
+ USB_StopDevice(hpcd->Instance);
+ USB_DevDisconnect (hpcd->Instance);
+ __HAL_UNLOCK(hpcd);
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles PCD interrupt request.
+ * @param hpcd: PCD handle
+ * @retval HAL status
+ */
+void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd)
+{
+ USB_OTG_GlobalTypeDef *USBx = hpcd->Instance;
+ uint32_t i = 0, ep_intr = 0, epint = 0, epnum = 0;
+ uint32_t fifoemptymsk = 0, temp = 0;
+ USB_OTG_EPTypeDef *ep;
+
+ /* ensure that we are in device mode */
+ if (USB_GetMode(hpcd->Instance) == USB_OTG_MODE_DEVICE)
+ {
+ /* avoid spurious interrupt */
+ if(__HAL_IS_INVALID_INTERRUPT(hpcd))
+ {
+ return;
+ }
+
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_MMIS))
+ {
+ /* incorrect mode, acknowledge the interrupt */
+ __HAL_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_MMIS);
+ }
+
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_OEPINT))
+ {
+ epnum = 0;
+
+ /* Read in the device interrupt bits */
+ ep_intr = USB_ReadDevAllOutEpInterrupt(hpcd->Instance);
+
+ while ( ep_intr )
+ {
+ if (ep_intr & 0x1)
+ {
+ epint = USB_ReadDevOutEPInterrupt(hpcd->Instance, epnum);
+
+ if(( epint & USB_OTG_DOEPINT_XFRC) == USB_OTG_DOEPINT_XFRC)
+ {
+ CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_XFRC);
+
+ if(hpcd->Init.dma_enable == 1)
+ {
+ hpcd->OUT_ep[epnum].xfer_count = hpcd->OUT_ep[epnum].maxpacket- (USBx_OUTEP(epnum)->DOEPTSIZ & USB_OTG_DOEPTSIZ_XFRSIZ);
+ hpcd->OUT_ep[epnum].xfer_buff += hpcd->OUT_ep[epnum].maxpacket;
+ }
+
+ HAL_PCD_DataOutStageCallback(hpcd, epnum);
+ if(hpcd->Init.dma_enable == 1)
+ {
+ if((epnum == 0) && (hpcd->OUT_ep[epnum].xfer_len == 0))
+ {
+ /* this is ZLP, so prepare EP0 for next setup */
+ USB_EP0_OutStart(hpcd->Instance, 1, (uint8_t *)hpcd->Setup);
+ }
+ }
+ }
+
+ if(( epint & USB_OTG_DOEPINT_STUP) == USB_OTG_DOEPINT_STUP)
+ {
+ /* Inform the upper layer that a setup packet is available */
+ HAL_PCD_SetupStageCallback(hpcd);
+ CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STUP);
+ }
+
+ if(( epint & USB_OTG_DOEPINT_OTEPDIS) == USB_OTG_DOEPINT_OTEPDIS)
+ {
+ CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPDIS);
+ }
+ }
+ epnum++;
+ ep_intr >>= 1;
+ }
+ }
+
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_IEPINT))
+ {
+ /* Read in the device interrupt bits */
+ ep_intr = USB_ReadDevAllInEpInterrupt(hpcd->Instance);
+
+ epnum = 0;
+
+ while ( ep_intr )
+ {
+ if (ep_intr & 0x1) /* In ITR */
+ {
+ epint = USB_ReadDevInEPInterrupt(hpcd->Instance, epnum);
+
+ if(( epint & USB_OTG_DIEPINT_XFRC) == USB_OTG_DIEPINT_XFRC)
+ {
+ fifoemptymsk = 0x1 << epnum;
+ USBx_DEVICE->DIEPEMPMSK = ~fifoemptymsk;
+
+ CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_XFRC);
+
+ if (hpcd->Init.dma_enable == 1)
+ {
+ hpcd->IN_ep[epnum].xfer_buff += hpcd->IN_ep[epnum].maxpacket;
+ }
+
+ HAL_PCD_DataInStageCallback(hpcd, epnum);
+
+ if (hpcd->Init.dma_enable == 1)
+ {
+ /* this is ZLP, so prepare EP0 for next setup */
+ if((epnum == 0) && (hpcd->IN_ep[epnum].xfer_len == 0))
+ {
+ /* prepare to rx more setup packets */
+ USB_EP0_OutStart(hpcd->Instance, 1, (uint8_t *)hpcd->Setup);
+ }
+ }
+ }
+ if(( epint & USB_OTG_DIEPINT_TOC) == USB_OTG_DIEPINT_TOC)
+ {
+ CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_TOC);
+ }
+ if(( epint & USB_OTG_DIEPINT_ITTXFE) == USB_OTG_DIEPINT_ITTXFE)
+ {
+ CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_ITTXFE);
+ }
+ if(( epint & USB_OTG_DIEPINT_INEPNE) == USB_OTG_DIEPINT_INEPNE)
+ {
+ CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_INEPNE);
+ }
+ if(( epint & USB_OTG_DIEPINT_EPDISD) == USB_OTG_DIEPINT_EPDISD)
+ {
+ CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_EPDISD);
+ }
+ if(( epint & USB_OTG_DIEPINT_TXFE) == USB_OTG_DIEPINT_TXFE)
+ {
+ PCD_WriteEmptyTxFifo(hpcd , epnum);
+ }
+ }
+ epnum++;
+ ep_intr >>= 1;
+ }
+ }
+
+ /* Handle Resume Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_WKUINT))
+ {
+ /* Clear the Remote Wake-up Signaling */
+ USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG;
+
+ HAL_PCD_ResumeCallback(hpcd);
+
+ __HAL_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_WKUINT);
+ }
+
+ /* Handle Suspend Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_USBSUSP))
+ {
+
+ if((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSPSTS) == USB_OTG_DSTS_SUSPSTS)
+ {
+
+ HAL_PCD_SuspendCallback(hpcd);
+ }
+ __HAL_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_USBSUSP);
+ }
+
+
+
+ /* Handle Reset Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_USBRST))
+ {
+ USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG;
+ USB_FlushTxFifo(hpcd->Instance , 0 );
+
+ for (i = 0; i < hpcd->Init.dev_endpoints ; i++)
+ {
+ USBx_INEP(i)->DIEPINT = 0xFF;
+ USBx_OUTEP(i)->DOEPINT = 0xFF;
+ }
+ USBx_DEVICE->DAINT = 0xFFFFFFFF;
+ USBx_DEVICE->DAINTMSK |= 0x10001;
+
+ if(hpcd->Init.use_dedicated_ep1)
+ {
+ USBx_DEVICE->DOUTEP1MSK |= (USB_OTG_DOEPMSK_STUPM | USB_OTG_DOEPMSK_XFRCM | USB_OTG_DOEPMSK_EPDM);
+ USBx_DEVICE->DINEP1MSK |= (USB_OTG_DIEPMSK_TOM | USB_OTG_DIEPMSK_XFRCM | USB_OTG_DIEPMSK_EPDM);
+ }
+ else
+ {
+ USBx_DEVICE->DOEPMSK |= (USB_OTG_DOEPMSK_STUPM | USB_OTG_DOEPMSK_XFRCM | USB_OTG_DOEPMSK_EPDM);
+ USBx_DEVICE->DIEPMSK |= (USB_OTG_DIEPMSK_TOM | USB_OTG_DIEPMSK_XFRCM | USB_OTG_DIEPMSK_EPDM);
+ }
+
+ /* Set Default Address to 0 */
+ USBx_DEVICE->DCFG &= ~USB_OTG_DCFG_DAD;
+
+ /* setup EP0 to receive SETUP packets */
+ USB_EP0_OutStart(hpcd->Instance, hpcd->Init.dma_enable, (uint8_t *)hpcd->Setup);
+
+ __HAL_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_USBRST);
+ }
+
+ /* Handle Enumeration done Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_ENUMDNE))
+ {
+ USB_ActivateSetup(hpcd->Instance);
+ hpcd->Instance->GUSBCFG &= ~USB_OTG_GUSBCFG_TRDT;
+
+ if ( USB_GetDevSpeed(hpcd->Instance) == USB_OTG_SPEED_HIGH)
+ {
+ hpcd->Init.speed = USB_OTG_SPEED_HIGH;
+ hpcd->Init.ep0_mps = USB_OTG_HS_MAX_PACKET_SIZE ;
+ hpcd->Instance->GUSBCFG |= (USB_OTG_GUSBCFG_TRDT_0 | USB_OTG_GUSBCFG_TRDT_3);
+ }
+ else
+ {
+ hpcd->Init.speed = USB_OTG_SPEED_FULL;
+ hpcd->Init.ep0_mps = USB_OTG_FS_MAX_PACKET_SIZE ;
+ hpcd->Instance->GUSBCFG |= (USB_OTG_GUSBCFG_TRDT_0 | USB_OTG_GUSBCFG_TRDT_2);
+ }
+
+ HAL_PCD_ResetCallback(hpcd);
+
+ __HAL_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_ENUMDNE);
+ }
+
+
+ /* Handle RxQLevel Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_RXFLVL))
+ {
+ USB_MASK_INTERRUPT(hpcd->Instance, USB_OTG_GINTSTS_RXFLVL);
+ temp = USBx->GRXSTSP;
+ ep = &hpcd->OUT_ep[temp & USB_OTG_GRXSTSP_EPNUM];
+
+ if(((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_DATA_UPDT)
+ {
+ if((temp & USB_OTG_GRXSTSP_BCNT) != 0)
+ {
+ USB_ReadPacket(USBx, ep->xfer_buff, (temp & USB_OTG_GRXSTSP_BCNT) >> 4);
+ ep->xfer_buff += (temp & USB_OTG_GRXSTSP_BCNT) >> 4;
+ ep->xfer_count += (temp & USB_OTG_GRXSTSP_BCNT) >> 4;
+ }
+ }
+ else if (((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_SETUP_UPDT)
+ {
+ USB_ReadPacket(USBx, (uint8_t *)hpcd->Setup, 8);
+ ep->xfer_count += (temp & USB_OTG_GRXSTSP_BCNT) >> 4;
+ }
+ USB_UNMASK_INTERRUPT(hpcd->Instance, USB_OTG_GINTSTS_RXFLVL);
+ }
+
+ /* Handle SOF Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_SOF))
+ {
+ HAL_PCD_SOFCallback(hpcd);
+ __HAL_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_SOF);
+ }
+
+ /* Handle Incomplete ISO IN Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_IISOIXFR))
+ {
+ HAL_PCD_ISOINIncompleteCallback(hpcd, epnum);
+ __HAL_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_IISOIXFR);
+ }
+
+ /* Handle Incomplete ISO OUT Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT))
+ {
+ HAL_PCD_ISOOUTIncompleteCallback(hpcd, epnum);
+ __HAL_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT);
+ }
+
+ /* Handle Connection event Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_SRQINT))
+ {
+ HAL_PCD_ConnectCallback(hpcd);
+ __HAL_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_SRQINT);
+ }
+
+ /* Handle Disconnection event Interrupt */
+ if(__HAL_GET_FLAG(hpcd, USB_OTG_GINTSTS_OTGINT))
+ {
+ temp = hpcd->Instance->GOTGINT;
+
+ if((temp & USB_OTG_GOTGINT_SEDET) == USB_OTG_GOTGINT_SEDET)
+ {
+ HAL_PCD_DisconnectCallback(hpcd);
+ }
+ hpcd->Instance->GOTGINT |= temp;
+ }
+ }
+}
+
+/**
+ * @brief Data out stage callbacks
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+ __weak void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Data IN stage callbacks
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+ __weak void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+/**
+ * @brief Setup stage callback
+ * @param hpcd: ppp handle
+ * @retval None
+ */
+ __weak void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief USB Start Of Frame callbacks
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+ __weak void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief USB Reset callbacks
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+ __weak void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+
+/**
+ * @brief Suspend event callbacks
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+ __weak void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Resume event callbacks
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+ __weak void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Incomplete ISO OUT callbacks
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+ __weak void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Incomplete ISO IN callbacks
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+ __weak void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Connection event callbacks
+ * @param hpcd: PCD handle
+ * @retval None
+ */
+ __weak void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Disconnection event callbacks
+ * @param hpcd: ppp handle
+ * @retval None
+ */
+ __weak void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PCD_DataOutStageCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup PCD_Group3 Peripheral Control functions
+ * @brief management functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the PCD data
+ transfers.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Send an amount of data in blocking mode
+ * @param hpcd: PCD handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd)
+{
+ __HAL_LOCK(hpcd);
+ USB_DevConnect(hpcd->Instance);
+ __HAL_UNLOCK(hpcd);
+ return HAL_OK;
+}
+
+/**
+ * @brief Send an amount of data in blocking mode
+ * @param hpcd: PCD handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd)
+{
+ __HAL_LOCK(hpcd);
+ USB_DevDisconnect(hpcd->Instance);
+ __HAL_UNLOCK(hpcd);
+ return HAL_OK;
+}
+
+/**
+ * @brief Set the USB Device address
+ * @param hpcd: PCD handle
+ * @param address: new device address
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address)
+{
+ __HAL_LOCK(hpcd);
+ USB_SetDevAddress(hpcd->Instance, address);
+ __HAL_UNLOCK(hpcd);
+ return HAL_OK;
+}
+/**
+ * @brief Open and configure an endpoint
+ * @param hpcd: PCD handle
+ * @param ep_addr: endpoint address
+ * @param ep_mps: endpoint max packert size
+ * @param ep_type: endpoint type
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type)
+{
+ HAL_StatusTypeDef ret = HAL_OK;
+ USB_OTG_EPTypeDef *ep;
+
+ if ((ep_addr & 0x80) == 0x80)
+ {
+ ep = &hpcd->IN_ep[ep_addr & 0x7F];
+ }
+ else
+ {
+ ep = &hpcd->OUT_ep[ep_addr & 0x7F];
+ }
+ ep->num = ep_addr & 0x7F;
+
+ ep->is_in = (0x80 & ep_addr) != 0;
+ ep->maxpacket = ep_mps;
+ ep->type = ep_type;
+ if (ep->is_in)
+ {
+ /* Assign a Tx FIFO */
+ ep->tx_fifo_num = ep->num;
+ }
+ /* Set initial data PID. */
+ if (ep_type == EP_TYPE_BULK )
+ {
+ ep->data_pid_start = 0;
+ }
+
+ __HAL_LOCK(hpcd);
+ USB_ActivateEndpoint(hpcd->Instance , ep);
+ __HAL_UNLOCK(hpcd);
+ return ret;
+}
+
+
+/**
+ * @brief Deactivate an endpoint
+ * @param hpcd: PCD handle
+ * @param ep_addr: endpoint address
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
+{
+ USB_OTG_EPTypeDef *ep;
+
+ if ((ep_addr & 0x80) == 0x80)
+ {
+ ep = &hpcd->IN_ep[ep_addr & 0x7F];
+ }
+ else
+ {
+ ep = &hpcd->OUT_ep[ep_addr & 0x7F];
+ }
+ ep->num = ep_addr & 0x7F;
+
+ ep->is_in = (0x80 & ep_addr) != 0;
+
+ __HAL_LOCK(hpcd);
+ USB_DeactivateEndpoint(hpcd->Instance , ep);
+ __HAL_UNLOCK(hpcd);
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Receive an amount of data
+ * @param hpcd: PCD handle
+ * @param ep_addr: endpoint address
+ * @param pBuf: pointer to the reception buffer
+ * @param len: amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len)
+{
+
+ USB_OTG_EPTypeDef *ep;
+
+ ep = &hpcd->OUT_ep[ep_addr & 0x7F];
+
+ /*setup and start the Xfer */
+ ep->xfer_buff = pBuf;
+ ep->xfer_len = len;
+ ep->xfer_count = 0;
+ ep->is_in = 0;
+ ep->num = ep_addr & 0x7F;
+
+ if (hpcd->Init.dma_enable == 1)
+ {
+ ep->dma_addr = (uint32_t)pBuf;
+ }
+
+ __HAL_LOCK(hpcd);
+
+ if ((ep_addr & 0x7F) == 0 )
+ {
+ USB_EP0StartXfer(hpcd->Instance , ep, hpcd->Init.dma_enable);
+ }
+ else
+ {
+ USB_EPStartXfer(hpcd->Instance , ep, hpcd->Init.dma_enable);
+ }
+ __HAL_UNLOCK(hpcd);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Get Received Data Size
+ * @param hpcd: PCD handle
+ * @param ep_addr: endpoint address
+ * @retval Data Size
+ */
+uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
+{
+ return hpcd->OUT_ep[ep_addr & 0x7F].xfer_count;
+}
+/**
+ * @brief Send an amount of data
+ * @param hpcd: PCD handle
+ * @param ep_addr: endpoint address
+ * @param pBuf: pointer to the transmission buffer
+ * @param len: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len)
+{
+ USB_OTG_EPTypeDef *ep;
+
+ ep = &hpcd->IN_ep[ep_addr & 0x7F];
+
+ /*setup and start the Xfer */
+ ep->xfer_buff = pBuf;
+ ep->xfer_len = len;
+ ep->xfer_count = 0;
+ ep->is_in = 1;
+ ep->num = ep_addr & 0x7F;
+
+ if (hpcd->Init.dma_enable == 1)
+ {
+ ep->dma_addr = (uint32_t)pBuf;
+ }
+
+ __HAL_LOCK(hpcd);
+
+ if ((ep_addr & 0x7F) == 0 )
+ {
+ USB_EP0StartXfer(hpcd->Instance , ep, hpcd->Init.dma_enable);
+ }
+ else
+ {
+ USB_EPStartXfer(hpcd->Instance , ep, hpcd->Init.dma_enable);
+ }
+
+ __HAL_UNLOCK(hpcd);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Set a STALL condition over an endpoint
+ * @param hpcd: PCD handle
+ * @param ep_addr: endpoint address
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
+{
+ USB_OTG_EPTypeDef *ep;
+
+ if ((0x80 & ep_addr) == 0x80)
+ {
+ ep = &hpcd->IN_ep[ep_addr & 0x7F];
+ }
+ else
+ {
+ ep = &hpcd->OUT_ep[ep_addr];
+ }
+
+ ep->is_stall = 1;
+ ep->num = ep_addr & 0x7F;
+ ep->is_in = ((ep_addr & 0x80) == 0x80);
+
+
+ __HAL_LOCK(hpcd);
+ USB_EPSetStall(hpcd->Instance , ep);
+ if((ep_addr & 0x7F) == 0)
+ {
+ USB_EP0_OutStart(hpcd->Instance, hpcd->Init.dma_enable, (uint8_t *)hpcd->Setup);
+ }
+ __HAL_UNLOCK(hpcd);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Clear a STALL condition over in an endpoint
+ * @param hpcd: PCD handle
+ * @param ep_addr: endpoint address
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
+{
+ USB_OTG_EPTypeDef *ep;
+
+ if ((0x80 & ep_addr) == 0x80)
+ {
+ ep = &hpcd->IN_ep[ep_addr & 0x7F];
+ }
+ else
+ {
+ ep = &hpcd->OUT_ep[ep_addr];
+ }
+
+ ep->is_stall = 0;
+ ep->num = ep_addr & 0x7F;
+ ep->is_in = ((ep_addr & 0x80) == 0x80);
+
+ __HAL_LOCK(hpcd);
+ USB_EPClearStall(hpcd->Instance , ep);
+ __HAL_UNLOCK(hpcd);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Flush an endpoint
+ * @param hpcd: PCD handle
+ * @param ep_addr: endpoint address
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
+{
+ __HAL_LOCK(hpcd);
+
+ if ((ep_addr & 0x80) == 0x80)
+ {
+ USB_FlushTxFifo(hpcd->Instance, ep_addr & 0x7F);
+ }
+ else
+ {
+ USB_FlushRxFifo(hpcd->Instance);
+ }
+
+ __HAL_UNLOCK(hpcd);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Update FIFO configuration
+ * @param hpcd: PCD handle
+ * @retval status
+ */
+HAL_StatusTypeDef HAL_PCD_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size)
+{
+ uint8_t i = 0;
+ uint32_t Tx_Offset = 0;
+
+
+ /* TXn min size = 16 words. (n : Transmit FIFO index)
+ * When a TxFIFO is not used, the Configuration should be as follows:
+ * case 1 : n > m and Txn is not used (n,m : Transmit FIFO indexes)
+ * --> Txm can use the space allocated for Txn.
+ * case2 : n < m and Txn is not used (n,m : Transmit FIFO indexes)
+ * --> Txn should be configured with the minimum space of 16 words
+ * The FIFO is used optimally when used TxFIFOs are allocated in the top
+ * of the FIFO.Ex: use EP1 and EP2 as IN instead of EP1 and EP3 as IN ones.
+ * When DMA is used 3n * FIFO locations should be reserved for internal DMA registers */
+
+ Tx_Offset = hpcd->Instance->GRXFSIZ;
+
+ if(fifo == 0)
+ {
+ hpcd->Instance->DIEPTXF0_HNPTXFSIZ = (size << 16) | Tx_Offset;
+ }
+ else
+ {
+ Tx_Offset += (hpcd->Instance->DIEPTXF0_HNPTXFSIZ) >> 16;
+ for (i = 0; i < (fifo - 1); i++)
+ {
+ Tx_Offset += (hpcd->Instance->DIEPTXF[i] >> 16);
+ }
+
+ /* Multiply Tx_Size by 2 to get higher performance */
+ hpcd->Instance->DIEPTXF[fifo - 1] = (size << 16) | Tx_Offset;
+
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Update FIFO configuration
+ * @param hpcd: PCD handle
+ * @retval status
+ */
+HAL_StatusTypeDef HAL_PCD_SetRxFiFo(PCD_HandleTypeDef *hpcd, uint16_t size)
+{
+
+ hpcd->Instance->GRXFSIZ = size;
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief HAL_PCD_ActiveRemoteWakeup : active remote wakeup signalling
+ * @param hpcd: PCD handle
+ * @retval status
+ */
+HAL_StatusTypeDef HAL_PCD_ActiveRemoteWakeup(PCD_HandleTypeDef *hpcd)
+{
+ USB_OTG_GlobalTypeDef *USBx = hpcd->Instance;
+
+ if((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSPSTS) == USB_OTG_DSTS_SUSPSTS)
+ {
+ /* active Remote wakeup signaling */
+ USBx_DEVICE->DCTL |= USB_OTG_DCTL_RWUSIG;
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief HAL_PCD_DeActiveRemoteWakeup : de-active remote wakeup signalling
+ * @param hpcd: PCD handle
+ * @retval status
+ */
+HAL_StatusTypeDef HAL_PCD_DeActiveRemoteWakeup(PCD_HandleTypeDef *hpcd)
+{
+ USB_OTG_GlobalTypeDef *USBx = hpcd->Instance;
+
+ /* active Remote wakeup signaling */
+ USBx_DEVICE->DCTL &= ~(USB_OTG_DCTL_RWUSIG);
+ return HAL_OK;
+}
+/**
+ * @}
+ */
+
+/** @defgroup PCD_Group4 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State functions #####
+ ===============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the PCD state
+ * @param hpcd : PCD handle
+ * @retval HAL state
+ */
+PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd)
+{
+ return hpcd->State;
+}
+/**
+ * @}
+ */
+
+/**
+ * @brief DCD_WriteEmptyTxFifo
+ * check FIFO for the next packet to be loaded
+ * @param hpcd: PCD handle
+ * @retval status
+ */
+static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum)
+{
+ USB_OTG_GlobalTypeDef *USBx = hpcd->Instance;
+ USB_OTG_EPTypeDef *ep;
+ int32_t len = 0;
+ uint32_t len32b;
+ uint32_t fifoemptymsk = 0;
+
+ ep = &hpcd->IN_ep[epnum];
+ len = ep->xfer_len - ep->xfer_count;
+
+ if (len > ep->maxpacket)
+ {
+ len = ep->maxpacket;
+ }
+
+
+ len32b = (len + 3) / 4;
+
+ while ( (USBx_INEP(epnum)->DTXFSTS & USB_OTG_DTXFSTS_INEPTFSAV) > len32b &&
+ ep->xfer_count < ep->xfer_len &&
+ ep->xfer_len != 0)
+ {
+ /* Write the FIFO */
+ len = ep->xfer_len - ep->xfer_count;
+
+ if (len > ep->maxpacket)
+ {
+ len = ep->maxpacket;
+ }
+ len32b = (len + 3) / 4;
+
+ USB_WritePacket(USBx, ep->xfer_buff, epnum, len, hpcd->Init.dma_enable);
+
+ ep->xfer_buff += len;
+ ep->xfer_count += len;
+ }
+
+ if(len <= 0)
+ {
+ fifoemptymsk = 0x1 << epnum;
+ USBx_DEVICE->DIEPEMPMSK &= ~fifoemptymsk;
+
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_PCD_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr.c
new file mode 100644
index 0000000..7577942
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr.c
@@ -0,0 +1,520 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_pwr.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief PWR HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Power Controller (PWR) peripheral:
+ * + Initialization and de-initialization functions
+ * + Peripheral Control functions
+ *
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup PWR
+ * @brief PWR HAL module driver
+ * @{
+ */
+
+#ifdef HAL_PWR_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup PWR_Private_Functions
+ * @{
+ */
+
+/** @defgroup PWR_Group1 Initialization and de-initialization functions
+ * @brief Initialization and de-initialization functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..]
+ After reset, the backup domain (RTC registers, RTC backup data
+ registers and backup SRAM) is protected against possible unwanted
+ write accesses.
+ To enable access to the RTC Domain and RTC registers, proceed as follows:
+ (+) Enable the Power Controller (PWR) APB1 interface clock using the
+ __PWR_CLK_ENABLE() macro.
+ (+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Deinitializes the HAL PWR peripheral registers to their default reset values.
+ * @param None
+ * @retval None
+ */
+void HAL_PWR_DeInit(void)
+{
+ __PWR_FORCE_RESET();
+ __PWR_RELEASE_RESET();
+}
+
+/**
+ * @brief Enables access to the backup domain (RTC registers, RTC
+ * backup data registers and backup SRAM).
+ * @note If the HSE divided by 2, 3, ..31 is used as the RTC clock, the
+ * Backup Domain Access should be kept enabled.
+ * @param None
+ * @retval None
+ */
+void HAL_PWR_EnableBkUpAccess(void)
+{
+ *(__IO uint32_t *) CR_DBP_BB = (uint32_t)ENABLE;
+}
+
+/**
+ * @brief Disables access to the backup domain (RTC registers, RTC
+ * backup data registers and backup SRAM).
+ * @note If the HSE divided by 2, 3, ..31 is used as the RTC clock, the
+ * Backup Domain Access should be kept enabled.
+ * @param None
+ * @retval None
+ */
+void HAL_PWR_DisableBkUpAccess(void)
+{
+ *(__IO uint32_t *) CR_DBP_BB = (uint32_t)DISABLE;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup PWR_Group2 Peripheral Control functions
+ * @brief Low Power modes configuration functions
+ *
+@verbatim
+
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+
+ *** PVD configuration ***
+ =========================
+ [..]
+ (+) The PVD is used to monitor the VDD power supply by comparing it to a
+ threshold selected by the PVD Level (PLS[2:0] bits in the PWR_CR).
+ (+) A PVDO flag is available to indicate if VDD/VDDA is higher or lower
+ than the PVD threshold. This event is internally connected to the EXTI
+ line16 and can generate an interrupt if enabled. This is done through
+ __HAL_PVD_EXTI_ENABLE_IT() macro.
+ (+) The PVD is stopped in Standby mode.
+
+ *** WakeUp pin configuration ***
+ ================================
+ [..]
+ (+) WakeUp pin is used to wake up the system from Standby mode. This pin is
+ forced in input pull-down configuration and is active on rising edges.
+ (+) There is only one WakeUp pin: WakeUp Pin 1 on PA.00.
+
+ *** Low Power modes configuration ***
+ =====================================
+ [..]
+ The devices feature 3 low-power modes:
+ (+) Sleep mode: Cortex-M4 core stopped, peripherals kept running.
+ (+) Stop mode: all clocks are stopped, regulator running, regulator
+ in low power mode
+ (+) Standby mode: 1.2V domain powered off.
+
+ *** Sleep mode ***
+ ==================
+ [..]
+ (+) Entry:
+ The Sleep mode is entered by using the HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI)
+ functions with
+ (++) PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction
+ (++) PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction
+
+ -@@- The Regulator parameter is not used for the STM32F4 family
+ and is kept as parameter just to maintain compatibility with the
+ lower power families (STM32L).
+ (+) Exit:
+ Any peripheral interrupt acknowledged by the nested vectored interrupt
+ controller (NVIC) can wake up the device from Sleep mode.
+
+ *** Stop mode ***
+ =================
+ [..]
+ In Stop mode, all clocks in the 1.2V domain are stopped, the PLL, the HSI,
+ and the HSE RC oscillators are disabled. Internal SRAM and register contents
+ are preserved.
+ The voltage regulator can be configured either in normal or low-power mode.
+ To minimize the consumption In Stop mode, FLASH can be powered off before
+ entering the Stop mode using the HAL_PWR_EnableFlashPowerDown() function.
+ It can be switched on again by software after exiting the Stop mode using
+ the HAL_PWR_DisableFlashPowerDown() function.
+
+ (+) Entry:
+ The Stop mode is entered using the HAL_PWR_EnterSTOPMode(PWR_MAINREGULATOR_ON)
+ function with:
+ (++) Main regulator ON.
+ (++) Low Power regulator ON.
+ (+) Exit:
+ Any EXTI Line (Internal or External) configured in Interrupt/Event mode.
+
+ *** Standby mode ***
+ ====================
+ [..]
+ (+)
+ The Standby mode allows to achieve the lowest power consumption. It is based
+ on the Cortex-M4 deep sleep mode, with the voltage regulator disabled.
+ The 1.2V domain is consequently powered off. The PLL, the HSI oscillator and
+ the HSE oscillator are also switched off. SRAM and register contents are lost
+ except for the RTC registers, RTC backup registers, backup SRAM and Standby
+ circuitry.
+
+ The voltage regulator is OFF.
+
+ (++) Entry:
+ (+++) The Standby mode is entered using the HAL_PWR_EnterSTANDBYMode() function.
+ (++) Exit:
+ (+++) WKUP pin rising edge, RTC alarm (Alarm A and Alarm B), RTC wakeup,
+ tamper event, time-stamp event, external reset in NRST pin, IWDG reset.
+
+ *** Auto-wakeup (AWU) from low-power mode ***
+ =============================================
+ [..]
+
+ (+) The MCU can be woken up from low-power mode by an RTC Alarm event, an RTC
+ Wakeup event, a tamper event or a time-stamp event, without depending on
+ an external interrupt (Auto-wakeup mode).
+
+ (+) RTC auto-wakeup (AWU) from the Stop and Standby modes
+
+ (++) To wake up from the Stop mode with an RTC alarm event, it is necessary to
+ configure the RTC to generate the RTC alarm using the HAL_RTC_SetAlarm_IT() function.
+
+ (++) To wake up from the Stop mode with an RTC Tamper or time stamp event, it
+ is necessary to configure the RTC to detect the tamper or time stamp event using the
+ HAL_RTCEx_SetTimeStamp_IT() or HAL_RTCEx_SetTamper_IT() functions.
+
+ (++) To wake up from the Stop mode with an RTC WakeUp event, it is necessary to
+ configure the RTC to generate the RTC WakeUp event using the HAL_RTCEx_SetWakeUpTimer_IT() function.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Configures the voltage threshold detected by the Power Voltage Detector(PVD).
+ * @param sConfigPVD: pointer to an PWR_PVDTypeDef structure that contains the configuration
+ * information for the PVD.
+ * @note Refer to the electrical characteristics of your device datasheet for
+ * more details about the voltage threshold corresponding to each
+ * detection level.
+ * @retval None
+ */
+void HAL_PWR_PVDConfig(PWR_PVDTypeDef *sConfigPVD)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_PWR_PVD_LEVEL(sConfigPVD->PVDLevel));
+ assert_param(IS_PWR_PVD_MODE(sConfigPVD->Mode));
+
+ tmpreg = PWR->CR;
+
+ /* Clear PLS[7:5] bits */
+ tmpreg &= ~ (uint32_t)PWR_CR_PLS;
+
+ /* Set PLS[7:5] bits according to PVDLevel value */
+ tmpreg |= sConfigPVD->PVDLevel;
+
+ /* Store the new value */
+ PWR->CR = tmpreg;
+
+ /* Configure the EXTI 16 interrupt */
+ if((sConfigPVD->Mode == PWR_MODE_IT_RISING_FALLING) ||\
+ (sConfigPVD->Mode == PWR_MODE_IT_FALLING) ||\
+ (sConfigPVD->Mode == PWR_MODE_IT_RISING))
+ {
+ __HAL_PVD_EXTI_ENABLE_IT(PWR_EXTI_LINE_PVD);
+ }
+ /* Configure the rising edge */
+ if((sConfigPVD->Mode == PWR_MODE_IT_RISING_FALLING) ||\
+ (sConfigPVD->Mode == PWR_MODE_IT_RISING))
+ {
+ EXTI->RTSR |= PWR_EXTI_LINE_PVD;
+ }
+ /* Configure the falling edge */
+ if((sConfigPVD->Mode == PWR_MODE_IT_RISING_FALLING) ||\
+ (sConfigPVD->Mode == PWR_MODE_IT_FALLING))
+ {
+ EXTI->FTSR |= PWR_EXTI_LINE_PVD;
+ }
+}
+
+/**
+ * @brief Enables the Power Voltage Detector(PVD).
+ * @param None
+ * @retval None
+ */
+void HAL_PWR_EnablePVD(void)
+{
+ *(__IO uint32_t *) CR_PVDE_BB = (uint32_t)ENABLE;
+}
+
+/**
+ * @brief Disables the Power Voltage Detector(PVD).
+ * @param None
+ * @retval None
+ */
+void HAL_PWR_DisablePVD(void)
+{
+ *(__IO uint32_t *) CR_PVDE_BB = (uint32_t)DISABLE;
+}
+
+/**
+ * @brief Enables the WakeUp PINx functionality.
+ * @param WakeUpPinx: Specifies the Power Wake-Up pin to enable
+ * This parameter can be one of the following values:
+ * @arg PWR_WAKEUP_PIN1
+ * @retval None
+ */
+void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx)
+{
+ /* Check the parameter */
+ assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx));
+ *(__IO uint32_t *) CSR_EWUP_BB = (uint32_t)ENABLE;
+}
+
+/**
+ * @brief Disables the WakeUp PINx functionality.
+ * @param WakeUpPinx: Specifies the Power Wake-Up pin to disable
+ * This parameter can be one of the following values:
+ * @arg PWR_WAKEUP_PIN1
+ * @retval None
+ */
+void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx)
+{
+ /* Check the parameter */
+ assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx));
+ *(__IO uint32_t *) CSR_EWUP_BB = (uint32_t)DISABLE;
+}
+
+/**
+ * @brief Enters Sleep mode.
+ *
+ * @note In Sleep mode, all I/O pins keep the same state as in Run mode.
+ *
+ * @note In Sleep mode, the systick is stopped to avoid exit from this mode with
+ * systick interrupt when used as time base for Timeout
+ *
+ * @param Regulator: Specifies the regulator state in SLEEP mode.
+ * This parameter can be one of the following values:
+ * @arg PWR_MAINREGULATOR_ON: SLEEP mode with regulator ON
+ * @arg PWR_LOWPOWERREGULATOR_ON: SLEEP mode with low power regulator ON
+ * @note This parameter is not used for the STM32F4 family and is kept as parameter
+ * just to maintain compatibility with the lower power families.
+ * @param SLEEPEntry: Specifies if SLEEP mode in entered with WFI or WFE instruction.
+ * This parameter can be one of the following values:
+ * @arg PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction
+ * @arg PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction
+ * @retval None
+ */
+void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry)
+{
+ /* Check the parameters */
+ assert_param(IS_PWR_REGULATOR(Regulator));
+ assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry));
+
+ /* Disable SysTick Timer */
+ SysTick->CTRL &= 0xFE;
+
+ /* Select SLEEP mode entry -------------------------------------------------*/
+ if(SLEEPEntry == PWR_SLEEPENTRY_WFI)
+ {
+ /* Request Wait For Interrupt */
+ __WFI();
+ }
+ else
+ {
+ /* Request Wait For Event */
+ __WFE();
+ }
+
+ /* Enable SysTick Timer */
+ SysTick->CTRL |= 0x01;
+}
+
+/**
+ * @brief Enters Stop mode.
+ * @note In Stop mode, all I/O pins keep the same state as in Run mode.
+ * @note When exiting Stop mode by issuing an interrupt or a wakeup event,
+ * the HSI RC oscillator is selected as system clock.
+ * @note When the voltage regulator operates in low power mode, an additional
+ * startup delay is incurred when waking up from Stop mode.
+ * By keeping the internal regulator ON during Stop mode, the consumption
+ * is higher although the startup time is reduced.
+ * @param Regulator: Specifies the regulator state in Stop mode.
+ * This parameter can be one of the following values:
+ * @arg PWR_MAINREGULATOR_ON: Stop mode with regulator ON
+ * @arg PWR_LOWPOWERREGULATOR_ON: Stop mode with low power regulator ON
+ * @param STOPEntry: Specifies if Stop mode in entered with WFI or WFE instruction.
+ * This parameter can be one of the following values:
+ * @arg PWR_STOPENTRY_WFI: Enter Stop mode with WFI instruction
+ * @arg PWR_STOPENTRY_WFE: Enter Stop mode with WFE instruction
+ * @retval None
+ */
+void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_PWR_REGULATOR(Regulator));
+ assert_param(IS_PWR_STOP_ENTRY(STOPEntry));
+
+ /* Select the regulator state in Stop mode ---------------------------------*/
+ tmpreg = PWR->CR;
+ /* Clear PDDS and LPDS bits */
+ tmpreg &= (uint32_t)~(PWR_CR_PDDS | PWR_CR_LPDS);
+
+ /* Set LPDS, MRLVDS and LPLVDS bits according to Regulator value */
+ tmpreg |= Regulator;
+
+ /* Store the new value */
+ PWR->CR = tmpreg;
+
+ /* Set SLEEPDEEP bit of Cortex System Control Register */
+ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
+
+ /* Select Stop mode entry --------------------------------------------------*/
+ if(STOPEntry == PWR_STOPENTRY_WFI)
+ {
+ /* Request Wait For Interrupt */
+ __WFI();
+ }
+ else
+ {
+ /* Request Wait For Event */
+ __WFE();
+ }
+ /* Reset SLEEPDEEP bit of Cortex System Control Register */
+ SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk);
+}
+
+/**
+ * @brief Enters Standby mode.
+ * @note In Standby mode, all I/O pins are high impedance except for:
+ * - Reset pad (still available)
+ * - RTC_AF1 pin (PC13) if configured for tamper, time-stamp, RTC
+ * Alarm out, or RTC clock calibration out.
+ * - RTC_AF2 pin (PI8) if configured for tamper or time-stamp.
+ * - WKUP pin 1 (PA0) if enabled.
+ * @param None
+ * @retval None
+ */
+void HAL_PWR_EnterSTANDBYMode(void)
+{
+ /* Clear Wakeup flag */
+ PWR->CR |= PWR_CR_CWUF;
+
+ /* Select Standby mode */
+ PWR->CR |= PWR_CR_PDDS;
+
+ /* Set SLEEPDEEP bit of Cortex System Control Register */
+ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
+
+ /* This option is used to ensure that store operations are completed */
+#if defined ( __CC_ARM)
+ __force_stores();
+#endif
+ /* Request Wait For Interrupt */
+ __WFI();
+}
+
+/**
+ * @brief This function handles the PWR PVD interrupt request.
+ * @note This API should be called under the PVD_IRQHandler().
+ * @param None
+ * @retval None
+ */
+void HAL_PWR_PVD_IRQHandler(void)
+{
+ /* Check PWR exti flag */
+ if(__HAL_PVD_EXTI_GET_FLAG(PWR_EXTI_LINE_PVD) != RESET)
+ {
+ /* PWR PVD interrupt user callback */
+ HAL_PWR_PVDCallback();
+
+ /* Clear PWR Exti pending bit */
+ __HAL_PVD_EXTI_CLEAR_FLAG(PWR_EXTI_LINE_PVD);
+ }
+}
+
+/**
+ * @brief PWR PVD interrupt callback
+ * @param none
+ * @retval none
+ */
+__weak void HAL_PWR_PVDCallback(void)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_PWR_PVDCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_PWR_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr_ex.c
new file mode 100644
index 0000000..36556ce
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr_ex.c
@@ -0,0 +1,329 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_pwr_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief Extended PWR HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of PWR extension peripheral:
+ * + Peripheral Extended features functions
+ *
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup PWREx
+ * @brief PWR HAL module driver
+ * @{
+ */
+
+#ifdef HAL_PWR_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define PWR_OVERDRIVE_TIMEOUT_VALUE 1000
+#define PWR_BKPREG_TIMEOUT_VALUE 1000
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup PWREx_Private_Functions
+ * @{
+ */
+
+/** @defgroup PWREx_Group1 Peripheral Extended features functions
+ * @brief Peripheral Extended features functions
+ *
+@verbatim
+
+ ===============================================================================
+ ##### Peripheral extended features functions #####
+ ===============================================================================
+
+ *** Main and Backup Regulators configuration ***
+ ================================================
+ [..]
+ (+) The backup domain includes 4 Kbytes of backup SRAM accessible only from
+ the CPU, and address in 32-bit, 16-bit or 8-bit mode. Its content is
+ retained even in Standby or VBAT mode when the low power backup regulator
+ is enabled. It can be considered as an internal EEPROM when VBAT is
+ always present. You can use the HAL_PWR_EnableBkUpReg() function to
+ enable the low power backup regulator.
+
+ (+) When the backup domain is supplied by VDD (analog switch connected to VDD)
+ the backup SRAM is powered from VDD which replaces the VBAT power supply to
+ save battery life.
+
+ (+) The backup SRAM is not mass erased by a tamper event. It is read
+ protected to prevent confidential data, such as cryptographic private
+ key, from being accessed. The backup SRAM can be erased only through
+ the Flash interface when a protection level change from level 1 to
+ level 0 is requested.
+ -@- Refer to the description of Read protection (RDP) in the Flash
+ programming manual.
+
+ (+) The main internal regulator can be configured to have a tradeoff between
+ performance and power consumption when the device does not operate at
+ the maximum frequency. This is done through __HAL_PWR_MAINREGULATORMODE_CONFIG()
+ macro which configure VOS bit in PWR_CR register
+
+ Refer to the product datasheets for more details.
+
+ *** FLASH Power Down configuration ****
+ =======================================
+ [..]
+ (+) By setting the FPDS bit in the PWR_CR register by using the
+ HAL_PWR_EnableFlashPowerDown() function, the Flash memory also enters power
+ down mode when the device enters Stop mode. When the Flash memory
+ is in power down mode, an additional startup delay is incurred when
+ waking up from Stop mode.
+
+ (+) For STM32F42xxx/43xxx Devices, the scale can be modified only when the PLL
+ is OFF and the HSI or HSE clock source is selected as system clock.
+ The new value programmed is active only when the PLL is ON.
+ When the PLL is OFF, the voltage scale 3 is automatically selected.
+ Refer to the datasheets for more details.
+
+ *** Over-Drive and Under-Drive configuration ****
+ =================================================
+ [..]
+ (+) For STM32F42xxx/43xxx Devices, in Run mode: the main regulator has
+ 2 operating modes available:
+ (++) Normal mode: The CPU and core logic operate at maximum frequency at a given
+ voltage scaling (scale 1, scale 2 or scale 3)
+ (++) Over-drive mode: This mode allows the CPU and the core logic to operate at a
+ higher frequency than the normal mode for a given voltage scaling (scale 1,
+ scale 2 or scale 3). This mode is enabled through HAL_PWREx_EnableOverDrive() function and
+ disabled by HAL_PWREx_DisableOverDrive() function, to enter or exit from Over-drive mode please follow
+ the sequence described in Reference manual.
+
+ (+) For STM32F42xxx/43xxx Devices, in Stop mode: the main regulator or low power regulator
+ supplies a low power voltage to the 1.2V domain, thus preserving the content of registers
+ and internal SRAM. 2 operating modes are available:
+ (++) Normal mode: the 1.2V domain is preserved in nominal leakage mode. This mode is only
+ available when the main regulator or the low power regulator is used in Scale 3 or
+ low voltage mode.
+ (++) Under-drive mode: the 1.2V domain is preserved in reduced leakage mode. This mode is only
+ available when the main regulator or the low power regulator is in low voltage mode.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables the Backup Regulator.
+ * @param None
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PWREx_EnableBkUpReg(void)
+{
+ uint32_t timeout = 0;
+
+ *(__IO uint32_t *) CSR_BRE_BB = (uint32_t)ENABLE;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + PWR_BKPREG_TIMEOUT_VALUE;
+ /* Wait till Backup regulator ready flag is set */
+ while(__HAL_PWR_GET_FLAG(PWR_FLAG_BRR) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables the Backup Regulator.
+ * @param None
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_PWREx_DisableBkUpReg(void)
+{
+ uint32_t timeout = 0;
+
+ *(__IO uint32_t *) CSR_BRE_BB = (uint32_t)DISABLE;
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + PWR_BKPREG_TIMEOUT_VALUE;
+ /* Wait till Backup regulator ready flag is set */
+ while(__HAL_PWR_GET_FLAG(PWR_FLAG_BRR) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Enables the Flash Power Down in Stop mode.
+ * @param None
+ * @retval None
+ */
+void HAL_PWREx_EnableFlashPowerDown(void)
+{
+ *(__IO uint32_t *) CR_FPDS_BB = (uint32_t)ENABLE;
+}
+
+/**
+ * @brief Disables the Flash Power Down in Stop mode.
+ * @param None
+ * @retval None
+ */
+void HAL_PWREx_DisableFlashPowerDown(void)
+{
+ *(__IO uint32_t *) CR_FPDS_BB = (uint32_t)DISABLE;
+}
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+/**
+ * @brief Activates the Over-Drive mode.
+ * @note These macros can be used only for STM32F42xx/STM32F43xx devices.
+ * This mode allows the CPU and the core logic to operate at a higher frequency
+ * than the normal mode for a given voltage scaling (scale 1, scale 2 or scale 3).
+ * @note It is recommended to enter or exit Over-drive mode when the application is not running
+ * critical tasks and when the system clock source is either HSI or HSE.
+ * During the Over-drive switch activation, no peripheral clocks should be enabled.
+ * The peripheral clocks must be enabled once the Over-drive mode is activated.
+ * @param None
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PWREx_ActivateOverDrive(void)
+{
+ uint32_t timeout = 0;
+
+ __PWR_CLK_ENABLE();
+
+ /* Enable the Over-drive to extend the clock frequency to 180 Mhz */
+ __HAL_PWR_OVERDRIVE_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + PWR_OVERDRIVE_TIMEOUT_VALUE;
+ while(!__HAL_PWR_GET_FLAG(PWR_FLAG_ODRDY))
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Enable the Over-drive switch */
+ __HAL_PWR_OVERDRIVESWITCHING_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + PWR_OVERDRIVE_TIMEOUT_VALUE;
+ while(!__HAL_PWR_GET_FLAG(PWR_FLAG_ODSWRDY))
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Deactivates the Over-Drive mode.
+ * @note These macros can be used only for STM32F42xx/STM32F43xx devices.
+ * This mode allows the CPU and the core logic to operate at a higher frequency
+ * than the normal mode for a given voltage scaling (scale 1, scale 2 or scale 3).
+ * @note It is recommended to enter or exit Over-drive mode when the application is not running
+ * critical tasks and when the system clock source is either HSI or HSE.
+ * During the Over-drive switch activation, no peripheral clocks should be enabled.
+ * The peripheral clocks must be enabled once the Over-drive mode is activated.
+ * @param None
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_PWREx_DeactivateOverDrive(void)
+{
+ uint32_t timeout = 0;
+
+ __PWR_CLK_ENABLE();
+
+ /* Disable the Over-drive switch */
+ __HAL_PWR_OVERDRIVESWITCHING_DISABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + PWR_OVERDRIVE_TIMEOUT_VALUE;
+
+ while(__HAL_PWR_GET_FLAG(PWR_FLAG_ODSWRDY))
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Disable the Over-drive */
+ __HAL_PWR_OVERDRIVE_DISABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + PWR_OVERDRIVE_TIMEOUT_VALUE;
+
+ while(__HAL_PWR_GET_FLAG(PWR_FLAG_ODRDY))
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ return HAL_OK;
+}
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_PWR_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc.c
new file mode 100644
index 0000000..a1e82d3
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc.c
@@ -0,0 +1,1248 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_rcc.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief RCC HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Reset and Clock Control (RCC) peripheral:
+ * + Initialization and de-initialization functions
+ * + Peripheral Control functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### RCC specific features #####
+ ==============================================================================
+ [..]
+ After reset the device is running from Internal High Speed oscillator
+ (HSI 16MHz) with Flash 0 wait state, Flash prefetch buffer, D-Cache
+ and I-Cache are disabled, and all peripherals are off except internal
+ SRAM, Flash and JTAG.
+ (+) There is no prescaler on High speed (AHB) and Low speed (APB) busses;
+ all peripherals mapped on these busses are running at HSI speed.
+ (+) The clock for all peripherals is switched off, except the SRAM and FLASH.
+ (+) All GPIOs are in input floating state, except the JTAG pins which
+ are assigned to be used for debug purpose.
+
+ [..]
+ Once the device started from reset, the user application has to:
+ (+) Configure the clock source to be used to drive the System clock
+ (if the application needs higher frequency/performance)
+ (+) Configure the System clock frequency and Flash settings
+ (+) Configure the AHB and APB busses prescalers
+ (+) Enable the clock for the peripheral(s) to be used
+ (+) Configure the clock source(s) for peripherals which clocks are not
+ derived from the System clock (I2S, RTC, ADC, USB OTG FS/SDIO/RNG)
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup RCC
+ * @brief RCC HAL module driver
+ * @{
+ */
+
+#ifdef HAL_RCC_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT
+#define HSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */
+#define LSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */
+#define PLL_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */
+#define CLOCKSWITCH_TIMEOUT_VALUE ((uint32_t)5000) /* 5 s */
+
+/* Private macro -------------------------------------------------------------*/
+#define __MCO1_CLK_ENABLE() __GPIOA_CLK_ENABLE()
+#define MCO1_GPIO_PORT GPIOA
+#define MCO1_PIN GPIO_PIN_8
+
+#define __MCO2_CLK_ENABLE() __GPIOC_CLK_ENABLE()
+#define MCO2_GPIO_PORT GPIOC
+#define MCO2_PIN GPIO_PIN_9
+
+/* Private variables ---------------------------------------------------------*/
+const uint8_t APBAHBPrescTable[16] = {0, 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 4, 6, 7, 8, 9};
+
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup RCC_Private_Functions
+ * @{
+ */
+
+/** @defgroup RCC_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..]
+ This section provide functions allowing to configure the internal/external oscillators
+ (HSE, HSI, LSE, LSI, PLL, CSS and MCO) and the System busses clocks (SYSCLK, AHB, APB1
+ and APB2).
+
+ [..] Internal/external clock and PLL configuration
+ (#) HSI (high-speed internal), 16 MHz factory-trimmed RC used directly or through
+ the PLL as System clock source.
+
+ (#) LSI (low-speed internal), 32 KHz low consumption RC used as IWDG and/or RTC
+ clock source.
+
+ (#) HSE (high-speed external), 4 to 26 MHz crystal oscillator used directly or
+ through the PLL as System clock source. Can be used also as RTC clock source.
+
+ (#) LSE (low-speed external), 32 KHz oscillator used as RTC clock source.
+
+ (#) PLL (clocked by HSI or HSE), featuring two different output clocks:
+ (++) The first output is used to generate the high speed system clock (up to 168 MHz)
+ (++) The second output is used to generate the clock for the USB OTG FS (48 MHz),
+ the random analog generator (<=48 MHz) and the SDIO (<= 48 MHz).
+
+ (#) CSS (Clock security system), once enable using the macro __HAL_RCC_CSS_ENABLE()
+ and if a HSE clock failure occurs(HSE used directly or through PLL as System
+ clock source), the System clockis automatically switched to HSI and an interrupt
+ is generated if enabled. The interrupt is linked to the Cortex-M4 NMI
+ (Non-Maskable Interrupt) exception vector.
+
+ (#) MCO1 (microcontroller clock output), used to output HSI, LSE, HSE or PLL
+ clock (through a configurable prescaler) on PA8 pin.
+
+ (#) MCO2 (microcontroller clock output), used to output HSE, PLL, SYSCLK or PLLI2S
+ clock (through a configurable prescaler) on PC9 pin.
+
+ [..] System, AHB and APB busses clocks configuration
+ (#) Several clock sources can be used to drive the System clock (SYSCLK): HSI,
+ HSE and PLL.
+ The AHB clock (HCLK) is derived from System clock through configurable
+ prescaler and used to clock the CPU, memory and peripherals mapped
+ on AHB bus (DMA, GPIO...). APB1 (PCLK1) and APB2 (PCLK2) clocks are derived
+ from AHB clock through configurable prescalers and used to clock
+ the peripherals mapped on these busses. You can use
+ "HAL_RCC_GetSysClockFreq()" function to retrieve the frequencies of these clocks.
+
+ -@- All the peripheral clocks are derived from the System clock (SYSCLK) except:
+ (+@) I2S: the I2S clock can be derived either from a specific PLL (PLLI2S) or
+ from an external clock mapped on the I2S_CKIN pin.
+ You have to use __HAL_RCC_PLLI2S_CONFIG() macro to configure this clock.
+ (+@) SAI: the SAI clock can be derived either from a specific PLL (PLLI2S) or (PLLSAI) or
+ from an external clock mapped on the I2S_CKIN pin.
+ You have to use __HAL_RCC_PLLI2S_CONFIG() macro to configure this clock.
+ (+@) RTC: the RTC clock can be derived either from the LSI, LSE or HSE clock
+ divided by 2 to 31. You have to use __HAL_RCC_RTC_CONFIG() and __HAL_RCC_RTC_ENABLE()
+ macros to configure this clock.
+ (+@) USB OTG FS, SDIO and RTC: USB OTG FS require a frequency equal to 48 MHz
+ to work correctly, while the SDIO require a frequency equal or lower than
+ to 48. This clock is derived of the main PLL through PLLQ divider.
+ (+@) IWDG clock which is always the LSI clock.
+
+ (#) For the STM32F405xx/07xx and STM32F415xx/17xx devices, the maximum
+ frequency of the SYSCLK and HCLK is 168 MHz, PCLK2 84 MHz and PCLK1 42 MHz.
+ Depending on the device voltage range, the maximum frequency should
+ be adapted accordingly:
+ +-------------------------------------------------------------------------------------+
+ | Latency | HCLK clock frequency (MHz) |
+ | |---------------------------------------------------------------------|
+ | | voltage range | voltage range | voltage range | voltage range |
+ | | 2.7 V - 3.6 V | 2.4 V - 2.7 V | 2.1 V - 2.4 V | 1.8 V - 2.1 V |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |0WS(1CPU cycle)|0 < HCLK <= 30 |0 < HCLK <= 24 |0 < HCLK <= 22 |0 < HCLK <= 20 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |1WS(2CPU cycle)|30 < HCLK <= 60 |24 < HCLK <= 48 |22 < HCLK <= 44 |20 < HCLK <= 40 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |2WS(3CPU cycle)|60 < HCLK <= 90 |48 < HCLK <= 72 |44 < HCLK <= 66 |40 < HCLK <= 60 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |3WS(4CPU cycle)|90 < HCLK <= 120|72 < HCLK <= 96 |66 < HCLK <= 88 |60 < HCLK <= 80 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |4WS(5CPU cycle)|120< HCLK <= 150|96 < HCLK <= 120|88 < HCLK <= 110 |80 < HCLK <= 100 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |5WS(6CPU cycle)|150< HCLK <= 168|120< HCLK <= 144|110 < HCLK <= 132|100 < HCLK <= 120|
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |6WS(7CPU cycle)| NA |144< HCLK <= 168|132 < HCLK <= 154|120 < HCLK <= 140|
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |7WS(8CPU cycle)| NA | NA |154 < HCLK <= 168|140 < HCLK <= 160|
+ +-------------------------------------------------------------------------------------+
+ (#) For the STM32F42xxx and STM32F43xxx devices, the maximum frequency
+ of the SYSCLK and HCLK is 180 MHz, PCLK2 90 MHz and PCLK1 45 MHz.
+ Depending on the device voltage range, the maximum frequency should
+ be adapted accordingly:
+ +-------------------------------------------------------------------------------------+
+ | Latency | HCLK clock frequency (MHz) |
+ | |---------------------------------------------------------------------|
+ | | voltage range | voltage range | voltage range | voltage range |
+ | | 2.7 V - 3.6 V | 2.4 V - 2.7 V | 2.1 V - 2.4 V | 1.8 V - 2.1 V |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |0WS(1CPU cycle)|0 < HCLK <= 30 |0 < HCLK <= 24 |0 < HCLK <= 22 |0 < HCLK <= 20 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |1WS(2CPU cycle)|30 < HCLK <= 60 |24 < HCLK <= 48 |22 < HCLK <= 44 |20 < HCLK <= 40 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |2WS(3CPU cycle)|60 < HCLK <= 90 |48 < HCLK <= 72 |44 < HCLK <= 66 |40 < HCLK <= 60 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |3WS(4CPU cycle)|90 < HCLK <= 120|72 < HCLK <= 96 |66 < HCLK <= 88 |60 < HCLK <= 80 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |4WS(5CPU cycle)|120< HCLK <= 150|96 < HCLK <= 120|88 < HCLK <= 110 |80 < HCLK <= 100 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |5WS(6CPU cycle)|150< HCLK <= 180|120< HCLK <= 144|110 < HCLK <= 132|100 < HCLK <= 120|
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |6WS(7CPU cycle)| NA |144< HCLK <= 168|132 < HCLK <= 154|120 < HCLK <= 140|
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |7WS(8CPU cycle)| NA |168< HCLK <= 180|154 < HCLK <= 176|140 < HCLK <= 160|
+ |-------------------------------------------------------------------------------------|
+ |8WS(9CPU cycle)| NA | NA |176 < HCLK <= 180|160 < HCLK <= 180|
+ +-------------------------------------------------------------------------------------+
+ (#) For the STM32F401xx, the maximum frequency of the SYSCLK and HCLK is 84 MHz,
+ PCLK2 84 MHz and PCLK1 42 MHz.
+ Depending on the device voltage range, the maximum frequency should
+ be adapted accordingly:
+ +-------------------------------------------------------------------------------------+
+ | Latency | HCLK clock frequency (MHz) |
+ | |---------------------------------------------------------------------|
+ | | voltage range | voltage range | voltage range | voltage range |
+ | | 2.7 V - 3.6 V | 2.4 V - 2.7 V | 2.1 V - 2.4 V | 1.8 V - 2.1 V |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |0WS(1CPU cycle)|0 < HCLK <= 30 |0 < HCLK <= 24 |0 < HCLK <= 22 |0 < HCLK <= 20 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |1WS(2CPU cycle)|30 < HCLK <= 60 |24 < HCLK <= 48 |22 < HCLK <= 44 |20 < HCLK <= 40 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |2WS(3CPU cycle)|60 < HCLK <= 84 |48 < HCLK <= 72 |44 < HCLK <= 66 |40 < HCLK <= 60 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |3WS(4CPU cycle)| NA |72 < HCLK <= 84 |66 < HCLK <= 84 |60 < HCLK <= 80 |
+ |---------------|----------------|----------------|-----------------|-----------------|
+ |4WS(5CPU cycle)| NA | NA | NA |80 < HCLK <= 84 |
+ +-------------------------------------------------------------------------------------+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Resets the RCC clock configuration to the default reset state.
+ * @note The default reset state of the clock configuration is given below:
+ * - HSI ON and used as system clock source
+ * - HSE, PLL and PLLI2S OFF
+ * - AHB, APB1 and APB2 prescaler set to 1.
+ * - CSS, MCO1 and MCO2 OFF
+ * - All interrupts disabled
+ * @note This function doesn't modify the configuration of the
+ * - Peripheral clocks
+ * - LSI, LSE and RTC clocks
+ * @param None
+ * @retval None
+ */
+void HAL_RCC_DeInit(void)
+{
+ /* Set HSION bit */
+ SET_BIT(RCC->CR, RCC_CR_HSION | RCC_CR_HSITRIM_4);
+
+ /* Reset CFGR register */
+ CLEAR_REG(RCC->CFGR);
+
+ /* Reset HSEON, CSSON, PLLON, PLLI2S */
+ CLEAR_BIT(RCC->CR, RCC_CR_HSEON | RCC_CR_CSSON | RCC_CR_PLLON| RCC_CR_PLLI2SON);
+
+ /* Reset PLLCFGR register */
+ CLEAR_REG(RCC->PLLCFGR);
+ SET_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLM_4 | RCC_PLLCFGR_PLLN_6 | RCC_PLLCFGR_PLLN_7 | RCC_PLLCFGR_PLLQ_2);
+
+ /* Reset PLLI2SCFGR register */
+ CLEAR_REG(RCC->PLLI2SCFGR);
+ SET_BIT(RCC->PLLI2SCFGR, RCC_PLLI2SCFGR_PLLI2SN_6 | RCC_PLLI2SCFGR_PLLI2SN_7 | RCC_PLLI2SCFGR_PLLI2SR_1);
+
+ /* Reset HSEBYP bit */
+ CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP);
+
+ /* Disable all interrupts */
+ CLEAR_REG(RCC->CIR);
+}
+
+/**
+ * @brief Initializes the RCC Oscillators according to the specified parameters in the
+ * RCC_OscInitTypeDef.
+ * @param RCC_OscInitStruct: pointer to an RCC_OscInitTypeDef structure that
+ * contains the configuration information for the RCC Oscillators.
+ * @note The PLL is not disabled when used as system clock.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
+{
+
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RCC_OSCILLATORTYPE(RCC_OscInitStruct->OscillatorType));
+ /*------------------------------- HSE Configuration ------------------------*/
+ if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE)
+ {
+ /* Check the parameters */
+ assert_param(IS_RCC_HSE(RCC_OscInitStruct->HSEState));
+ /* When the HSE is used as system clock or clock source for PLL in these cases HSE will not disabled */
+ if((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSE) || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLL) && ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLCFGR_PLLSRC_HSE)))
+ {
+ if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) && (RCC_OscInitStruct->HSEState != RCC_HSE_ON))
+ {
+ return HAL_ERROR;
+ }
+ }
+ else
+ {
+ /* Reset HSEON and HSEBYP bits before configuring the HSE --------------*/
+ __HAL_RCC_HSE_CONFIG(RCC_HSE_OFF);
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + HSE_TIMEOUT_VALUE;
+
+ /* Wait till HSE is disabled */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Set the new HSE configuration ---------------------------------------*/
+ __HAL_RCC_HSE_CONFIG(RCC_OscInitStruct->HSEState);
+
+ /* Check the HSE State */
+ if((RCC_OscInitStruct->HSEState) == RCC_HSE_ON)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + HSE_TIMEOUT_VALUE;
+
+ /* Wait till HSE is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ else
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + HSE_TIMEOUT_VALUE;
+
+ /* Wait till HSE is bypassed or disabled */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ }
+ /*----------------------------- HSI Configuration --------------------------*/
+ if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI)
+ {
+ /* Check the parameters */
+ assert_param(IS_RCC_HSI(RCC_OscInitStruct->HSIState));
+ assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue));
+
+ /* When the HSI is used as system clock it will not disabled */
+ if((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSI) || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLL) && ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLCFGR_PLLSRC_HSI)))
+ {
+ if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON))
+ {
+ return HAL_ERROR;
+ }
+ }
+ else
+ {
+ /* Check the HSI State */
+ if((RCC_OscInitStruct->HSIState)!= RCC_HSI_OFF)
+ {
+ /* Enable the Internal High Speed oscillator (HSI). */
+ __HAL_RCC_HSI_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + HSI_TIMEOUT_VALUE;
+
+ /* Wait till HSI is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Adjusts the Internal High Speed oscillator (HSI) calibration value.*/
+ __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->HSICalibrationValue);
+ }
+ else
+ {
+ /* Disable the Internal High Speed oscillator (HSI). */
+ __HAL_RCC_HSI_DISABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + HSI_TIMEOUT_VALUE;
+
+ /* Wait till HSI is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ }
+ /*------------------------------ LSI Configuration -------------------------*/
+ if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI)
+ {
+ /* Check the parameters */
+ assert_param(IS_RCC_LSI(RCC_OscInitStruct->LSIState));
+
+ /* Check the LSI State */
+ if((RCC_OscInitStruct->LSIState)!= RCC_LSI_OFF)
+ {
+ /* Enable the Internal Low Speed oscillator (LSI). */
+ __HAL_RCC_LSI_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + LSI_TIMEOUT_VALUE;
+
+ /* Wait till LSI is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ else
+ {
+ /* Disable the Internal Low Speed oscillator (LSI). */
+ __HAL_RCC_LSI_DISABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + LSI_TIMEOUT_VALUE;
+
+ /* Wait till LSI is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ /*------------------------------ LSE Configuration -------------------------*/
+ if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE)
+ {
+ /* Check the parameters */
+ assert_param(IS_RCC_LSE(RCC_OscInitStruct->LSEState));
+
+ /* Enable Power Clock*/
+ __PWR_CLK_ENABLE();
+
+ /* Enable write access to Backup domain */
+ PWR->CR |= PWR_CR_DBP;
+
+ /* Wait for Backup domain Write protection disable */
+ timeout = HAL_GetTick() + DBP_TIMEOUT_VALUE;
+
+ while((PWR->CR & PWR_CR_DBP) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Reset LSEON and LSEBYP bits before configuring the LSE ----------------*/
+ __HAL_RCC_LSE_CONFIG(RCC_LSE_OFF);
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + LSE_TIMEOUT_VALUE;
+
+ /* Wait till LSE is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Set the new LSE configuration -----------------------------------------*/
+ __HAL_RCC_LSE_CONFIG(RCC_OscInitStruct->LSEState);
+ /* Check the LSE State */
+ if((RCC_OscInitStruct->LSEState) == RCC_LSE_ON)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + LSE_TIMEOUT_VALUE;
+
+ /* Wait till LSE is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ else
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + LSE_TIMEOUT_VALUE;
+
+ /* Wait till LSE is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ /*-------------------------------- PLL Configuration -----------------------*/
+ /* Check the parameters */
+ assert_param(IS_RCC_PLL(RCC_OscInitStruct->PLL.PLLState));
+ if ((RCC_OscInitStruct->PLL.PLLState) != RCC_PLL_NONE)
+ {
+ /* Check if the PLL is used as system clock or not */
+ if(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL)
+ {
+ if((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON)
+ {
+ /* Check the parameters */
+ assert_param(IS_RCC_PLLSOURCE(RCC_OscInitStruct->PLL.PLLSource));
+ assert_param(IS_RCC_PLLM_VALUE(RCC_OscInitStruct->PLL.PLLM));
+ assert_param(IS_RCC_PLLN_VALUE(RCC_OscInitStruct->PLL.PLLN));
+ assert_param(IS_RCC_PLLP_VALUE(RCC_OscInitStruct->PLL.PLLP));
+ assert_param(IS_RCC_PLLQ_VALUE(RCC_OscInitStruct->PLL.PLLQ));
+
+ /* Disable the main PLL. */
+ __HAL_RCC_PLL_DISABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + PLL_TIMEOUT_VALUE;
+
+ /* Wait till PLL is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Configure the main PLL clock source, multiplication and division factors. */
+ __HAL_RCC_PLL_CONFIG(RCC_OscInitStruct->PLL.PLLSource,
+ RCC_OscInitStruct->PLL.PLLM,
+ RCC_OscInitStruct->PLL.PLLN,
+ RCC_OscInitStruct->PLL.PLLP,
+ RCC_OscInitStruct->PLL.PLLQ);
+ /* Enable the main PLL. */
+ __HAL_RCC_PLL_ENABLE();
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + PLL_TIMEOUT_VALUE;
+
+ /* Wait till PLL is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ else
+ {
+ /* Disable the main PLL. */
+ __HAL_RCC_PLL_DISABLE();
+ /* Get timeout */
+ timeout = HAL_GetTick() + PLL_TIMEOUT_VALUE;
+
+ /* Wait till PLL is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the CPU, AHB and APB busses clocks according to the specified
+ * parameters in the RCC_ClkInitStruct.
+ * @param RCC_ClkInitStruct: pointer to an RCC_OscInitTypeDef structure that
+ * contains the configuration information for the RCC peripheral.
+ * @param FLatency: FLASH Latency, this parameter depend on device selected
+ *
+ * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency
+ * and updated by HAL_RCC_GetHCLKFreq() function called within this function
+ *
+ * @note The HSI is used (enabled by hardware) as system clock source after
+ * startup from Reset, wake-up from STOP and STANDBY mode, or in case
+ * of failure of the HSE used directly or indirectly as system clock
+ * (if the Clock Security System CSS is enabled).
+ *
+ * @note A switch from one clock source to another occurs only if the target
+ * clock source is ready (clock stable after startup delay or PLL locked).
+ * If a clock source which is not yet ready is selected, the switch will
+ * occur when the clock source will be ready.
+ *
+ * @note Depending on the device voltage range, the software has to set correctly
+ * HPRE[3:0] bits to ensure that HCLK not exceed the maximum allowed frequency
+ * (for more details refer to section above "Initialization/de-initialization functions")
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency)
+{
+
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RCC_CLOCKTYPE(RCC_ClkInitStruct->ClockType));
+ assert_param(IS_FLASH_LATENCY(FLatency));
+
+ /* To correctly read data from FLASH memory, the number of wait states (LATENCY)
+ must be correctly programmed according to the frequency of the CPU clock
+ (HCLK) and the supply voltage of the device. */
+
+ /* Increasing the CPU frequency */
+ if(FLatency > (FLASH->ACR & FLASH_ACR_LATENCY))
+ {
+ /* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */
+ __HAL_FLASH_SET_LATENCY(FLatency);
+
+ /* Check that the new number of wait states is taken into account to access the Flash
+ memory by reading the FLASH_ACR register */
+ if((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency)
+ {
+ return HAL_ERROR;
+ }
+
+ /*------------------------- SYSCLK Configuration ---------------------------*/
+ if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK)
+ {
+ assert_param(IS_RCC_SYSCLKSOURCE(RCC_ClkInitStruct->SYSCLKSource));
+
+ /* HSE is selected as System Clock Source */
+ if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE)
+ {
+ /* Check the HSE ready flag */
+ if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET)
+ {
+ return HAL_ERROR;
+ }
+ }
+ /* PLL is selected as System Clock Source */
+ else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK)
+ {
+ /* Check the PLL ready flag */
+ if(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET)
+ {
+ return HAL_ERROR;
+ }
+ }
+ /* HSI is selected as System Clock Source */
+ else
+ {
+ /* Check the HSI ready flag */
+ if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET)
+ {
+ return HAL_ERROR;
+ }
+ }
+ MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_ClkInitStruct->SYSCLKSource);
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + CLOCKSWITCH_TIMEOUT_VALUE;
+
+ if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE)
+ {
+ while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_HSE)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK)
+ {
+ while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ else
+ {
+ while(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_HSI)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ }
+ /* Decreasing the CPU frequency */
+ else
+ {
+ /*------------------------- SYSCLK Configuration ---------------------------*/
+ if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK)
+ {
+ assert_param(IS_RCC_SYSCLKSOURCE(RCC_ClkInitStruct->SYSCLKSource));
+
+ /* HSE is selected as System Clock Source */
+ if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE)
+ {
+ /* Check the HSE ready flag */
+ if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET)
+ {
+ return HAL_ERROR;
+ }
+ }
+ /* PLL is selected as System Clock Source */
+ else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK)
+ {
+ /* Check the PLL ready flag */
+ if(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET)
+ {
+ return HAL_ERROR;
+ }
+ }
+ /* HSI is selected as System Clock Source */
+ else
+ {
+ /* Check the HSI ready flag */
+ if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET)
+ {
+ return HAL_ERROR;
+ }
+ }
+ MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_ClkInitStruct->SYSCLKSource);
+
+ /* Get timeout */
+ timeout = HAL_GetTick() + CLOCKSWITCH_TIMEOUT_VALUE;
+
+ if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE)
+ {
+ while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_HSE)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK)
+ {
+ while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ else
+ {
+ while(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_HSI)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+
+ /* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */
+ __HAL_FLASH_SET_LATENCY(FLatency);
+
+ /* Check that the new number of wait states is taken into account to access the Flash
+ memory by reading the FLASH_ACR register */
+ if((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency)
+ {
+ return HAL_ERROR;
+ }
+ }
+
+ /*-------------------------- HCLK Configuration ----------------------------*/
+ if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK)
+ {
+ assert_param(IS_RCC_HCLK(RCC_ClkInitStruct->AHBCLKDivider));
+ MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_ClkInitStruct->AHBCLKDivider);
+ }
+
+ /*-------------------------- PCLK1 Configuration ---------------------------*/
+ if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1)
+ {
+ assert_param(IS_RCC_PCLK(RCC_ClkInitStruct->APB1CLKDivider));
+ MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_ClkInitStruct->APB1CLKDivider);
+ }
+
+ /*-------------------------- PCLK2 Configuration ---------------------------*/
+ if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2)
+ {
+ assert_param(IS_RCC_PCLK(RCC_ClkInitStruct->APB2CLKDivider));
+ MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, ((RCC_ClkInitStruct->APB2CLKDivider) << 3));
+ }
+
+ /* Setup SysTick Timer for 1 msec interrupts.
+ ------------------------------------------
+ The SysTick_Config() function is a CMSIS function which configure:
+ - The SysTick Reload register with value passed as function parameter.
+ - Configure the SysTick IRQ priority to the lowest value (0x0F).
+ - Reset the SysTick Counter register.
+ - Configure the SysTick Counter clock source to be Core Clock Source (HCLK).
+ - Enable the SysTick Interrupt.
+ - Start the SysTick Counter.*/
+ SysTick_Config(HAL_RCC_GetHCLKFreq() / 1000);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup RCC_Group2 Peripheral Control functions
+ * @brief RCC clocks control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the RCC Clocks
+ frequencies.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Selects the clock source to output on MCO1 pin(PA8) or on MCO2 pin(PC9).
+ * @note PA8/PC9 should be configured in alternate function mode.
+ * @param RCC_MCOx: specifies the output direction for the clock source.
+ * This parameter can be one of the following values:
+ * @arg RCC_MCO1: Clock source to output on MCO1 pin(PA8).
+ * @arg RCC_MCO2: Clock source to output on MCO2 pin(PC9).
+ * @param RCC_MCOSource: specifies the clock source to output.
+ * This parameter can be one of the following values:
+ * @arg RCC_MCO1SOURCE_HSI: HSI clock selected as MCO1 source
+ * @arg RCC_MCO1SOURCE_LSE: LSE clock selected as MCO1 source
+ * @arg RCC_MCO1SOURCE_HSE: HSE clock selected as MCO1 source
+ * @arg RCC_MCO1SOURCE_PLLCLK: main PLL clock selected as MCO1 source
+ * @arg RCC_MCO2SOURCE_SYSCLK: System clock (SYSCLK) selected as MCO2 source
+ * @arg RCC_MCO2SOURCE_PLLI2SCLK: PLLI2S clock selected as MCO2 source
+ * @arg RCC_MCO2SOURCE_HSE: HSE clock selected as MCO2 source
+ * @arg RCC_MCO2SOURCE_PLLCLK: main PLL clock selected as MCO2 source
+ * @param RCC_MCODiv: specifies the MCOx prescaler.
+ * This parameter can be one of the following values:
+ * @arg RCC_MCODIV_1: no division applied to MCOx clock
+ * @arg RCC_MCODIV_2: division by 2 applied to MCOx clock
+ * @arg RCC_MCODIV_3: division by 3 applied to MCOx clock
+ * @arg RCC_MCODIV_4: division by 4 applied to MCOx clock
+ * @arg RCC_MCODIV_5: division by 5 applied to MCOx clock
+ * @retval None
+ */
+void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv)
+{
+ GPIO_InitTypeDef GPIO_InitStruct;
+ /* Check the parameters */
+ assert_param(IS_RCC_MCO(RCC_MCOx));
+ assert_param(IS_RCC_MCODIV(RCC_MCODiv));
+ /* RCC_MCO1 */
+ if(RCC_MCOx == RCC_MCO1)
+ {
+ assert_param(IS_RCC_MCO1SOURCE(RCC_MCOSource));
+
+ /* MCO1 Clock Enable */
+ __MCO1_CLK_ENABLE();
+
+ /* Configue the MCO1 pin in alternate function mode */
+ GPIO_InitStruct.Pin = MCO1_PIN;
+ GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
+ GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
+ GPIO_InitStruct.Pull = GPIO_NOPULL;
+ GPIO_InitStruct.Alternate = GPIO_AF0_MCO;
+ HAL_GPIO_Init(MCO1_GPIO_PORT, &GPIO_InitStruct);
+
+ /* Mask MCO1 and MCO1PRE[2:0] bits then Select MCO1 clock source and prescaler */
+ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO1 | RCC_CFGR_MCO1PRE), (RCC_MCOSource | RCC_MCODiv));
+ }
+ else
+ {
+ assert_param(IS_RCC_MCO2SOURCE(RCC_MCOSource));
+
+ /* MCO2 Clock Enable */
+ __MCO2_CLK_ENABLE();
+
+ /* Configue the MCO2 pin in alternate function mode */
+ GPIO_InitStruct.Pin = MCO2_PIN;
+ GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
+ GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
+ GPIO_InitStruct.Pull = GPIO_NOPULL;
+ GPIO_InitStruct.Alternate = GPIO_AF0_MCO;
+ HAL_GPIO_Init(MCO2_GPIO_PORT, &GPIO_InitStruct);
+
+ /* Mask MCO2 and MCO2PRE[2:0] bits then Select MCO2 clock source and prescaler */
+ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO2 | RCC_CFGR_MCO2PRE), (RCC_MCOSource | (RCC_MCODiv << 3)));
+ }
+}
+
+/**
+ * @brief Enables the Clock Security System.
+ * @note If a failure is detected on the HSE oscillator clock, this oscillator
+ * is automatically disabled and an interrupt is generated to inform the
+ * software about the failure (Clock Security System Interrupt, CSSI),
+ * allowing the MCU to perform rescue operations. The CSSI is linked to
+ * the Cortex-M4 NMI (Non-Maskable Interrupt) exception vector.
+ * @param None
+ * @retval None
+ */
+void HAL_RCC_EnableCSS(void)
+{
+ *(__IO uint32_t *) CR_CSSON_BB = (uint32_t)ENABLE;
+}
+
+/**
+ * @brief Disables the Clock Security System.
+ * @param None
+ * @retval None
+ */
+void HAL_RCC_DisableCSS(void)
+{
+ *(__IO uint32_t *) CR_CSSON_BB = (uint32_t)DISABLE;
+}
+
+/**
+ * @brief Returns the SYSCLK frequency
+ *
+ * @note The system frequency computed by this function is not the real
+ * frequency in the chip. It is calculated based on the predefined
+ * constant and the selected clock source:
+ * @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(*)
+ * @note If SYSCLK source is HSE, function returns values based on HSE_VALUE(**)
+ * @note If SYSCLK source is PLL, function returns values based on HSE_VALUE(**)
+ * or HSI_VALUE(*) multiplied/divided by the PLL factors.
+ * @note (*) HSI_VALUE is a constant defined in stm32f4xx_hal_conf.h file (default value
+ * 16 MHz) but the real value may vary depending on the variations
+ * in voltage and temperature.
+ * @note (**) HSE_VALUE is a constant defined in stm32f4xx_hal_conf.h file (default value
+ * 25 MHz), user has to ensure that HSE_VALUE is same as the real
+ * frequency of the crystal used. Otherwise, this function may
+ * have wrong result.
+ *
+ * @note The result of this function could be not correct when using fractional
+ * value for HSE crystal.
+ *
+ * @note This function can be used by the user application to compute the
+ * baudrate for the communication peripherals or configure other parameters.
+ *
+ * @note Each time SYSCLK changes, this function must be called to update the
+ * right SYSCLK value. Otherwise, any configuration based on this function will be incorrect.
+ *
+ *
+ * @param None
+ * @retval SYSCLK frequency
+ */
+uint32_t HAL_RCC_GetSysClockFreq(void)
+{
+ uint32_t pllm = 0, pllvco = 0, pllp = 0;
+ uint32_t sysclockfreq = 0;
+
+ /* Get SYSCLK source -------------------------------------------------------*/
+ switch (RCC->CFGR & RCC_CFGR_SWS)
+ {
+ case RCC_CFGR_SWS_HSI: /* HSI used as system clock source */
+ {
+ sysclockfreq = HSI_VALUE;
+ break;
+ }
+ case RCC_CFGR_SWS_HSE: /* HSE used as system clock source */
+ {
+ sysclockfreq = HSE_VALUE;
+ break;
+ }
+ case RCC_CFGR_SWS_PLL: /* PLL used as system clock source */
+ {
+ /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN
+ SYSCLK = PLL_VCO / PLLP */
+ pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM;
+ if (__RCC_PLLSRC() != 0)
+ {
+ /* HSE used as PLL clock source */
+ pllvco = ((HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> POSITION_VAL(RCC_PLLCFGR_PLLN)));
+ }
+ else
+ {
+ /* HSI used as PLL clock source */
+ pllvco = ((HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> POSITION_VAL(RCC_PLLCFGR_PLLN)));
+ }
+ pllp = ((((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >> POSITION_VAL(RCC_PLLCFGR_PLLP)) + 1 ) *2);
+
+ sysclockfreq = pllvco/pllp;
+ break;
+ }
+ default:
+ {
+ sysclockfreq = HSI_VALUE;
+ break;
+ }
+ }
+ return sysclockfreq;
+}
+
+/**
+ * @brief Returns the HCLK frequency
+ * @note Each time HCLK changes, this function must be called to update the
+ * right HCLK value. Otherwise, any configuration based on this function will be incorrect.
+ *
+ * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency
+ * and updated within this function
+ * @param None
+ * @retval HCLK frequency
+ */
+uint32_t HAL_RCC_GetHCLKFreq(void)
+{
+ SystemCoreClock = HAL_RCC_GetSysClockFreq() >> APBAHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE)>> POSITION_VAL(RCC_CFGR_HPRE)];
+ return SystemCoreClock;
+}
+
+/**
+ * @brief Returns the PCLK1 frequency
+ * @note Each time PCLK1 changes, this function must be called to update the
+ * right PCLK1 value. Otherwise, any configuration based on this function will be incorrect.
+ * @param None
+ * @retval PCLK1 frequency
+ */
+uint32_t HAL_RCC_GetPCLK1Freq(void)
+{
+ /* Get HCLK source and Compute PCLK1 frequency ---------------------------*/
+ return (HAL_RCC_GetHCLKFreq() >> APBAHBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE1)>> POSITION_VAL(RCC_CFGR_PPRE1)]);
+}
+
+/**
+ * @brief Returns the PCLK2 frequency
+ * @note Each time PCLK2 changes, this function must be called to update the
+ * right PCLK2 value. Otherwise, any configuration based on this function will be incorrect.
+ * @param None
+ * @retval PCLK2 frequency
+ */
+uint32_t HAL_RCC_GetPCLK2Freq(void)
+{
+ /* Get HCLK source and Compute PCLK2 frequency ---------------------------*/
+ return (HAL_RCC_GetHCLKFreq()>> APBAHBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE2)>> POSITION_VAL(RCC_CFGR_PPRE2)]);
+}
+
+/**
+ * @brief Configures the RCC_OscInitStruct according to the internal
+ * RCC configuration registers.
+ * @param RCC_OscInitStruct: pointer to an RCC_OscInitTypeDef structure that
+ * will be configured.
+ * @retval None
+ */
+void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
+{
+ /* Set all possible values for the Oscillator type parameter ---------------*/
+ RCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI;
+
+ /* Get the HSE configuration -----------------------------------------------*/
+ if((RCC->CR &RCC_CR_HSEBYP) == RCC_CR_HSEBYP)
+ {
+ RCC_OscInitStruct->HSEState = RCC_HSE_BYPASS;
+ }
+ else if((RCC->CR &RCC_CR_HSEON) == RCC_CR_HSEON)
+ {
+ RCC_OscInitStruct->HSEState = RCC_HSE_ON;
+ }
+ else
+ {
+ RCC_OscInitStruct->HSEState = RCC_HSE_OFF;
+ }
+
+ /* Get the HSI configuration -----------------------------------------------*/
+ if((RCC->CR &RCC_CR_HSION) == RCC_CR_HSION)
+ {
+ RCC_OscInitStruct->HSIState = RCC_HSI_ON;
+ }
+ else
+ {
+ RCC_OscInitStruct->HSIState = RCC_HSI_OFF;
+ }
+
+ RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->CR &RCC_CR_HSITRIM) >> POSITION_VAL(RCC_CR_HSITRIM));
+
+ /* Get the LSE configuration -----------------------------------------------*/
+ if((RCC->BDCR &RCC_BDCR_LSEBYP) == RCC_BDCR_LSEBYP)
+ {
+ RCC_OscInitStruct->LSEState = RCC_LSE_BYPASS;
+ }
+ else if((RCC->BDCR &RCC_BDCR_LSEON) == RCC_BDCR_LSEON)
+ {
+ RCC_OscInitStruct->LSEState = RCC_LSE_ON;
+ }
+ else
+ {
+ RCC_OscInitStruct->LSEState = RCC_LSE_OFF;
+ }
+
+ /* Get the LSI configuration -----------------------------------------------*/
+ if((RCC->CSR &RCC_CSR_LSION) == RCC_CSR_LSION)
+ {
+ RCC_OscInitStruct->LSIState = RCC_LSI_ON;
+ }
+ else
+ {
+ RCC_OscInitStruct->LSIState = RCC_LSI_OFF;
+ }
+
+ /* Get the PLL configuration -----------------------------------------------*/
+ if((RCC->CR &RCC_CR_PLLON) == RCC_CR_PLLON)
+ {
+ RCC_OscInitStruct->PLL.PLLState = RCC_PLL_ON;
+ }
+ else
+ {
+ RCC_OscInitStruct->PLL.PLLState = RCC_PLL_OFF;
+ }
+ RCC_OscInitStruct->PLL.PLLSource = (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC);
+ RCC_OscInitStruct->PLL.PLLM = (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM);
+ RCC_OscInitStruct->PLL.PLLN = (uint32_t)((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> POSITION_VAL(RCC_PLLCFGR_PLLN));
+ RCC_OscInitStruct->PLL.PLLP = (uint32_t)((((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) + RCC_PLLCFGR_PLLP_0) << 1) >> POSITION_VAL(RCC_PLLCFGR_PLLP));
+ RCC_OscInitStruct->PLL.PLLQ = (uint32_t)((RCC->PLLCFGR & RCC_PLLCFGR_PLLQ) >> POSITION_VAL(RCC_PLLCFGR_PLLQ));
+}
+
+/**
+ * @brief Configures the RCC_ClkInitStruct according to the internal
+ * RCC configuration registers.
+ * @param RCC_OscInitStruct: pointer to an RCC_ClkInitTypeDef structure that
+ * will be configured.
+ * @param pFLatency: Pointer on the Flash Latency.
+ * @retval None
+ */
+void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency)
+{
+ /* Set all possible values for the Clock type parameter --------------------*/
+ RCC_ClkInitStruct->ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
+
+ /* Get the SYSCLK configuration --------------------------------------------*/
+ RCC_ClkInitStruct->SYSCLKSource = (uint32_t)(RCC->CFGR & RCC_CFGR_SW);
+
+ /* Get the HCLK configuration ----------------------------------------------*/
+ RCC_ClkInitStruct->AHBCLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_HPRE);
+
+ /* Get the APB1 configuration ----------------------------------------------*/
+ RCC_ClkInitStruct->APB1CLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_PPRE1);
+
+ /* Get the APB2 configuration ----------------------------------------------*/
+ RCC_ClkInitStruct->APB2CLKDivider = (uint32_t)((RCC->CFGR & RCC_CFGR_PPRE2) >> 3);
+
+ /* Get the Flash Wait State (Latency) configuration ------------------------*/
+ *pFLatency = (uint32_t)(FLASH->ACR & FLASH_ACR_LATENCY);
+}
+
+/**
+ * @brief This function handles the RCC CSS interrupt request.
+ * @note This API should be called under the NMI_Handler().
+ * @param None
+ * @retval None
+ */
+void HAL_RCC_NMI_IRQHandler(void)
+{
+ /* Check RCC CSSF flag */
+ if(__HAL_RCC_GET_IT(RCC_IT_CSS))
+ {
+ /* RCC Clock Security System interrupt user callback */
+ HAL_RCC_CCSCallback();
+
+ /* Clear RCC CSS pending bit */
+ __HAL_RCC_CLEAR_IT(RCC_IT_CSS);
+ }
+}
+
+/**
+ * @brief RCC Clock Security System interrupt callback
+ * @param none
+ * @retval none
+ */
+__weak void HAL_RCC_CCSCallback(void)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RCC_CCSCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_RCC_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc_ex.c
new file mode 100644
index 0000000..c6808c3
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc_ex.c
@@ -0,0 +1,512 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_rcc_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief Extension RCC HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities RCC extension peripheral:
+ * + Extended Peripheral Control functions
+ *
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup RCC
+ * @brief RCC HAL module driver
+ * @{
+ */
+
+#ifdef HAL_RCC_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define PLLI2S_TIMEOUT_VALUE 100 /* Timeout value fixed to 100 ms */
+#define PLLSAI_TIMEOUT_VALUE 100 /* Timeout value fixed to 100 ms */
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup RCCEx_Private_Functions
+ * @{
+ */
+
+/** @defgroup RCCEx_Group1 Extended Peripheral Control functions
+ * @brief Extended Peripheral Control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Extended Peripheral Control functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the RCC Clocks
+ frequencies.
+ [..]
+ (@) Important note: Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to
+ select the RTC clock source; in this case the Backup domain will be reset in
+ order to modify the RTC Clock source, as consequence RTC registers (including
+ the backup registers) and RCC_BDCR register are set to their reset values.
+
+@endverbatim
+ * @{
+ */
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx)
+/**
+ * @brief Initializes the RCC extended peripherals clocks according to the specified
+ * parameters in the RCC_PeriphCLKInitTypeDef.
+ * @param PeriphClkInit: pointer to an RCC_PeriphCLKInitTypeDef structure that
+ * contains the configuration information for the Extended Peripherals
+ * clocks(I2S, SAI, LTDC RTC and TIM).
+ *
+ * @note Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select
+ * the RTC clock source; in this case the Backup domain will be reset in
+ * order to modify the RTC Clock source, as consequence RTC registers (including
+ * the backup registers) and RCC_BDCR register are set to their reset values.
+ *
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit)
+{
+ uint32_t timeout = 0;
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection));
+
+ /*----------------------- SAI/I2S Configuration (PLLI2S) -------------------------*/
+
+ /*----------------------- Common configuration SAI/I2S ---------------------------*/
+ /* In Case of SAI or I2S Clock Configuration through PLLI2S, PLLI2SN division
+ factor is common parameters for both peripherals */
+ if((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) ||
+ (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI_PLLI2S) == RCC_PERIPHCLK_SAI_PLLI2S))
+ {
+ /* check for Parameters */
+ assert_param(IS_RCC_PLLI2SN_VALUE(PeriphClkInit->PLLI2S.PLLI2SN));
+
+ /* Disable the PLLI2S */
+ __HAL_RCC_PLLI2S_DISABLE();
+ /* Get new Timeout value */
+ timeout = HAL_GetTick() + PLLI2S_TIMEOUT_VALUE;
+ /* Wait till PLLI2S is disabled */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* return in case of Timeout detected */
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /*---------------------------- I2S configuration -------------------------------*/
+ /* In Case of I2S Clock Configuration through PLLI2S, PLLI2SR must be added
+ only for I2S configuration */
+ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == (RCC_PERIPHCLK_I2S))
+ {
+ /* check for Parameters */
+ assert_param(IS_RCC_PLLI2SR_VALUE(PeriphClkInit->PLLI2S.PLLI2SR));
+ /* Configure the PLLI2S division factors */
+ /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) × (PLLI2SN/PLLM) */
+ /* I2SCLK = f(PLLI2S clock output) = f(VCO clock) / PLLI2SR */
+ __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN , PeriphClkInit->PLLI2S.PLLI2SR);
+ }
+
+ /*---------------------------- SAI configuration -------------------------------*/
+ /* In Case of SAI Clock Configuration through PLLI2S, PLLI2SQ and PLLI2S_DIVQ must
+ be added only for SAI configuration */
+ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI_PLLI2S) == (RCC_PERIPHCLK_SAI_PLLI2S))
+ {
+ /* Check the PLLI2S division factors */
+ assert_param(IS_RCC_PLLI2SQ_VALUE(PeriphClkInit->PLLI2S.PLLI2SQ));
+ assert_param(IS_RCC_PLLI2S_DIVQ_VALUE(PeriphClkInit->PLLI2SDivQ));
+
+ /* Read PLLI2SR value from PLLI2SCFGR register (this value is not need for SAI configuration) */
+ tmpreg = ((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SR));
+ /* Configure the PLLI2S division factors */
+ /* PLLI2S_VCO Input = PLL_SOURCE/PLLM */
+ /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */
+ /* SAI_CLK(first level) = PLLI2S_VCO Output/PLLI2SQ */
+ __HAL_RCC_PLLI2S_SAICLK_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN , PeriphClkInit->PLLI2S.PLLI2SQ , tmpreg);
+ /* SAI_CLK_x = SAI_CLK(first level)/PLLI2SDIVQ */
+ __HAL_RCC_PLLI2S_PLLSAICLKDIVQ_CONFIG(PeriphClkInit->PLLI2SDivQ);
+ }
+
+ /* Enable the PLLI2S */
+ __HAL_RCC_PLLI2S_ENABLE();
+ /* Get new Timeout value */
+ timeout = HAL_GetTick() + PLLI2S_TIMEOUT_VALUE;
+ /* Wait till PLLI2S is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* return in case of Timeout detected */
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /*----------------------- SAI/LTDC Configuration (PLLSAI) -------------------------*/
+
+ /*----------------------- Common configuration SAI/LTDC ---------------------------*/
+ /* In Case of SAI or LTDC Clock Configuration through PLLSAI, PLLSAIN division
+ factor is common parameters for both peripherals */
+ if((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI_PLLSAI) == RCC_PERIPHCLK_SAI_PLLSAI) ||
+ (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LTDC) == RCC_PERIPHCLK_LTDC))
+ {
+ /* Check the PLLSAI division factors */
+ assert_param(IS_RCC_PLLSAIN_VALUE(PeriphClkInit->PLLSAI.PLLSAIN));
+
+ /* Disable PLLSAI Clock */
+ __HAL_RCC_PLLSAI_DISABLE();
+ /* Get new Timeout value */
+ timeout = HAL_GetTick() + PLLSAI_TIMEOUT_VALUE;
+ /* Wait till PLLSAI is disabled */
+ while(__HAL_RCC_PLLSAI_GET_FLAG() != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* return in case of Timeout detected */
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /*---------------------------- SAI configuration -------------------------------*/
+ /* In Case of SAI Clock Configuration through PLLSAI, PLLSAIQ and PLLSAI_DIVQ must
+ be added only for SAI configuration */
+ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI_PLLSAI) == (RCC_PERIPHCLK_SAI_PLLSAI))
+ {
+ assert_param(IS_RCC_PLLSAIQ_VALUE(PeriphClkInit->PLLSAI.PLLSAIQ));
+ assert_param(IS_RCC_PLLSAI_DIVQ_VALUE(PeriphClkInit->PLLSAIDivQ));
+
+ /* Read PLLSAIR value from PLLSAICFGR register (this value is not need for SAI configuration) */
+ tmpreg = ((RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIR) >> POSITION_VAL(RCC_PLLSAICFGR_PLLSAIR));
+ /* PLLSAI_VCO Input = PLL_SOURCE/PLLM */
+ /* PLLSAI_VCO Output = PLLSAI_VCO Input * PLLSAIN */
+ /* SAI_CLK(first level) = PLLSAI_VCO Output/PLLSAIQ */
+ __HAL_RCC_PLLSAI_CONFIG(PeriphClkInit->PLLSAI.PLLSAIN , PeriphClkInit->PLLSAI.PLLSAIQ, tmpreg);
+ /* SAI_CLK_x = SAI_CLK(first level)/PLLSAIDIVQ */
+ __HAL_RCC_PLLSAI_PLLSAICLKDIVQ_CONFIG(PeriphClkInit->PLLSAIDivQ);
+ }
+
+ /*---------------------------- LTDC configuration -------------------------------*/
+ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LTDC) == (RCC_PERIPHCLK_LTDC))
+ {
+ assert_param(IS_RCC_PLLSAIR_VALUE(PeriphClkInit->PLLSAI.PLLSAIR));
+ assert_param(IS_RCC_PLLSAI_DIVR_VALUE(PeriphClkInit->PLLSAIDivR));
+
+ /* Read PLLSAIR value from PLLSAICFGR register (this value is not need for SAI configuration) */
+ tmpreg = ((RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIQ) >> POSITION_VAL(RCC_PLLSAICFGR_PLLSAIQ));
+ /* PLLSAI_VCO Input = PLL_SOURCE/PLLM */
+ /* PLLSAI_VCO Output = PLLSAI_VCO Input * PLLSAIN */
+ /* LTDC_CLK(first level) = PLLSAI_VCO Output/PLLSAIR */
+ __HAL_RCC_PLLSAI_CONFIG(PeriphClkInit->PLLSAI.PLLSAIN , tmpreg, PeriphClkInit->PLLSAI.PLLSAIR);
+ /* LTDC_CLK = LTDC_CLK(first level)/PLLSAIDIVR */
+ __HAL_RCC_PLLSAI_PLLSAICLKDIVR_CONFIG(PeriphClkInit->PLLSAIDivR);
+ }
+ /* Enable PLLSAI Clock */
+ __HAL_RCC_PLLSAI_ENABLE();
+ /* Get new Timeout value */
+ timeout = HAL_GetTick() + PLLSAI_TIMEOUT_VALUE;
+ /* Wait till PLLSAI is ready */
+ while(__HAL_RCC_PLLSAI_GET_FLAG() == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* return in case of Timeout detected */
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+
+ /*---------------------------- RTC configuration -------------------------------*/
+ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC))
+ {
+ /* Enable Power Clock*/
+ __PWR_CLK_ENABLE();
+
+ /* Enable write access to Backup domain */
+ PWR->CR |= PWR_CR_DBP;
+
+ /* Wait for Backup domain Write protection disable */
+ timeout = HAL_GetTick() + DBP_TIMEOUT_VALUE;
+
+ while((PWR->CR & PWR_CR_DBP) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Reset the Backup domain only if the RTC Clock source selction is modified */
+ if((RCC->BDCR & RCC_BDCR_RTCSEL) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))
+ {
+ /* Store the content of BDCR register before the reset of Backup Domain */
+ tmpreg = (RCC->BDCR & ~(RCC_BDCR_RTCSEL));
+ /* RTC Clock selection can be changed only if the Backup Domain is reset */
+ __HAL_RCC_BACKUPRESET_FORCE();
+ __HAL_RCC_BACKUPRESET_RELEASE();
+ /* Restore the Content of BDCR register */
+ RCC->BDCR = tmpreg;
+ }
+
+ /* If LSE is selected as RTC clock source, wait for LSE reactivation */
+ if(PeriphClkInit->RTCClockSelection == RCC_RTCCLKSOURCE_LSE)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + LSE_TIMEOUT_VALUE;
+
+ /* Wait till LSE is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ __HAL_RCC_RTC_CONFIG(PeriphClkInit->RTCClockSelection);
+ }
+
+ /*---------------------------- TIM configuration -------------------------------*/
+ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM))
+ {
+ __HAL_RCC_TIMCLKPRESCALER(PeriphClkInit->TIMPresSelection);
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the RCC_OscInitStruct according to the internal
+ * RCC configuration registers.
+ * @param RCC_OscInitStruct: pointer to an RCC_OscInitTypeDef structure that
+ * will be configured.
+ * @retval None
+ */
+void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit)
+{
+ uint32_t tempreg;
+
+ /* Set all possible values for the extended clock type parameter------------*/
+ PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_I2S | RCC_PERIPHCLK_SAI_PLLSAI | RCC_PERIPHCLK_SAI_PLLI2S | RCC_PERIPHCLK_LTDC | RCC_PERIPHCLK_TIM | RCC_PERIPHCLK_RTC;
+
+ /* Get the PLLI2S Clock configuration -----------------------------------------------*/
+ PeriphClkInit->PLLI2S.PLLI2SN = (uint32_t)((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SN));
+ PeriphClkInit->PLLI2S.PLLI2SR = (uint32_t)((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SR));
+ PeriphClkInit->PLLI2S.PLLI2SQ = (uint32_t)((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SQ) >> POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SQ));
+ /* Get the PLLSAI Clock configuration -----------------------------------------------*/
+ PeriphClkInit->PLLSAI.PLLSAIN = (uint32_t)((RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIN) >> POSITION_VAL(RCC_PLLSAICFGR_PLLSAIN));
+ PeriphClkInit->PLLSAI.PLLSAIR = (uint32_t)((RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIR) >> POSITION_VAL(RCC_PLLSAICFGR_PLLSAIR));
+ PeriphClkInit->PLLSAI.PLLSAIQ = (uint32_t)((RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIQ) >> POSITION_VAL(RCC_PLLSAICFGR_PLLSAIQ));
+ /* Get the PLLSAI/PLLI2S division factors -----------------------------------------------*/
+ PeriphClkInit->PLLI2SDivQ = (uint32_t)((RCC->DCKCFGR & RCC_DCKCFGR_PLLI2SDIVQ) >> POSITION_VAL(RCC_DCKCFGR_PLLI2SDIVQ));
+ PeriphClkInit->PLLSAIDivQ = (uint32_t)((RCC->DCKCFGR & RCC_DCKCFGR_PLLSAIDIVQ) >> POSITION_VAL(RCC_DCKCFGR_PLLSAIDIVQ));
+ PeriphClkInit->PLLSAIDivR = (uint32_t)(RCC->DCKCFGR & RCC_DCKCFGR_PLLSAIDIVR);
+ /* Get the RTC Clock configuration -----------------------------------------------*/
+ tempreg = (RCC->CFGR & RCC_CFGR_RTCPRE);
+ PeriphClkInit->RTCClockSelection = (uint32_t)((tempreg) | (RCC->BDCR & RCC_BDCR_RTCSEL));
+
+ if ((RCC->DCKCFGR & RCC_DCKCFGR_TIMPRE) == RESET)
+ {
+ PeriphClkInit->TIMPresSelection = RCC_TIMPRES_DESACTIVATED;
+ }
+ else
+ {
+ PeriphClkInit->TIMPresSelection = RCC_TIMPRES_ACTIVATED;
+ }
+}
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) || defined(STM32F401xC) || defined(STM32F401xE)
+/**
+ * @brief Initializes the RCC extended peripherals clocks according to the specified parameters in the
+ * RCC_PeriphCLKInitTypeDef.
+ * @param PeriphClkInit: pointer to an RCC_PeriphCLKInitTypeDef structure that
+ * contains the configuration information for the Extended Peripherals clocks(I2S and RTC clocks).
+ *
+ * @note A caution to be taken when HAL_RCCEx_PeriphCLKConfig() is used to select RTC clock selection, in this case
+ * the Reset of Backup domain will be applied in order to modify the RTC Clock source as consequence all backup
+ * domain (RTC and RCC_BDCR register expect BKPSRAM) will be reset
+ *
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit)
+{
+ uint32_t timeout = 0;
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection));
+
+ /*---------------------------- I2S configuration -------------------------------*/
+ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == (RCC_PERIPHCLK_I2S))
+ {
+ /* check for Parameters */
+ assert_param(IS_RCC_PLLI2SR_VALUE(PeriphClkInit->PLLI2S.PLLI2SR));
+ assert_param(IS_RCC_PLLI2SN_VALUE(PeriphClkInit->PLLI2S.PLLI2SN));
+
+ /* Disable the PLLI2S */
+ __HAL_RCC_PLLI2S_DISABLE();
+ /* Get new Timeout value */
+ timeout = HAL_GetTick() + PLLI2S_TIMEOUT_VALUE;
+ /* Wait till PLLI2S is disabled */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* return in case of Timeout detected */
+ return HAL_TIMEOUT;
+ }
+ }
+ /* Configure the PLLI2S division factors */
+ /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) × (PLLI2SN/PLLM) */
+ /* I2SCLK = f(PLLI2S clock output) = f(VCO clock) / PLLI2SR */
+ __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN , PeriphClkInit->PLLI2S.PLLI2SR);
+
+ /* Enable the PLLI2S */
+ __HAL_RCC_PLLI2S_ENABLE();
+ /* Get new Timeout value */
+ timeout = HAL_GetTick() + PLLI2S_TIMEOUT_VALUE;
+ /* Wait till PLLI2S is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* return in case of Timeout detected */
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /*---------------------------- RTC configuration -------------------------------*/
+ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC))
+ {
+ /* Enable Power Clock*/
+ __PWR_CLK_ENABLE();
+
+ /* Enable write access to Backup domain */
+ PWR->CR |= PWR_CR_DBP;
+
+ /* Wait for Backup domain Write protection disable */
+ timeout = HAL_GetTick() + DBP_TIMEOUT_VALUE;
+
+ while((PWR->CR & PWR_CR_DBP) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Reset the Backup domain only if the RTC Clock source selction is modified */
+ if((RCC->BDCR & RCC_BDCR_RTCSEL) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))
+ {
+ /* Store the content of BDCR register before the reset of Backup Domain */
+ tmpreg = (RCC->BDCR & ~(RCC_BDCR_RTCSEL));
+ /* RTC Clock selection can be changed only if the Backup Domain is reset */
+ __HAL_RCC_BACKUPRESET_FORCE();
+ __HAL_RCC_BACKUPRESET_RELEASE();
+ /* Restore the Content of BDCR register */
+ RCC->BDCR = tmpreg;
+ }
+
+ /* If LSE is selected as RTC clock source, wait for LSE reactivation */
+ if(PeriphClkInit->RTCClockSelection == RCC_RTCCLKSOURCE_LSE)
+ {
+ /* Get timeout */
+ timeout = HAL_GetTick() + LSE_TIMEOUT_VALUE;
+
+ /* Wait till LSE is ready */
+ while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ __HAL_RCC_RTC_CONFIG(PeriphClkInit->RTCClockSelection);
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the RCC_OscInitStruct according to the internal
+ * RCC configuration registers.
+ * @param RCC_OscInitStruct: pointer to an RCC_OscInitTypeDef structure that
+ * will be configured.
+ * @retval None
+ */
+void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit)
+{
+ uint32_t tempreg;
+
+ /* Set all possible values for the extended clock type parameter------------*/
+ PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_I2S | RCC_PERIPHCLK_RTC;
+
+ /* Get the PLLI2S Clock configuration -----------------------------------------------*/
+ PeriphClkInit->PLLI2S.PLLI2SN = (uint32_t)((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SN));
+ PeriphClkInit->PLLI2S.PLLI2SR = (uint32_t)((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SR));
+
+ /* Get the RTC Clock configuration -----------------------------------------------*/
+ tempreg = (RCC->CFGR & RCC_CFGR_RTCPRE);
+ PeriphClkInit->RTCClockSelection = (uint32_t)((tempreg) | (RCC->BDCR & RCC_BDCR_RTCSEL));
+
+}
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_RCC_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rng.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rng.c
new file mode 100644
index 0000000..7e40104
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rng.c
@@ -0,0 +1,414 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_rng.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief RNG HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Random Number Generator (RNG) peripheral:
+ * + Initialization/de-initialization functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The RNG HAL driver can be used as follows:
+
+ (#) Enable the RNG controller clock using __RNG_CLK_ENABLE() macro.
+ (#) Activate the RNG peripheral using __HAL_RNG_ENABLE() macro.
+ (#) Wait until the 32 bit Random Number Generator contains a valid
+ random data using (polling/interrupt) mode.
+ (#) Get the 32 bit random number using HAL_RNG_GetRandomNumber() function.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup RNG
+ * @brief RNG HAL module driver.
+ * @{
+ */
+
+#ifdef HAL_RNG_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define RNG_TIMEOUT_VALUE 1000
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup RNG_Private_Functions
+ * @{
+ */
+
+/** @defgroup RNG_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions.
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Initialize the RNG according to the specified parameters
+ in the RNG_InitTypeDef and create the associated handle
+ (+) DeInitialize the RNG peripheral
+ (+) Initialize the RNG MSP
+ (+) DeInitialize RNG MSP
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the RNG according to the specified
+ * parameters in the RNG_InitTypeDef and creates the associated handle.
+ * @param hrng: RNG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng)
+{
+ /* Check the RNG handle allocation */
+ if(hrng == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ if(hrng->State == HAL_RNG_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_RNG_MspInit(hrng);
+ }
+
+ /* Enable the RNG Peripheral */
+ __HAL_RNG_ENABLE(hrng);
+
+ /* Initialize the RNG state */
+ hrng->State = HAL_RNG_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the RNG peripheral.
+ * @param hrng: RNG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RNG_DeInit(RNG_HandleTypeDef *hrng)
+{
+ /* Check the RNG peripheral state */
+ if(hrng->State == HAL_RNG_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the RNG state */
+ hrng->State = HAL_RNG_STATE_BUSY;
+
+ /* Disable the RNG Peripheral */
+ __HAL_RNG_DISABLE(hrng);
+
+ /* Set the RNG registers to their reset values */
+ hrng->Instance->CR &= 0xFFFFFFF3;
+ hrng->Instance->SR &= 0xFFFFFF98;
+ hrng->Instance->DR &= 0x0;
+
+ /* DeInit the low level hardware */
+ HAL_RNG_MspDeInit(hrng);
+
+ /* Update the RNG state */
+ hrng->State = HAL_RNG_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hrng);
+
+ /* Return the function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the RNG MSP.
+ * @param hrng: RNG handle
+ * @retval None
+ */
+__weak void HAL_RNG_MspInit(RNG_HandleTypeDef *hrng)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RNG_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the RNG MSP.
+ * @param hrng: RNG handle
+ * @retval None
+ */
+__weak void HAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RNG_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup RNG_Group2 Peripheral Control functions
+ * @brief management functions.
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) Get the 32 bit Random number
+ (+) Get the 32 bit Random number with interrupt enabled
+ (+) Handle RNG interrupt request
+
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns a 32-bit random number.
+ * @note Each time the random number data is read the RNG_FLAG_DRDY flag
+ * is automatically cleared.
+ * @param hrng: RNG handle
+ * @retval 32-bit random number
+ */
+uint32_t HAL_RNG_GetRandomNumber(RNG_HandleTypeDef *hrng)
+{
+ uint32_t random32bit = 0;
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hrng);
+
+ timeout = HAL_GetTick() + RNG_TIMEOUT_VALUE;
+
+ /* Check if data register contains valid random data */
+ while(__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Get a 32bit Random number */
+ random32bit = hrng->Instance->DR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrng);
+
+ /* Return the 32 bit random number */
+ return random32bit;
+}
+
+/**
+ * @brief Returns a 32-bit random number with interrupt enabled.
+ * @param hrng: RNG handle
+ * @retval 32-bit random number
+ */
+uint32_t HAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef *hrng)
+{
+ uint32_t random32bit = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hrng);
+
+ /* Change RNG peripheral state */
+ hrng->State = HAL_RNG_STATE_BUSY;
+
+ /* Get a 32bit Random number */
+ random32bit = hrng->Instance->DR;
+
+ /* Enable the RNG Interrupts: Data Ready, Clock error, Seed error */
+ __HAL_RNG_ENABLE_IT(hrng);
+
+ /* Return the 32 bit random number */
+ return random32bit;
+}
+
+/**
+ * @brief Handles RNG interrupt request.
+ * @note In the case of a clock error, the RNG is no more able to generate
+ * random numbers because the PLL48CLK clock is not correct. User has
+ * to check that the clock controller is correctly configured to provide
+ * the RNG clock and clear the CEIS bit using __HAL_RNG_CLEAR_FLAG().
+ * The clock error has no impact on the previously generated
+ * random numbers, and the RNG_DR register contents can be used.
+ * @note In the case of a seed error, the generation of random numbers is
+ * interrupted as long as the SECS bit is '1'. If a number is
+ * available in the RNG_DR register, it must not be used because it may
+ * not have enough entropy. In this case, it is recommended to clear the
+ * SEIS bit using __HAL_RNG_CLEAR_FLAG(), then disable and enable
+ * the RNG peripheral to reinitialize and restart the RNG.
+ * @param hrng: RNG handle
+ * @retval None
+
+ */
+void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng)
+{
+ /* RNG clock error interrupt occured */
+ if(__HAL_RNG_GET_FLAG(hrng, RNG_IT_CEI) != RESET)
+ {
+ HAL_RNG_ErrorCallback(hrng);
+
+ /* Clear the clock error flag */
+ __HAL_RNG_CLEAR_FLAG(hrng, RNG_IT_CEI);
+
+ /* Change RNG peripheral state */
+ hrng->State = HAL_RNG_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrng);
+ }
+
+ /* RNG seed error interrupt occured */
+ if(__HAL_RNG_GET_FLAG(hrng, RNG_IT_SEI) != RESET)
+ {
+ HAL_RNG_ErrorCallback(hrng);
+
+ /* Clear the seed error flag */
+ __HAL_RNG_CLEAR_FLAG(hrng, RNG_IT_SEI);
+
+ /* Change RNG peripheral state */
+ hrng->State = HAL_RNG_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrng);
+ }
+
+ /* Check RNG data ready flag */
+ if(__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) != RESET)
+ {
+ /* Data Ready callback */
+ HAL_RNG_ReadyCallback(hrng);
+
+ /* Change RNG peripheral state */
+ hrng->State = HAL_RNG_STATE_READY;
+
+ /* Clear the RNG Data Ready flag */
+ __HAL_RNG_CLEAR_FLAG(hrng, RNG_FLAG_DRDY);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrng);
+ }
+}
+
+/**
+ * @brief Data Ready callback in non-blocking mode.
+ * @param hrng: RNG handle
+ * @retval None
+ */
+
+__weak void HAL_RNG_ReadyCallback(RNG_HandleTypeDef* hrng)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RNG_ReadyCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief RNG error callbacks.
+ * @param hrng: RNG handle
+ * @retval None
+ */
+__weak void HAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RNG_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup RNG_Group3 Peripheral State functions
+ * @brief Peripheral State functions.
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State functions #####
+ ===============================================================================
+ [..]
+ This subsection permits to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the RNG state.
+ * @param hrng: RNG handle
+ * @retval HAL state
+ */
+HAL_RNG_StateTypeDef HAL_RNG_GetState(RNG_HandleTypeDef *hrng)
+{
+ return hrng->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_RNG_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc.c
new file mode 100644
index 0000000..a28a883
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc.c
@@ -0,0 +1,1497 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_rtc.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief RTC HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Real Time Clock (RTC) peripheral:
+ * + Initialization and de-initialization functions
+ * + RTC Time and Date functions
+ * + RTC Alarm functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### Backup Domain Operating Condition #####
+ ==============================================================================
+ [..] The real-time clock (RTC), the RTC backup registers, and the backup
+ SRAM (BKP SRAM) can be powered from the VBAT voltage when the main
+ VDD supply is powered off.
+ To retain the content of the RTC backup registers, backup SRAM, and supply
+ the RTC when VDD is turned off, VBAT pin can be connected to an optional
+ standby voltage supplied by a battery or by another source.
+
+ [..] To allow the RTC to operate even when the main digital supply (VDD) is turned
+ off, the VBAT pin powers the following blocks:
+ (#) The RTC
+ (#) The LSE oscillator
+ (#) The backup SRAM when the low power backup regulator is enabled
+ (#) PC13 to PC15 I/Os, plus PI8 I/O (when available)
+
+ [..] When the backup domain is supplied by VDD (analog switch connected to VDD),
+ the following functions are available:
+ (#) PC14 and PC15 can be used as either GPIO or LSE pins
+ (#) PC13 can be used as a GPIO or as the RTC_AF1 pin
+ (#) PI8 can be used as a GPIO or as the RTC_AF2 pin
+
+ [..] When the backup domain is supplied by VBAT (analog switch connected to VBAT
+ because VDD is not present), the following functions are available:
+ (#) PC14 and PC15 can be used as LSE pins only
+ (#) PC13 can be used as the RTC_AF1 pin
+ (#) PI8 can be used as the RTC_AF2 pin
+
+ ##### Backup Domain Reset #####
+ ==================================================================
+ [..] The backup domain reset sets all RTC registers and the RCC_BDCR register
+ to their reset values. The BKPSRAM is not affected by this reset. The only
+ way of resetting the BKPSRAM is through the Flash interface by requesting
+ a protection level change from 1 to 0.
+ [..] A backup domain reset is generated when one of the following events occurs:
+ (#) Software reset, triggered by setting the BDRST bit in the
+ RCC Backup domain control register (RCC_BDCR).
+ (#) VDD or VBAT power on, if both supplies have previously been powered off.
+
+ ##### Backup Domain Access #####
+ ==================================================================
+ [..] After reset, the backup domain (RTC registers, RTC backup data
+ registers and backup SRAM) is protected against possible unwanted write
+ accesses.
+ [..] To enable access to the RTC Domain and RTC registers, proceed as follows:
+ (+) Enable the Power Controller (PWR) APB1 interface clock using the
+ __PWR_CLK_ENABLE() function.
+ (+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function.
+ (+) Select the RTC clock source using the __HAL_RCC_RTC_CONFIG() function.
+ (+) Enable RTC Clock using the __HAL_RCC_RTC_ENABLE() function.
+
+
+ ##### How to use this driver #####
+ ==================================================================
+ [..]
+ (+) Enable the RTC domain access (see description in the section above).
+ (+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour
+ format using the HAL_RTC_Init() function.
+
+ *** Time and Date configuration ***
+ ===================================
+ [..]
+ (+) To configure the RTC Calendar (Time and Date) use the HAL_RTC_SetTime()
+ and HAL_RTC_SetDate() functions.
+ (+) To read the RTC Calendar, use the HAL_RTC_GetTime() and HAL_RTC_GetDate() functions.
+
+ *** Alarm configuration ***
+ ===========================
+ [..]
+ (+) To configure the RTC Alarm use the HAL_RTC_SetAlarm() function.
+ You can also configure the RTC Alarm with interrupt mode using the HAL_RTC_SetAlarm_IT() function.
+ (+) To read the RTC Alarm, use the HAL_RTC_GetAlarm() function.
+
+ ##### RTC and low power modes #####
+ ==================================================================
+ [..] The MCU can be woken up from a low power mode by an RTC alternate
+ function.
+ [..] The RTC alternate functions are the RTC alarms (Alarm A and Alarm B),
+ RTC wakeup, RTC tamper event detection and RTC time stamp event detection.
+ These RTC alternate functions can wake up the system from the Stop and
+ Standby low power modes.
+ [..] The system can also wake up from low power modes without depending
+ on an external interrupt (Auto-wakeup mode), by using the RTC alarm
+ or the RTC wakeup events.
+ [..] The RTC provides a programmable time base for waking up from the
+ Stop or Standby mode at regular intervals.
+ Wakeup from STOP and Standby modes is possible only when the RTC clock source
+ is LSE or LSI.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup RTC
+ * @brief RTC HAL module driver
+ * @{
+ */
+
+#ifdef HAL_RTC_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup RTC_Private_Functions
+ * @{
+ */
+
+/** @defgroup RTC_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This section provide functions allowing to initialize and configure the
+ RTC Prescaler (Synchronous and Asynchronous), RTC Hour format, disable
+ RTC registers Write protection, enter and exit the RTC initialization mode,
+ RTC registers synchronization check and reference clock detection enable.
+ (#) The RTC Prescaler is programmed to generate the RTC 1Hz time base.
+ It is split into 2 programmable prescalers to minimize power consumption.
+ (++) A 7-bit asynchronous prescaler and A 13-bit synchronous prescaler.
+ (++) When both prescalers are used, it is recommended to configure the
+ asynchronous prescaler to a high value to minimize consumption.
+ (#) All RTC registers are Write protected. Writing to the RTC registers
+ is enabled by writing a key into the Write Protection register, RTC_WPR.
+ (#) To Configure the RTC Calendar, user application should enter
+ initialization mode. In this mode, the calendar counter is stopped
+ and its value can be updated. When the initialization sequence is
+ complete, the calendar restarts counting after 4 RTCCLK cycles.
+ (#) To read the calendar through the shadow registers after Calendar
+ initialization, calendar update or after wakeup from low power modes
+ the software must first clear the RSF flag. The software must then
+ wait until it is set again before reading the calendar, which means
+ that the calendar registers have been correctly copied into the
+ RTC_TR and RTC_DR shadow registers.The HAL_RTC_WaitForSynchro() function
+ implements the above software sequence (RSF clear and RSF check).
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the RTC peripheral
+ * @param hrtc: RTC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc)
+{
+ /* Check the RTC peripheral state */
+ if(hrtc == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_RTC_HOUR_FORMAT(hrtc->Init.HourFormat));
+ assert_param(IS_RTC_ASYNCH_PREDIV(hrtc->Init.AsynchPrediv));
+ assert_param(IS_RTC_SYNCH_PREDIV(hrtc->Init.SynchPrediv));
+ assert_param (IS_RTC_OUTPUT(hrtc->Init.OutPut));
+ assert_param (IS_RTC_OUTPUT_POL(hrtc->Init.OutPutPolarity));
+ assert_param(IS_RTC_OUTPUT_TYPE(hrtc->Init.OutPutType));
+
+ if(hrtc->State == HAL_RTC_STATE_RESET)
+ {
+ /* Initialize RTC MSP */
+ HAL_RTC_MspInit(hrtc);
+ }
+
+ /* Set RTC state */
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Set Initialization mode */
+ if(RTC_EnterInitMode(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state */
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Clear RTC_CR FMT, OSEL and POL Bits */
+ hrtc->Instance->CR &= ((uint32_t)~(RTC_CR_FMT | RTC_CR_OSEL | RTC_CR_POL));
+ /* Set RTC_CR register */
+ hrtc->Instance->CR |= (uint32_t)(hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity);
+
+ /* Configure the RTC PRER */
+ hrtc->Instance->PRER = (uint32_t)(hrtc->Init.SynchPrediv);
+ hrtc->Instance->PRER |= (uint32_t)(hrtc->Init.AsynchPrediv << 16);
+
+ /* Exit Initialization mode */
+ hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
+
+ hrtc->Instance->TAFCR &= (uint32_t)~RTC_TAFCR_ALARMOUTTYPE;
+ hrtc->Instance->TAFCR |= (uint32_t)(hrtc->Init.OutPutType);
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ return HAL_OK;
+ }
+}
+
+/**
+ * @brief DeInitializes the RTC peripheral
+ * @param hrtc: RTC handle
+ * @note This function doesn't reset the RTC Backup Data registers.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc)
+{
+ uint32_t timeout = 0;
+
+ /* Set RTC state */
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Set Initialization mode */
+ if(RTC_EnterInitMode(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state */
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Reset TR, DR and CR registers */
+ hrtc->Instance->TR = (uint32_t)0x00000000;
+ hrtc->Instance->DR = (uint32_t)0x00002101;
+ /* Reset All CR bits except CR[2:0] */
+ hrtc->Instance->CR &= (uint32_t)0x00000007;
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+
+ /* Wait till WUTWF flag is set and if Time out is reached exit */
+ while(((hrtc->Instance->ISR) & RTC_ISR_WUTWF) == (uint32_t)RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state */
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Reset all RTC CR register bits */
+ hrtc->Instance->CR &= (uint32_t)0x00000000;
+ hrtc->Instance->WUTR = (uint32_t)0x0000FFFF;
+ hrtc->Instance->PRER = (uint32_t)0x007F00FF;
+ hrtc->Instance->CALIBR = (uint32_t)0x00000000;
+ hrtc->Instance->ALRMAR = (uint32_t)0x00000000;
+ hrtc->Instance->ALRMBR = (uint32_t)0x00000000;
+ hrtc->Instance->SHIFTR = (uint32_t)0x00000000;
+ hrtc->Instance->CALR = (uint32_t)0x00000000;
+ hrtc->Instance->ALRMASSR = (uint32_t)0x00000000;
+ hrtc->Instance->ALRMBSSR = (uint32_t)0x00000000;
+
+ /* Reset ISR register and exit initialization mode */
+ hrtc->Instance->ISR = (uint32_t)0x00000000;
+
+ /* Reset Tamper and alternate functions configuration register */
+ hrtc->Instance->TAFCR = 0x00000000;
+
+ /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
+ if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET)
+ {
+ if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ return HAL_ERROR;
+ }
+ }
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* De-Initialize RTC MSP */
+ HAL_RTC_MspDeInit(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the RTC MSP.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+__weak void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RTC_MspInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the RTC MSP.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+__weak void HAL_RTC_MspDeInit(RTC_HandleTypeDef* hrtc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RTC_MspDeInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup RTC_Group2 RTC Time and Date functions
+ * @brief RTC Time and Date functions
+ *
+@verbatim
+ ===============================================================================
+ ##### RTC Time and Date functions #####
+ ===============================================================================
+
+ [..] This section provide functions allowing to configure Time and Date features
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Sets RTC current time.
+ * @param hrtc: RTC handle
+ * @param sTime: Pointer to Time structure
+ * @param Format: Specifies the format of the entered parameters.
+ * This parameter can be one of the following values:
+ * @arg Format_BIN: Binary data format
+ * @arg Format_BCD: BCD data format
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_FORMAT(Format));
+ assert_param(IS_RTC_DAYLIGHT_SAVING(sTime->DayLightSaving));
+ assert_param(IS_RTC_STORE_OPERATION(sTime->StoreOperation));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ if(Format == FORMAT_BIN)
+ {
+ if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
+ {
+ assert_param(IS_RTC_HOUR12(sTime->Hours));
+ assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat));
+ }
+ else
+ {
+ sTime->TimeFormat = 0x00;
+ assert_param(IS_RTC_HOUR24(sTime->Hours));
+ }
+ assert_param(IS_RTC_MINUTES(sTime->Minutes));
+ assert_param(IS_RTC_SECONDS(sTime->Seconds));
+
+ tmpreg = (uint32_t)(((uint32_t)RTC_ByteToBcd2(sTime->Hours) << 16) | \
+ ((uint32_t)RTC_ByteToBcd2(sTime->Minutes) << 8) | \
+ ((uint32_t)RTC_ByteToBcd2(sTime->Seconds)) | \
+ (((uint32_t)sTime->TimeFormat) << 16));
+ }
+ else
+ {
+ if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
+ {
+ tmpreg = RTC_Bcd2ToByte(sTime->Hours);
+ assert_param(IS_RTC_HOUR12(tmpreg));
+ assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat));
+ }
+ else
+ {
+ sTime->TimeFormat = 0x00;
+ assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sTime->Hours)));
+ }
+ assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sTime->Minutes)));
+ assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sTime->Seconds)));
+ tmpreg = (((uint32_t)(sTime->Hours) << 16) | \
+ ((uint32_t)(sTime->Minutes) << 8) | \
+ ((uint32_t)sTime->Seconds) | \
+ ((uint32_t)(sTime->TimeFormat) << 16));
+ }
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Set Initialization mode */
+ if(RTC_EnterInitMode(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state */
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Set the RTC_TR register */
+ hrtc->Instance->TR = (uint32_t)(tmpreg & RTC_TR_RESERVED_MASK);
+
+ /* Clear the bits to be configured */
+ hrtc->Instance->CR &= (uint32_t)~RTC_CR_BCK;
+
+ /* Configure the RTC_CR register */
+ hrtc->Instance->CR |= (uint32_t)(sTime->DayLightSaving | sTime->StoreOperation);
+
+ /* Exit Initialization mode */
+ hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
+
+ /* If CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
+ if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET)
+ {
+ if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+ }
+}
+
+/**
+ * @brief Gets RTC current time.
+ * @param hrtc: RTC handle
+ * @param sTime: Pointer to Time structure
+ * @param Format: Specifies the format of the entered parameters.
+ * This parameter can be one of the following values:
+ * @arg Format_BIN: Binary data format
+ * @arg Format_BCD: BCD data format
+ * @note Call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values
+ * in the higher-order calendar shadow registers.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_FORMAT(Format));
+
+ /* Get subseconds values from the correspondent registers*/
+ sTime->SubSeconds = (uint32_t)(hrtc->Instance->SSR);
+
+ /* Get the TR register */
+ tmpreg = (uint32_t)(hrtc->Instance->TR & RTC_TR_RESERVED_MASK);
+
+ /* Fill the structure fields with the read parameters */
+ sTime->Hours = (uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> 16);
+ sTime->Minutes = (uint8_t)((tmpreg & (RTC_TR_MNT | RTC_TR_MNU)) >>8);
+ sTime->Seconds = (uint8_t)(tmpreg & (RTC_TR_ST | RTC_TR_SU));
+ sTime->TimeFormat = (uint8_t)((tmpreg & (RTC_TR_PM)) >> 16);
+
+ /* Check the input parameters format */
+ if(Format == FORMAT_BIN)
+ {
+ /* Convert the time structure parameters to Binary format */
+ sTime->Hours = (uint8_t)RTC_Bcd2ToByte(sTime->Hours);
+ sTime->Minutes = (uint8_t)RTC_Bcd2ToByte(sTime->Minutes);
+ sTime->Seconds = (uint8_t)RTC_Bcd2ToByte(sTime->Seconds);
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets RTC current date.
+ * @param hrtc: RTC handle
+ * @param sDate: Pointer to date structure
+ * @param Format: specifies the format of the entered parameters.
+ * This parameter can be one of the following values:
+ * @arg Format_BIN: Binary data format
+ * @arg Format_BCD: BCD data format
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format)
+{
+ uint32_t datetmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_FORMAT(Format));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ if((Format == FORMAT_BIN) && ((sDate->Month & 0x10) == 0x10))
+ {
+ sDate->Month = (uint8_t)((sDate->Month & (uint8_t)~(0x10)) + (uint8_t)0x0A);
+ }
+
+ assert_param(IS_RTC_WEEKDAY(sDate->WeekDay));
+
+ if(Format == FORMAT_BIN)
+ {
+ assert_param(IS_RTC_YEAR(sDate->Year));
+ assert_param(IS_RTC_MONTH(sDate->Month));
+ assert_param(IS_RTC_DATE(sDate->Date));
+
+ datetmpreg = (((uint32_t)RTC_ByteToBcd2(sDate->Year) << 16) | \
+ ((uint32_t)RTC_ByteToBcd2(sDate->Month) << 8) | \
+ ((uint32_t)RTC_ByteToBcd2(sDate->Date)) | \
+ ((uint32_t)sDate->WeekDay << 13));
+ }
+ else
+ {
+ assert_param(IS_RTC_YEAR(RTC_Bcd2ToByte(sDate->Year)));
+ datetmpreg = RTC_Bcd2ToByte(sDate->Month);
+ assert_param(IS_RTC_MONTH(datetmpreg));
+ datetmpreg = RTC_Bcd2ToByte(sDate->Date);
+ assert_param(IS_RTC_DATE(datetmpreg));
+
+ datetmpreg = ((((uint32_t)sDate->Year) << 16) | \
+ (((uint32_t)sDate->Month) << 8) | \
+ ((uint32_t)sDate->Date) | \
+ (((uint32_t)sDate->WeekDay) << 13));
+ }
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Set Initialization mode */
+ if(RTC_EnterInitMode(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state*/
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Set the RTC_DR register */
+ hrtc->Instance->DR = (uint32_t)(datetmpreg & RTC_DR_RESERVED_MASK);
+
+ /* Exit Initialization mode */
+ hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
+
+ /* If CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
+ if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET)
+ {
+ if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_READY ;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+ }
+}
+
+/**
+ * @brief Gets RTC current date.
+ * @param hrtc: RTC handle
+ * @param sDate: Pointer to Date structure
+ * @param Format: Specifies the format of the entered parameters.
+ * This parameter can be one of the following values:
+ * @arg Format_BIN : Binary data format
+ * @arg Format_BCD : BCD data format
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format)
+{
+ uint32_t datetmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_FORMAT(Format));
+
+ /* Get the DR register */
+ datetmpreg = (uint32_t)(hrtc->Instance->DR & RTC_DR_RESERVED_MASK);
+
+ /* Fill the structure fields with the read parameters */
+ sDate->Year = (uint8_t)((datetmpreg & (RTC_DR_YT | RTC_DR_YU)) >> 16);
+ sDate->Month = (uint8_t)((datetmpreg & (RTC_DR_MT | RTC_DR_MU)) >> 8);
+ sDate->Date = (uint8_t)(datetmpreg & (RTC_DR_DT | RTC_DR_DU));
+ sDate->WeekDay = (uint8_t)((datetmpreg & (RTC_DR_WDU)) >> 13);
+
+ /* Check the input parameters format */
+ if(Format == FORMAT_BIN)
+ {
+ /* Convert the date structure parameters to Binary format */
+ sDate->Year = (uint8_t)RTC_Bcd2ToByte(sDate->Year);
+ sDate->Month = (uint8_t)RTC_Bcd2ToByte(sDate->Month);
+ sDate->Date = (uint8_t)RTC_Bcd2ToByte(sDate->Date);
+ }
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup RTC_Group3 RTC Alarm functions
+ * @brief RTC Alarm functions
+ *
+@verbatim
+ ===============================================================================
+ ##### RTC Alarm functions #####
+ ===============================================================================
+
+ [..] This section provide functions allowing to configure Alarm feature
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Sets the specified RTC Alarm.
+ * @param hrtc: RTC handle
+ * @param sAlarm: Pointer to Alarm structure
+ * @param Format: Specifies the format of the entered parameters.
+ * This parameter can be one of the following values:
+ * @arg Format_BIN: Binary data format
+ * @arg Format_BCD: BCD data format
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format)
+{
+ uint32_t timeout = 0;
+ uint32_t tmpreg = 0, subsecondtmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_FORMAT(Format));
+ assert_param(IS_ALARM(sAlarm->Alarm));
+ assert_param(IS_ALARM_MASK(sAlarm->AlarmMask));
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel));
+ assert_param(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds));
+ assert_param(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ if(Format == FORMAT_BIN)
+ {
+ if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
+ {
+ assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours));
+ assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
+ }
+ else
+ {
+ sAlarm->AlarmTime.TimeFormat = 0x00;
+ assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours));
+ }
+ assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes));
+ assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds));
+
+ if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
+ {
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay));
+ }
+ else
+ {
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay));
+ }
+
+ tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << 16) | \
+ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << 8) | \
+ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \
+ ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \
+ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << 24) | \
+ ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
+ ((uint32_t)sAlarm->AlarmMask));
+ }
+ else
+ {
+ if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
+ {
+ tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours);
+ assert_param(IS_RTC_HOUR12(tmpreg));
+ assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
+ }
+ else
+ {
+ sAlarm->AlarmTime.TimeFormat = 0x00;
+ assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
+ }
+
+ assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)));
+ assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));
+
+ if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
+ {
+ tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(tmpreg));
+ }
+ else
+ {
+ tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(tmpreg));
+ }
+
+ tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << 16) | \
+ ((uint32_t)(sAlarm->AlarmTime.Minutes) << 8) | \
+ ((uint32_t) sAlarm->AlarmTime.Seconds) | \
+ ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \
+ ((uint32_t)(sAlarm->AlarmDateWeekDay) << 24) | \
+ ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
+ ((uint32_t)sAlarm->AlarmMask));
+ }
+
+ /* Configure the Alarm A or Alarm B Sub Second registers */
+ subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask));
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Configure the Alarm register */
+ if(sAlarm->Alarm == RTC_ALARM_A)
+ {
+ /* Disable the Alarm A interrupt */
+ __HAL_RTC_ALARMA_DISABLE(hrtc);
+
+ /* In case of interrupt mode is used, the interrupt source must disabled */
+ __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+ /* Wait till RTC ALRAWF flag is set and if Time out is reached exit */
+ while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ hrtc->Instance->ALRMAR = (uint32_t)tmpreg;
+ /* Configure the Alarm A Sub Second register */
+ hrtc->Instance->ALRMASSR = subsecondtmpreg;
+ /* Configure the Alarm state: Enable Alarm */
+ __HAL_RTC_ALARMA_ENABLE(hrtc);
+ }
+ else
+ {
+ /* Disable the Alarm B interrupt */
+ __HAL_RTC_ALARMB_DISABLE(hrtc);
+
+ /* In case of interrupt mode is used, the interrupt source must disabled */
+ __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRB);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+ /* Wait till RTC ALRBWF flag is set and if Time out is reached exit */
+ while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ hrtc->Instance->ALRMBR = (uint32_t)tmpreg;
+ /* Configure the Alarm B Sub Second register */
+ hrtc->Instance->ALRMBSSR = subsecondtmpreg;
+ /* Configure the Alarm state: Enable Alarm */
+ __HAL_RTC_ALARMB_ENABLE(hrtc);
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets the specified RTC Alarm with Interrupt
+ * @param hrtc: RTC handle
+ * @param sAlarm: Pointer to Alarm structure
+ * @param Format: Specifies the format of the entered parameters.
+ * This parameter can be one of the following values:
+ * @arg Format_BIN: Binary data format
+ * @arg Format_BCD: BCD data format
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format)
+{
+ uint32_t timeout = 0;
+ uint32_t tmpreg = 0, subsecondtmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_FORMAT(Format));
+ assert_param(IS_ALARM(sAlarm->Alarm));
+ assert_param(IS_ALARM_MASK(sAlarm->AlarmMask));
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel));
+ assert_param(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds));
+ assert_param(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ if(Format == FORMAT_BIN)
+ {
+ if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
+ {
+ assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours));
+ assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
+ }
+ else
+ {
+ sAlarm->AlarmTime.TimeFormat = 0x00;
+ assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours));
+ }
+ assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes));
+ assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds));
+
+ if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
+ {
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay));
+ }
+ else
+ {
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay));
+ }
+ tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << 16) | \
+ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << 8) | \
+ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \
+ ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \
+ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << 24) | \
+ ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
+ ((uint32_t)sAlarm->AlarmMask));
+ }
+ else
+ {
+ if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
+ {
+ tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours);
+ assert_param(IS_RTC_HOUR12(tmpreg));
+ assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
+ }
+ else
+ {
+ sAlarm->AlarmTime.TimeFormat = 0x00;
+ assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
+ }
+
+ assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)));
+ assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));
+
+ if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
+ {
+ tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(tmpreg));
+ }
+ else
+ {
+ tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
+ assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(tmpreg));
+ }
+ tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << 16) | \
+ ((uint32_t)(sAlarm->AlarmTime.Minutes) << 8) | \
+ ((uint32_t) sAlarm->AlarmTime.Seconds) | \
+ ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \
+ ((uint32_t)(sAlarm->AlarmDateWeekDay) << 24) | \
+ ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
+ ((uint32_t)sAlarm->AlarmMask));
+ }
+ /* Configure the Alarm A or Alarm B Sub Second registers */
+ subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask));
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Configure the Alarm register */
+ if(sAlarm->Alarm == RTC_ALARM_A)
+ {
+ /* Disable the Alarm A interrupt */
+ __HAL_RTC_ALARMA_DISABLE(hrtc);
+
+ /* Clear flag alarm A */
+ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+ /* Wait till RTC ALRAWF flag is set and if Time out is reached exit */
+ while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ hrtc->Instance->ALRMAR = (uint32_t)tmpreg;
+ /* Configure the Alarm A Sub Second register */
+ hrtc->Instance->ALRMASSR = subsecondtmpreg;
+ /* Configure the Alarm state: Enable Alarm */
+ __HAL_RTC_ALARMA_ENABLE(hrtc);
+ /* Configure the Alarm interrupt */
+ __HAL_RTC_ALARM_ENABLE_IT(hrtc,RTC_IT_ALRA);
+ }
+ else
+ {
+ /* Disable the Alarm B interrupt */
+ __HAL_RTC_ALARMB_DISABLE(hrtc);
+
+ /* Clear flag alarm B */
+ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+ /* Wait till RTC ALRBWF flag is set and if Time out is reached exit */
+ while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ hrtc->Instance->ALRMBR = (uint32_t)tmpreg;
+ /* Configure the Alarm B Sub Second register */
+ hrtc->Instance->ALRMBSSR = subsecondtmpreg;
+ /* Configure the Alarm state: Enable Alarm */
+ __HAL_RTC_ALARMB_ENABLE(hrtc);
+ /* Configure the Alarm interrupt */
+ __HAL_RTC_ALARM_ENABLE_IT(hrtc, RTC_IT_ALRB);
+ }
+
+ /* RTC Alarm Interrupt Configuration: EXTI configuration */
+ __HAL_RTC_ENABLE_IT(RTC_EXTI_LINE_ALARM_EVENT);
+
+ EXTI->RTSR |= RTC_EXTI_LINE_ALARM_EVENT;
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Deactive the specified RTC Alarm
+ * @param hrtc: RTC handle
+ * @param Alarm: Specifies the Alarm.
+ * This parameter can be one of the following values:
+ * @arg ALARM_A : AlarmA
+ * @arg ALARM_B : AlarmB
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm)
+{
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_ALARM(Alarm));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ if(Alarm == RTC_ALARM_A)
+ {
+ /* AlarmA */
+ __HAL_RTC_ALARMA_DISABLE(hrtc);
+
+ /* In case of interrupt mode is used, the interrupt source must disabled */
+ __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+
+ /* Wait till RTC ALRxWF flag is set and if Time out is reached exit */
+ while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ else
+ {
+ /* AlarmB */
+ __HAL_RTC_ALARMB_DISABLE(hrtc);
+
+ /* In case of interrupt mode is used, the interrupt source must disabled */
+ __HAL_RTC_ALARM_DISABLE_IT(hrtc,RTC_IT_ALRB);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+
+ /* Wait till RTC ALRxWF flag is set and if Time out is reached exit */
+ while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Gets the RTC Alarm value and masks.
+ * @param hrtc: RTC handle
+ * @param sAlarm: Pointer to Date structure
+ * @param Alarm: Specifies the Alarm
+ * This parameter can be one of the following values:
+ * @arg ALARM_A: AlarmA
+ * @arg ALARM_B: AlarmB
+ * @param Format: Specifies the format of the entered parameters.
+ * This parameter can be one of the following values:
+ * @arg Format_BIN: Binary data format
+ * @arg Format_BCD: BCD data format
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format)
+{
+ uint32_t tmpreg = 0, subsecondtmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_FORMAT(Format));
+ assert_param(IS_ALARM(Alarm));
+
+ if(Alarm == RTC_ALARM_A)
+ {
+ /* AlarmA */
+ sAlarm->Alarm = RTC_ALARM_A;
+
+ tmpreg = (uint32_t)(hrtc->Instance->ALRMAR);
+ subsecondtmpreg = (uint32_t)((hrtc->Instance->ALRMASSR ) & RTC_ALRMASSR_SS);
+ }
+ else
+ {
+ sAlarm->Alarm = RTC_ALARM_B;
+
+ tmpreg = (uint32_t)(hrtc->Instance->ALRMBR);
+ subsecondtmpreg = (uint32_t)((hrtc->Instance->ALRMBSSR) & RTC_ALRMBSSR_SS);
+ }
+
+ /* Fill the structure with the read parameters */
+ sAlarm->AlarmTime.Hours = (uint32_t)((tmpreg & (RTC_ALRMAR_HT | RTC_ALRMAR_HU)) >> 16);
+ sAlarm->AlarmTime.Minutes = (uint32_t)((tmpreg & (RTC_ALRMAR_MNT | RTC_ALRMAR_MNU)) >> 8);
+ sAlarm->AlarmTime.Seconds = (uint32_t)(tmpreg & (RTC_ALRMAR_ST | RTC_ALRMAR_SU));
+ sAlarm->AlarmTime.TimeFormat = (uint32_t)((tmpreg & RTC_ALRMAR_PM) >> 16);
+ sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg;
+ sAlarm->AlarmDateWeekDay = (uint32_t)((tmpreg & (RTC_ALRMAR_DT | RTC_ALRMAR_DU)) >> 24);
+ sAlarm->AlarmDateWeekDaySel = (uint32_t)(tmpreg & RTC_ALRMAR_WDSEL);
+ sAlarm->AlarmMask = (uint32_t)(tmpreg & RTC_ALARMMASK_ALL);
+
+ if(Format == FORMAT_BIN)
+ {
+ sAlarm->AlarmTime.Hours = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours);
+ sAlarm->AlarmTime.Minutes = RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes);
+ sAlarm->AlarmTime.Seconds = RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds);
+ sAlarm->AlarmDateWeekDay = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles Alarm interrupt request.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef* hrtc)
+{
+ if(__HAL_RTC_ALARM_GET_IT(hrtc, RTC_IT_ALRA))
+ {
+ /* Get the status of the Interrupt */
+ if((uint32_t)(hrtc->Instance->CR & RTC_IT_ALRA) != (uint32_t)RESET)
+ {
+ /* AlarmA callback */
+ HAL_RTC_AlarmAEventCallback(hrtc);
+
+ /* Clear the Alarm interrupt pending bit */
+ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc,RTC_FLAG_ALRAF);
+ }
+ }
+
+ if(__HAL_RTC_ALARM_GET_IT(hrtc, RTC_IT_ALRB))
+ {
+ /* Get the status of the Interrupt */
+ if((uint32_t)(hrtc->Instance->CR & RTC_IT_ALRB) != (uint32_t)RESET)
+ {
+ /* AlarmB callback */
+ HAL_RTCEx_AlarmBEventCallback(hrtc);
+
+ /* Clear the Alarm interrupt pending bit */
+ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc,RTC_FLAG_ALRBF);
+ }
+ }
+
+ /* Clear the EXTI's line Flag for RTC Alarm */
+ __HAL_RTC_CLEAR_FLAG(RTC_EXTI_LINE_ALARM_EVENT);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+}
+
+/**
+ * @brief Alarm A callback.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+__weak void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RTC_AlarmAEventCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief This function handles AlarmA Polling request.
+ * @param hrtc: RTC handle
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
+{
+
+ uint32_t timeout = 0;
+
+ /* Get Timeout value */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAF) == RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Clear the Alarm interrupt pending bit */
+ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup RTC_Group4 Peripheral Control functions
+ * @brief Peripheral Control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Wait for RTC Time and Date Synchronization
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Waits until the RTC Time and Date registers (RTC_TR and RTC_DR) are
+ * synchronized with RTC APB clock.
+ * @note The RTC Resynchronization mode is write protected, use the
+ * __HAL_RTC_WRITEPROTECTION_DISABLE() before calling this function.
+ * @note To read the calendar through the shadow registers after Calendar
+ * initialization, calendar update or after wakeup from low power modes
+ * the software must first clear the RSF flag.
+ * The software must then wait until it is set again before reading
+ * the calendar, which means that the calendar registers have been
+ * correctly copied into the RTC_TR and RTC_DR shadow registers.
+ * @param hrtc: RTC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc)
+{
+ uint32_t timeout = 0;
+
+ /* Clear RSF flag */
+ hrtc->Instance->ISR &= (uint32_t)RTC_RSF_MASK;
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+
+ /* Wait the registers to be synchronised */
+ while((hrtc->Instance->ISR & RTC_ISR_RSF) == (uint32_t)RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ return HAL_OK;
+}
+
+/** @defgroup RTC_Group5 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State functions #####
+ ===============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Get RTC state
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Returns the Alarm state.
+ * @param hrtc: RTC handle
+ * @retval HAL state
+ */
+HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef* hrtc)
+{
+ return hrtc->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief Enters the RTC Initialization mode.
+ * @note The RTC Initialization mode is write protected, use the
+ * __HAL_RTC_WRITEPROTECTION_DISABLE() before calling this function.
+ * @param hrtc: RTC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc)
+{
+ uint32_t timeout = 0;
+
+ /* Check if the Initialization mode is set */
+ if((hrtc->Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET)
+ {
+ /* Set the Initialization mode */
+ hrtc->Instance->ISR = (uint32_t)RTC_INIT_MASK;
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+ /* Wait till RTC is in INIT state and if Time out is reached exit */
+ while((hrtc->Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Converts a 2 digit decimal to BCD format.
+ * @param Value: Byte to be converted
+ * @retval Converted byte
+ */
+uint8_t RTC_ByteToBcd2(uint8_t Value)
+{
+ uint32_t bcdhigh = 0;
+
+ while(Value >= 10)
+ {
+ bcdhigh++;
+ Value -= 10;
+ }
+
+ return ((uint8_t)(bcdhigh << 4) | Value);
+}
+
+/**
+ * @brief Converts from 2 digit BCD to Binary.
+ * @param Value: BCD value to be converted
+ * @retval Converted word
+ */
+uint8_t RTC_Bcd2ToByte(uint8_t Value)
+{
+ uint32_t tmp = 0;
+ tmp = ((uint8_t)(Value & (uint8_t)0xF0) >> (uint8_t)0x4) * 10;
+ return (tmp + (Value & (uint8_t)0x0F));
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_RTC_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc_ex.c
new file mode 100644
index 0000000..4e68a5c
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc_ex.c
@@ -0,0 +1,1671 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_rtc_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief RTC HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Real Time Clock (RTC) Extension peripheral:
+ * + RTC Time Stamp functions
+ * + RTC Tamper functions
+ * + RTC Wake-up functions
+ * + Extension Control functions
+ * + Extension RTC features functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (+) Enable the RTC domain access.
+ (+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour
+ format using the HAL_RTC_Init() function.
+
+ *** RTC Wakeup configuration ***
+ ================================
+ [..]
+ (+) To configure the RTC Wakeup Clock source and Counter use the HAL_RTC_SetWakeUpTimer()
+ function. You can also configure the RTC Wakeup timer with interrupt mode
+ using the HAL_RTC_SetWakeUpTimer_IT() function.
+ (+) To read the RTC WakeUp Counter register, use the HAL_RTC_GetWakeUpTimer()
+ function.
+
+ *** TimeStamp configuration ***
+ ===============================
+ [..]
+ (+) Configure the RTC_AFx trigger and enables the RTC TimeStamp using the
+ HAL_RTC_SetTimeStamp() function. You can also configure the RTC TimeStamp with
+ interrupt mode using the HAL_RTC_SetTimeStamp_IT() function.
+ (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTC_GetTimeStamp()
+ function.
+ (+) The TIMESTAMP alternate function can be mapped either to RTC_AF1 (PC13)
+ or RTC_AF2 (PI8) depending on the value of TSINSEL bit in
+ RTC_TAFCR register. The corresponding pin is also selected by HAL_RTC_SetTimeStamp()
+ or HAL_RTC_SetTimeStamp_IT() function.
+
+ *** Tamper configuration ***
+ ============================
+ [..]
+ (+) Enable the RTC Tamper and Configure the Tamper filter count, trigger Edge
+ or Level according to the Tamper filter (if equal to 0 Edge else Level)
+ value, sampling frequency, precharge or discharge and Pull-UP using the
+ HAL_RTC_SetTamper() function. You can configure RTC Tamper with interrupt
+ mode using HAL_RTC_SetTamper_IT() function.
+ (+) The TAMPER1 alternate function can be mapped either to RTC_AF1 (PC13)
+ or RTC_AF2 (PI8) depending on the value of TAMP1INSEL bit in
+ RTC_TAFCR register. The corresponding pin is also selected by HAL_RTC_SetTamper()
+ or HAL_RTC_SetTamper_IT() function.
+
+ *** Backup Data Registers configuration ***
+ ===========================================
+ [..]
+ (+) To write to the RTC Backup Data registers, use the HAL_RTC_BKUPWrite()
+ function.
+ (+) To read the RTC Backup Data registers, use the HAL_RTC_BKUPRead()
+ function.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup RTCEx
+ * @brief RTC HAL module driver
+ * @{
+ */
+
+#ifdef HAL_RTC_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup RTCEx_Private_Functions
+ * @{
+ */
+
+
+/** @defgroup RTCEx_Group1 RTC TimeStamp and Tamper functions
+ * @brief RTC TimeStamp and Tamper functions
+ *
+@verbatim
+ ===============================================================================
+ ##### RTC TimeStamp and Tamper functions #####
+ ===============================================================================
+
+ [..] This section provide functions allowing to configure TimeStamp feature
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Sets TimeStamp.
+ * @note This API must be called before enabling the TimeStamp feature.
+ * @param hrtc: RTC handle
+ * @param TimeStampEdge: Specifies the pin edge on which the TimeStamp is
+ * activated.
+ * This parameter can be one of the following:
+ * @arg TimeStampEdge_Rising: the Time stamp event occurs on the
+ * rising edge of the related pin.
+ * @arg TimeStampEdge_Falling: the Time stamp event occurs on the
+ * falling edge of the related pin.
+ * @param RTC_TimeStampPin: specifies the RTC TimeStamp Pin.
+ * This parameter can be one of the following values:
+ * @arg RTC_TIMESTAMPPIN_PC13: PC13 is selected as RTC TimeStamp Pin.
+ * @arg RTC_TIMESTAMPPIN_PI8: PI8 is selected as RTC TimeStamp Pin.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge));
+ assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Get the RTC_CR register and clear the bits to be configured */
+ tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE));
+
+ tmpreg|= TimeStampEdge;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ hrtc->Instance->TAFCR &= (uint32_t)~RTC_TAFCR_TSINSEL;
+ hrtc->Instance->TAFCR |= (uint32_t)(RTC_TimeStampPin);
+
+ /* Configure the Time Stamp TSEDGE and Enable bits */
+ hrtc->Instance->CR = (uint32_t)tmpreg;
+
+ __HAL_RTC_TIMESTAMP_ENABLE(hrtc);
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets TimeStamp with Interrupt.
+ * @param hrtc: RTC handle
+ * @note This API must be called before enabling the TimeStamp feature.
+ * @param TimeStampEdge: Specifies the pin edge on which the TimeStamp is
+ * activated.
+ * This parameter can be one of the following:
+ * @arg TimeStampEdge_Rising: the Time stamp event occurs on the
+ * rising edge of the related pin.
+ * @arg TimeStampEdge_Falling: the Time stamp event occurs on the
+ * falling edge of the related pin.
+ * @param RTC_TimeStampPin: Specifies the RTC TimeStamp Pin.
+ * This parameter can be one of the following values:
+ * @arg RTC_TIMESTAMPPIN_PC13: PC13 is selected as RTC TimeStamp Pin.
+ * @arg RTC_TIMESTAMPPIN_PI8: PI8 is selected as RTC TimeStamp Pin.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge));
+ assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Get the RTC_CR register and clear the bits to be configured */
+ tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE));
+
+ tmpreg |= TimeStampEdge;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Configure the Time Stamp TSEDGE and Enable bits */
+ hrtc->Instance->CR = (uint32_t)tmpreg;
+
+ hrtc->Instance->TAFCR &= (uint32_t)~RTC_TAFCR_TSINSEL;
+ hrtc->Instance->TAFCR |= (uint32_t)(RTC_TimeStampPin);
+
+ __HAL_RTC_TIMESTAMP_ENABLE(hrtc);
+
+ /* Enable IT timestamp */
+ __HAL_RTC_TIMESTAMP_ENABLE_IT(hrtc,RTC_IT_TS);
+
+ /* RTC timestamp Interrupt Configuration: EXTI configuration */
+ __HAL_RTC_ENABLE_IT(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT);
+
+ EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT;
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Deactivates TimeStamp.
+ * @param hrtc: RTC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc)
+{
+ uint32_t tmpreg = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* In case of interrupt mode is used, the interrupt source must disabled */
+ __HAL_RTC_TIMESTAMP_DISABLE_IT(hrtc, RTC_IT_TS);
+
+ /* Get the RTC_CR register and clear the bits to be configured */
+ tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE));
+
+ /* Configure the Time Stamp TSEDGE and Enable bits */
+ hrtc->Instance->CR = (uint32_t)tmpreg;
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Gets the RTC TimeStamp value.
+ * @param hrtc: RTC handle
+ * @param sTimeStamp: Pointer to Time structure
+ * @param sTimeStampDate: Pointer to Date structure
+ * @param Format: specifies the format of the entered parameters.
+ * This parameter can be one of the following values:
+ * @arg Format_BIN: Binary data format
+ * @arg Format_BCD: BCD data format
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef* sTimeStamp, RTC_DateTypeDef* sTimeStampDate, uint32_t Format)
+{
+ uint32_t tmptime = 0, tmpdate = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_FORMAT(Format));
+
+ /* Get the TimeStamp time and date registers values */
+ tmptime = (uint32_t)(hrtc->Instance->TSTR & RTC_TR_RESERVED_MASK);
+ tmpdate = (uint32_t)(hrtc->Instance->TSDR & RTC_DR_RESERVED_MASK);
+
+ /* Fill the Time structure fields with the read parameters */
+ sTimeStamp->Hours = (uint8_t)((tmptime & (RTC_TR_HT | RTC_TR_HU)) >> 16);
+ sTimeStamp->Minutes = (uint8_t)((tmptime & (RTC_TR_MNT | RTC_TR_MNU)) >> 8);
+ sTimeStamp->Seconds = (uint8_t)(tmptime & (RTC_TR_ST | RTC_TR_SU));
+ sTimeStamp->TimeFormat = (uint8_t)((tmptime & (RTC_TR_PM)) >> 16);
+ sTimeStamp->SubSeconds = (uint32_t) hrtc->Instance->TSSSR;
+
+ /* Fill the Date structure fields with the read parameters */
+ sTimeStampDate->Year = 0;
+ sTimeStampDate->Month = (uint8_t)((tmpdate & (RTC_DR_MT | RTC_DR_MU)) >> 8);
+ sTimeStampDate->Date = (uint8_t)(tmpdate & (RTC_DR_DT | RTC_DR_DU));
+ sTimeStampDate->WeekDay = (uint8_t)((tmpdate & (RTC_DR_WDU)) >> 13);
+
+ /* Check the input parameters format */
+ if(Format == FORMAT_BIN)
+ {
+ /* Convert the TimeStamp structure parameters to Binary format */
+ sTimeStamp->Hours = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Hours);
+ sTimeStamp->Minutes = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Minutes);
+ sTimeStamp->Seconds = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Seconds);
+
+ /* Convert the DateTimeStamp structure parameters to Binary format */
+ sTimeStampDate->Month = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Month);
+ sTimeStampDate->Date = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Date);
+ sTimeStampDate->WeekDay = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->WeekDay);
+ }
+
+ /* Clear the TIMESTAMP Flag */
+ __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets Tamper
+ * @note By calling this API we disable the tamper interrupt for all tampers.
+ * @param hrtc: RTC handle
+ * @param sTamper: Pointer to Tamper Structure.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_TAMPER(sTamper->Tamper));
+ assert_param(IS_RTC_TAMPER_PIN(sTamper->PinSelection));
+ assert_param(IS_TAMPER_TRIGGER(sTamper->Trigger));
+ assert_param(IS_TAMPER_FILTER(sTamper->Filter));
+ assert_param(IS_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency));
+ assert_param(IS_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration));
+ assert_param(IS_TAMPER_PULLUP_STATE(sTamper->TamperPullUp));
+ assert_param(IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ if(sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE)
+ {
+ sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1);
+ }
+
+ tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->PinSelection | (uint32_t)sTamper->Trigger |\
+ (uint32_t)sTamper->Filter | (uint32_t)sTamper->SamplingFrequency | (uint32_t)sTamper->PrechargeDuration |\
+ (uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection);
+
+ hrtc->Instance->TAFCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1) | (uint32_t)RTC_TAFCR_TAMPTS |\
+ (uint32_t)RTC_TAFCR_TAMPFREQ | (uint32_t)RTC_TAFCR_TAMPFLT | (uint32_t)RTC_TAFCR_TAMPPRCH |\
+ (uint32_t)RTC_TAFCR_TAMPPUDIS | (uint32_t)RTC_TAFCR_TAMPINSEL | (uint32_t)RTC_TAFCR_TAMPIE);
+
+ hrtc->Instance->TAFCR |= tmpreg;
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets Tamper with interrupt.
+ * @note By calling this API we force the tamper interrupt for all tampers.
+ * @param hrtc: RTC handle
+ * @param sTamper: Pointer to RTC Tamper.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_TAMPER(sTamper->Tamper));
+ assert_param(IS_RTC_TAMPER_PIN(sTamper->PinSelection));
+ assert_param(IS_TAMPER_TRIGGER(sTamper->Trigger));
+ assert_param(IS_TAMPER_FILTER(sTamper->Filter));
+ assert_param(IS_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency));
+ assert_param(IS_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration));
+ assert_param(IS_TAMPER_PULLUP_STATE(sTamper->TamperPullUp));
+ assert_param(IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Configure the tamper trigger */
+ if((sTamper->Trigger == RTC_TAMPERTRIGGER_RISINGEDGE) || (sTamper->Trigger == RTC_TAMPERTRIGGER_LOWLEVEL))
+ {
+ sTamper->Trigger = RTC_TAMPERTRIGGER_RISINGEDGE;
+ }
+ else
+ {
+ sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1);
+ }
+
+ tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->PinSelection | (uint32_t)sTamper->Trigger |\
+ (uint32_t)sTamper->Filter | (uint32_t)sTamper->SamplingFrequency | (uint32_t)sTamper->PrechargeDuration |\
+ (uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection);
+
+ hrtc->Instance->TAFCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1) | (uint32_t)RTC_TAFCR_TAMPTS |\
+ (uint32_t)RTC_TAFCR_TAMPFREQ | (uint32_t)RTC_TAFCR_TAMPFLT | (uint32_t)RTC_TAFCR_TAMPPRCH |\
+ (uint32_t)RTC_TAFCR_TAMPPUDIS | (uint32_t)RTC_TAFCR_TAMPINSEL);
+
+ hrtc->Instance->TAFCR |= tmpreg;
+
+ /* Configure the Tamper Interrupt in the RTC_TAFCR */
+ hrtc->Instance->TAFCR |= (uint32_t)RTC_TAFCR_TAMPIE;
+
+ /* RTC Tamper Interrupt Configuration: EXTI configuration */
+ __HAL_RTC_ENABLE_IT(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT);
+
+ EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT;
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Deactivates Tamper.
+ * @param hrtc: RTC handle
+ * @param Tamper: Selected tamper pin.
+ * This parameter can be RTC_Tamper_1 and/or RTC_TAMPER_2.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper)
+{
+ assert_param(IS_TAMPER(Tamper));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the selected Tamper pin */
+ hrtc->Instance->TAFCR &= (uint32_t)~Tamper;
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles TimeStamp interrupt request.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc)
+{
+ if(__HAL_RTC_TIMESTAMP_GET_IT(hrtc, RTC_IT_TS))
+ {
+ /* Get the status of the Interrupt */
+ if((uint32_t)(hrtc->Instance->CR & RTC_IT_TS) != (uint32_t)RESET)
+ {
+ /* TIMESTAMP callback */
+ HAL_RTCEx_TimeStampEventCallback(hrtc);
+
+ /* Clear the TIMESTAMP interrupt pending bit */
+ __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc,RTC_FLAG_TSF);
+ }
+ }
+
+ /* Get the status of the Interrupt */
+ if(__HAL_RTC_TAMPER_GET_IT(hrtc,RTC_IT_TAMP1))
+ {
+ /* Get the TAMPER Interrupt enable bit and pending bit */
+ if(((hrtc->Instance->TAFCR & (RTC_TAFCR_TAMPIE))) != (uint32_t)RESET)
+ {
+ /* Tamper callback */
+ HAL_RTCEx_Tamper1EventCallback(hrtc);
+
+ /* Clear the Tamper interrupt pending bit */
+ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP1F);
+ }
+ }
+
+ /* Get the status of the Interrupt */
+ if(__HAL_RTC_TAMPER_GET_IT(hrtc, RTC_IT_TAMP2))
+ {
+ /* Get the TAMPER Interrupt enable bit and pending bit */
+ if(((hrtc->Instance->TAFCR & RTC_TAFCR_TAMPIE)) != (uint32_t)RESET)
+ {
+ /* Tamper callback */
+ HAL_RTCEx_Tamper2EventCallback(hrtc);
+
+ /* Clear the Tamper interrupt pending bit */
+ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP2F);
+ }
+ }
+ /* Clear the EXTI's Flag for RTC TimeStamp and Tamper */
+ __HAL_RTC_CLEAR_FLAG(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+}
+
+/**
+ * @brief TimeStamp callback.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+__weak void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RTC_TimeStampEventCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Tamper 1 callback.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+__weak void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RTC_Tamper1EventCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Tamper 2 callback.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+__weak void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RTC_Tamper2EventCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief This function handles TimeStamp polling request.
+ * @param hrtc: RTC handle
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Get Timeout value */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSF) == RESET)
+ {
+ if(__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSOVF) != RESET)
+ {
+ /* Clear the TIMESTAMP OverRun Flag */
+ __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSOVF);
+
+ /* Change TIMESTAMP state */
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ return HAL_ERROR;
+ }
+
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles Tamper1 Polling.
+ * @param hrtc: RTC handle
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Get Timeout value */
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Get the status of the Interrupt */
+ while(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP1F)== RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Clear the Tamper Flag */
+ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP1F);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles Tamper2 Polling.
+ * @param hrtc: RTC handle
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Get Timeout value */
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Get the status of the Interrupt */
+ while(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP2F) == RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Clear the Tamper Flag */
+ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP2F);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup RTCEx_Group2 RTC Wake-up functions
+ * @brief RTC Wake-up functions
+ *
+@verbatim
+ ===============================================================================
+ ##### RTC Wake-up functions #####
+ ===============================================================================
+
+ [..] This section provide functions allowing to configure Wake-up feature
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Sets wake up timer.
+ * @param hrtc: RTC handle
+ * @param WakeUpCounter: Wake up counter
+ * @param WakeUpClock: Wake up clock
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock)
+{
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_WAKEUP_CLOCK(WakeUpClock));
+ assert_param(IS_WAKEUP_COUNTER(WakeUpCounter));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+
+ /* Wait till RTC WUTWF flag is set and if Time out is reached exit */
+ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Clear the Wakeup Timer clock source bits in CR register */
+ hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL;
+
+ /* Configure the clock source */
+ hrtc->Instance->CR |= (uint32_t)WakeUpClock;
+
+ /* Configure the Wakeup Timer counter */
+ hrtc->Instance->WUTR = (uint32_t)WakeUpCounter;
+
+ /* Enable the Wakeup Timer */
+ __HAL_RTC_WAKEUPTIMER_ENABLE(hrtc);
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets wake up timer with interrupt
+ * @param hrtc: RTC handle
+ * @param WakeUpCounter: wake up counter
+ * @param WakeUpClock: wake up clock
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock)
+{
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_WAKEUP_CLOCK(WakeUpClock));
+ assert_param(IS_WAKEUP_COUNTER(WakeUpCounter));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+
+ /* Wait till RTC WUTWF flag is set and if Time out is reached exit */
+ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Configure the Wakeup Timer counter */
+ hrtc->Instance->WUTR = (uint32_t)WakeUpCounter;
+
+ /* Clear the Wakeup Timer clock source bits in CR register */
+ hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL;
+
+ /* Configure the clock source */
+ hrtc->Instance->CR |= (uint32_t)WakeUpClock;
+
+ /* RTC WakeUpTimer Interrupt Configuration: EXTI configuration */
+ __HAL_RTC_ENABLE_IT(RTC_EXTI_LINE_WAKEUPTIMER_EVENT);
+
+ EXTI->RTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT;
+
+ /* Configure the Interrupt in the RTC_CR register */
+ __HAL_RTC_WAKEUPTIMER_ENABLE_IT(hrtc,RTC_IT_WUT);
+
+ /* Enable the Wakeup Timer */
+ __HAL_RTC_WAKEUPTIMER_ENABLE(hrtc);
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Deactivates wake up timer counter.
+ * @param hrtc: RTC handle
+ * @retval HAL status
+ */
+uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc)
+{
+ uint32_t timeout = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Disable the Wakeup Timer */
+ __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc);
+
+ /* In case of interrupt mode is used, the interrupt source must disabled */
+ __HAL_RTC_WAKEUPTIMER_DISABLE_IT(hrtc,RTC_IT_WUT);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+ /* Wait till RTC WUTWF flag is set and if Time out is reached exit */
+ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Gets wake up timer counter.
+ * @param hrtc: RTC handle
+ * @retval Counter value
+ */
+uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc)
+{
+ /* Get the counter value */
+ return ((uint32_t)(hrtc->Instance->WUTR & RTC_WUTR_WUT));
+}
+
+/**
+ * @brief This function handles Wake Up Timer interrupt request.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc)
+{
+ if(__HAL_RTC_WAKEUPTIMER_GET_IT(hrtc, RTC_IT_WUT))
+ {
+ /* Get the status of the Interrupt */
+ if((uint32_t)(hrtc->Instance->CR & RTC_IT_WUT) != (uint32_t)RESET)
+ {
+ /* WAKEUPTIMER callback */
+ HAL_RTCEx_WakeUpTimerEventCallback(hrtc);
+
+ /* Clear the WAKEUPTIMER interrupt pending bit */
+ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF);
+ }
+ }
+
+ /* Clear the EXTI's line Flag for RTC WakeUpTimer */
+ __HAL_RTC_CLEAR_FLAG(RTC_EXTI_LINE_WAKEUPTIMER_EVENT);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+}
+
+/**
+ * @brief Wake Up Timer callback.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+__weak void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RTC_WakeUpTimerEventCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief This function handles Wake Up Timer Polling.
+ * @param hrtc: RTC handle
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Get Timeout value */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTF) == RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Clear the WAKEUPTIMER Flag */
+ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+
+/** @defgroup RTCEx_Group3 Extension Peripheral Control functions
+ * @brief Extension Peripheral Control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Extension Peripheral Control functions #####
+ ===============================================================================
+ [..]
+ This subsection provides functions allowing to
+ (+) Writes a data in a specified RTC Backup data register
+ (+) Read a data in a specified RTC Backup data register
+ (+) Sets the Coarse calibration parameters.
+ (+) Deactivates the Coarse calibration parameters
+ (+) Sets the Smooth calibration parameters.
+ (+) Configures the Synchronization Shift Control Settings.
+ (+) Configures the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz).
+ (+) Deactivates the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz).
+ (+) Enables the RTC reference clock detection.
+ (+) Disable the RTC reference clock detection.
+ (+) Enables the Bypass Shadow feature.
+ (+) Disables the Bypass Shadow feature.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Writes a data in a specified RTC Backup data register.
+ * @param hrtc: RTC handle
+ * @param BackupRegister: RTC Backup data Register number.
+ * This parameter can be: RTC_BKP_DRx where x can be from 0 to 19 to
+ * specify the register.
+ * @param Data: Data to be written in the specified RTC Backup data register.
+ * @retval None
+ */
+void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data)
+{
+ uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_BKP(BackupRegister));
+
+ tmp = (uint32_t)&(hrtc->Instance->BKP0R);
+ tmp += (BackupRegister * 4);
+
+ /* Write the specified register */
+ *(__IO uint32_t *)tmp = (uint32_t)Data;
+}
+
+/**
+ * @brief Reads data from the specified RTC Backup data Register.
+ * @param hrtc: RTC handle
+ * @param BackupRegister: RTC Backup data Register number.
+ * This parameter can be: RTC_BKP_DRx where x can be from 0 to 19 to
+ * specify the register.
+ * @retval Read value
+ */
+uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister)
+{
+ uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_BKP(BackupRegister));
+
+ tmp = (uint32_t)&(hrtc->Instance->BKP0R);
+ tmp += (BackupRegister * 4);
+
+ /* Read the specified register */
+ return (*(__IO uint32_t *)tmp);
+}
+
+/**
+ * @brief Sets the Coarse calibration parameters.
+ * @param hrtc: RTC handle
+ * @param CalibSign: Specifies the sign of the coarse calibration value.
+ * This parameter can be one of the following values :
+ * @arg RTC_CALIBSIGN_POSITIVE: The value sign is positive
+ * @arg RTC_CALIBSIGN_NEGATIVE: The value sign is negative
+ * @param Value: value of coarse calibration expressed in ppm (coded on 5 bits).
+ *
+ * @note This Calibration value should be between 0 and 63 when using negative
+ * sign with a 2-ppm step.
+ *
+ * @note This Calibration value should be between 0 and 126 when using positive
+ * sign with a 4-ppm step.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetCoarseCalib(RTC_HandleTypeDef* hrtc, uint32_t CalibSign, uint32_t Value)
+{
+ /* Check the parameters */
+ assert_param(IS_RTC_CALIB_SIGN(CalibSign));
+ assert_param(IS_RTC_CALIB_VALUE(Value));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Set Initialization mode */
+ if(RTC_EnterInitMode(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state*/
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Enable the Coarse Calibration */
+ __HAL_RTC_COARSE_CALIB_ENABLE(hrtc);
+
+ /* Set the coarse calibration value */
+ hrtc->Instance->CALIBR = (uint32_t)(CalibSign|Value);
+
+ /* Exit Initialization mode */
+ hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Deactivates the Coarse calibration parameters.
+ * @param hrtc: RTC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_DeactivateCoarseCalib(RTC_HandleTypeDef* hrtc)
+{
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Set Initialization mode */
+ if(RTC_EnterInitMode(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state*/
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+ else
+ {
+ /* Enable the Coarse Calibration */
+ __HAL_RTC_COARSE_CALIB_DISABLE(hrtc);
+
+ /* Exit Initialization mode */
+ hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets the Smooth calibration parameters.
+ * @param hrtc: RTC handle
+ * @param SmoothCalibPeriod: Select the Smooth Calibration Period.
+ * This parameter can be can be one of the following values :
+ * @arg RTC_SMOOTHCALIB_PERIOD_32SEC: The smooth calibration periode is 32s.
+ * @arg RTC_SMOOTHCALIB_PERIOD_16SEC: The smooth calibration periode is 16s.
+ * @arg RTC_SMOOTHCALIB_PERIOD_8SEC: The smooth calibartion periode is 8s.
+ * @param SmoothCalibPlusPulses: Select to Set or reset the CALP bit.
+ * This parameter can be one of the following values:
+ * @arg RTC_SMOOTHCALIB_PLUSPULSES_SET: Add one RTCCLK puls every 2*11 pulses.
+ * @arg RTC_SMOOTHCALIB_PLUSPULSES_RESET: No RTCCLK pulses are added.
+ * @param SmouthCalibMinusPulsesValue: Select the value of CALM[8:0] bits.
+ * This parameter can be one any value from 0 to 0x000001FF.
+ * @note To deactivate the smooth calibration, the field SmoothCalibPlusPulses
+ * must be equal to SMOOTHCALIB_PLUSPULSES_RESET and the field
+ * SmouthCalibMinusPulsesValue mut be equal to 0.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef* hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue)
+{
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_SMOOTH_CALIB_PERIOD(SmoothCalibPeriod));
+ assert_param(IS_RTC_SMOOTH_CALIB_PLUS(SmoothCalibPlusPulses));
+ assert_param(IS_RTC_SMOOTH_CALIB_MINUS(SmouthCalibMinusPulsesValue));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* check if a calibration is pending*/
+ if((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET)
+ {
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+
+ /* check if a calibration is pending*/
+ while((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Configure the Smooth calibration settings */
+ hrtc->Instance->CALR = (uint32_t)((uint32_t)SmoothCalibPeriod | (uint32_t)SmoothCalibPlusPulses | (uint32_t)SmouthCalibMinusPulsesValue);
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the Synchronization Shift Control Settings.
+ * @note When REFCKON is set, firmware must not write to Shift control register.
+ * @param hrtc: RTC handle
+ * @param ShiftAdd1S: Select to add or not 1 second to the time calendar.
+ * This parameter can be one of the following values :
+ * @arg RTC_SHIFTADD1S_SET: Add one second to the clock calendar.
+ * @arg RTC_SHIFTADD1S_RESET: No effect.
+ * @param ShiftSubFS: Select the number of Second Fractions to substitute.
+ * This parameter can be one any value from 0 to 0x7FFF.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef* hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS)
+{
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_RTC_SHIFT_ADD1S(ShiftAdd1S));
+ assert_param(IS_RTC_SHIFT_SUBFS(ShiftSubFS));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE;
+
+ /* Wait until the shift is completed*/
+ while((hrtc->Instance->ISR & RTC_ISR_SHPF) != RESET)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+
+ /* Check if the reference clock detection is disabled */
+ if((hrtc->Instance->CR & RTC_CR_REFCKON) == RESET)
+ {
+ /* Configure the Shift settings */
+ hrtc->Instance->SHIFTR = (uint32_t)(uint32_t)(ShiftSubFS) | (uint32_t)(ShiftAdd1S);
+
+ /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
+ if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET)
+ {
+ if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+ }
+ }
+ else
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz).
+ * @param hrtc: RTC handle
+ * @param CalibOutput : Select the Calibration output Selection .
+ * This parameter can be one of the following values:
+ * @arg RTC_CALIBOUTPUT_512HZ: A signal has a regular waveform at 512Hz.
+ * @arg RTC_CALIBOUTPUT_1HZ: A signal has a regular waveform at 1Hz.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef* hrtc, uint32_t CalibOutput)
+{
+ /* Check the parameters */
+ assert_param(IS_RTC_CALIB_OUTPUT(CalibOutput));
+
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Clear flags before config */
+ hrtc->Instance->CR &= (uint32_t)~RTC_CR_COSEL;
+
+ /* Configure the RTC_CR register */
+ hrtc->Instance->CR |= (uint32_t)CalibOutput;
+
+ __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(hrtc);
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Deactivates the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz).
+ * @param hrtc: RTC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef* hrtc)
+{
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(hrtc);
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enables the RTC reference clock detection.
+ * @param hrtc: RTC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef* hrtc)
+{
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Set Initialization mode */
+ if(RTC_EnterInitMode(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state*/
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+ else
+ {
+ __HAL_RTC_CLOCKREF_DETECTION_ENABLE(hrtc);
+
+ /* Exit Initialization mode */
+ hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disable the RTC reference clock detection.
+ * @param hrtc: RTC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef* hrtc)
+{
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Set Initialization mode */
+ if(RTC_EnterInitMode(hrtc) != HAL_OK)
+ {
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Set RTC state*/
+ hrtc->State = HAL_RTC_STATE_ERROR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_ERROR;
+ }
+ else
+ {
+ __HAL_RTC_CLOCKREF_DETECTION_DISABLE(hrtc);
+
+ /* Exit Initialization mode */
+ hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
+ }
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enables the Bypass Shadow feature.
+ * @param hrtc: RTC handle
+ * @note When the Bypass Shadow is enabled the calendar value are taken
+ * directly from the Calendar counter.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef* hrtc)
+{
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Set the BYPSHAD bit */
+ hrtc->Instance->CR |= (uint8_t)RTC_CR_BYPSHAD;
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables the Bypass Shadow feature.
+ * @param hrtc: RTC handle
+ * @note When the Bypass Shadow is enabled the calendar value are taken
+ * directly from the Calendar counter.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef* hrtc)
+{
+ /* Process Locked */
+ __HAL_LOCK(hrtc);
+
+ hrtc->State = HAL_RTC_STATE_BUSY;
+
+ /* Disable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
+
+ /* Reset the BYPSHAD bit */
+ hrtc->Instance->CR &= (uint8_t)~RTC_CR_BYPSHAD;
+
+ /* Enable the write protection for RTC registers */
+ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hrtc);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+ /** @defgroup RTCEx_Group4 Extended features functions
+ * @brief Extended features functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Extended features functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+ (+) RTC Alram B callback
+ (+) RTC Poll for Alarm B request
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Alarm B callback.
+ * @param hrtc: RTC handle
+ * @retval None
+ */
+__weak void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_RTC_AlarmBEventCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief This function handles AlarmB Polling request.
+ * @param hrtc: RTC handle
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Get Timeout value */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBF) == RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ hrtc->State = HAL_RTC_STATE_TIMEOUT;
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ /* Clear the Alarm Flag */
+ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF);
+
+ /* Change RTC state */
+ hrtc->State = HAL_RTC_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_RTC_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sai.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sai.c
new file mode 100644
index 0000000..b2912e3
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sai.c
@@ -0,0 +1,1338 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_sai.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief SAI HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Serial Audio Interface (SAI) peripheral:
+ * + Initialization/de-initialization functions
+ * + I/O operation functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+
+ [..]
+ The SAI HAL driver can be used as follow:
+
+ (#) Declare a SAI_HandleTypeDef handle structure.
+ (#) Initialize the SAI low level resources by implement the HAL_SAI_MspInit() API:
+ (##) Enable the SAI interface clock.
+ (##) SAI pins configuration:
+ (+++) Enable the clock for the SAI GPIOs.
+ (+++) Configure these SAI pins as alternate function pull-up.
+ (##) NVIC configuration if you need to use interrupt process (HAL_SAI_Transmit_IT()
+ and HAL_SAI_Receive_IT() APIs):
+ (+++) Configure the SAI interrupt priority.
+ (+++) Enable the NVIC SAI IRQ handle.
+
+ (##) DMA Configuration if you need to use DMA process (HAL_SAI_Transmit_DMA()
+ and HAL_SAI_Receive_DMA() APIs):
+ (+++) Declare a DMA handle structure for the Tx/Rx stream.
+ (+++) Enable the DMAx interface clock.
+ (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.
+ (+++) Configure the DMA Tx/Rx Stream.
+ (+++) Associate the initialized DMA handle to the SAI DMA Tx/Rx handle.
+ (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the
+ DMA Tx/Rx Stream.
+
+ (#) Program the SAI Mode, Standard, Data Format, MCLK Output, Audio frequency and Polarity
+ using HAL_SAI_Init() function.
+
+ -@- The specific SAI interrupts (FIFO request and Overrun underrun interrupt)
+ will be managed using the macros __SAI_ENABLE_IT() and __SAI_DISABLE_IT()
+ inside the transmit and receive process.
+
+ [..]
+ (@) Make sure that either:
+ (+@) I2S PLL is configured or
+ (+@) SAI PLL is configured or
+ (+@) External clock source is configured after setting correctly
+ the define constant EXTERNAL_CLOCK_VALUE in the stm32f4xx_hal_conf.h file.
+
+ [..]
+ (@) In master TX mode: enabling the audio block immediately generates the bit clock
+ for the external slaves even if there is no data in the FIFO, However FS signal
+ generation is conditioned by the presence of data in the FIFO.
+
+ [..]
+ (@) In master RX mode: enabling the audio block immediately generates the bit clock
+ and FS signal for the external slaves.
+
+ [..]
+ (@) It is mandatory to respect the following conditions in order to avoid bad SAI behavior:
+ (+@) First bit Offset <= (SLOT size - Data size)
+ (+@) Data size <= SLOT size
+ (+@) Number of SLOT x SLOT size = Frame length
+ (+@) The number of slots should be even when SAI_FS_CHANNEL_IDENTIFICATION is selected.
+
+ [..]
+ Three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Send an amount of data in blocking mode using HAL_SAI_Transmit()
+ (+) Receive an amount of data in blocking mode using HAL_SAI_Receive()
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Send an amount of data in non blocking mode using HAL_SAI_Transmit_IT()
+ (+) At transmission end of transfer HAL_SAI_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_SAI_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode using HAL_SAI_Receive_IT()
+ (+) At reception end of transfer HAL_SAI_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_SAI_RxCpltCallback
+ (+) In case of transfer Error, HAL_SAI_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_SAI_ErrorCallback
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Send an amount of data in non blocking mode (DMA) using HAL_SAI_Transmit_DMA()
+ (+) At transmission end of transfer HAL_SAI_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_SAI_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode (DMA) using HAL_SAI_Receive_DMA()
+ (+) At reception end of transfer HAL_SAI_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_SAI_RxCpltCallback
+ (+) In case of transfer Error, HAL_SAI_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_SAI_ErrorCallback
+ (+) Pause the DMA Transfer using HAL_SAI_DMAPause()
+ (+) Resume the DMA Transfer using HAL_SAI_DMAResume()
+ (+) Stop the DMA Transfer using HAL_SAI_DMAStop()
+
+ *** SAI HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in USART HAL driver.
+
+ (+) __HAL_SAI_ENABLE: Enable the SAI peripheral
+ (+) __HAL_SAI_DISABLE: Disable the SAI peripheral
+ (+) __HAL_SAI_ENABLE_IT : Enable the specified SAI interrupts
+ (+) __HAL_SAI_DISABLE_IT : Disable the specified SAI interrupts
+ (+) __HAL_SAI_GET_IT_SOURCE: Check if the specified SAI interrupt source is
+ enabled or disabled
+ (+) __HAL_SAI_GET_FLAG: Check whether the specified SAI flag is set or not
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup SAI
+ * @brief SAI HAL module driver
+ * @{
+ */
+
+#ifdef HAL_SAI_MODULE_ENABLED
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* SAI registers Masks */
+#define CR1_CLEAR_MASK ((uint32_t)0xFF07C010)
+#define FRCR_CLEAR_MASK ((uint32_t)0xFFF88000)
+#define SLOTR_CLEAR_MASK ((uint32_t)0x0000F020)
+
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void SAI_DMATxCplt(DMA_HandleTypeDef *hdma);
+static void SAI_DMATxHalfCplt(DMA_HandleTypeDef *hdma);
+static void SAI_DMARxCplt(DMA_HandleTypeDef *hdma);
+static void SAI_DMARxHalfCplt(DMA_HandleTypeDef *hdma);
+static void SAI_DMAError(DMA_HandleTypeDef *hdma);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup SAI_Private_Functions
+ * @{
+ */
+
+/** @defgroup SAI_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This subsection provides a set of functions allowing to initialize and
+ de-initialize the SAIx peripheral:
+
+ (+) User must Implement HAL_SAI_MspInit() function in which he configures
+ all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ).
+
+ (+) Call the function HAL_SAI_Init() to configure the selected device with
+ the selected configuration:
+ (++) Mode (Master/slave TX/RX)
+ (++) Protocol
+ (++) Data Size
+ (++) MCLK Output
+ (++) Audio frequency
+ (++) FIFO Threshold
+ (++) Frame Config
+ (++) Slot Config
+
+ (+) Call the function HAL_SAI_DeInit() to restore the default configuration
+ of the selected SAI peripheral.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the SAI according to the specified parameters
+ * in the SAI_InitTypeDef and create the associated handle.
+ * @param hsai: SAI handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SAI_Init(SAI_HandleTypeDef *hsai)
+{
+ uint32_t tmpreg = 0;
+ uint32_t tmpclock = 0, tmp2clock = 0;
+ /* This variable used to store the VCO Input (value in Hz) */
+ uint32_t vcoinput = 0;
+ /* This variable used to store the SAI_CK_x (value in Hz) */
+ uint32_t saiclocksource = 0;
+
+ /* Check the SAI handle allocation */
+ if(hsai == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the SAI Block parameters */
+ assert_param(IS_SAI_BLOCK_PROTOCOL(hsai->Init.Protocol));
+ assert_param(IS_SAI_BLOCK_MODE(hsai->Init.AudioMode));
+ assert_param(IS_SAI_BLOCK_DATASIZE(hsai->Init.DataSize));
+ assert_param(IS_SAI_BLOCK_FIRST_BIT(hsai->Init.FirstBit));
+ assert_param(IS_SAI_BLOCK_CLOCK_STROBING(hsai->Init.ClockStrobing));
+ assert_param(IS_SAI_BLOCK_SYNCHRO(hsai->Init.Synchro));
+ assert_param(IS_SAI_BLOCK_OUTPUT_DRIVE(hsai->Init.OutputDrive));
+ assert_param(IS_SAI_BLOCK_NODIVIDER(hsai->Init.NoDivider));
+ assert_param(IS_SAI_BLOCK_FIFO_THRESHOLD(hsai->Init.FIFOThreshold));
+ assert_param(IS_SAI_AUDIO_FREQUENCY(hsai->Init.AudioFrequency));
+
+ /* Check the SAI Block Frame parameters */
+ assert_param(IS_SAI_BLOCK_FRAME_LENGTH(hsai->FrameInit.FrameLength));
+ assert_param(IS_SAI_BLOCK_ACTIVE_FRAME(hsai->FrameInit.ActiveFrameLength));
+ assert_param(IS_SAI_BLOCK_FS_DEFINITION(hsai->FrameInit.FSDefinition));
+ assert_param(IS_SAI_BLOCK_FS_POLARITY(hsai->FrameInit.FSPolarity));
+ assert_param(IS_SAI_BLOCK_FS_OFFSET(hsai->FrameInit.FSOffset));
+
+ /* Check the SAI Block Slot parameters */
+ assert_param(IS_SAI_BLOCK_FIRSTBIT_OFFSET(hsai->SlotInit.FirstBitOffset));
+ assert_param(IS_SAI_BLOCK_SLOT_SIZE(hsai->SlotInit.SlotSize));
+ assert_param(IS_SAI_BLOCK_SLOT_NUMBER(hsai->SlotInit.SlotNumber));
+ assert_param(IS_SAI_SLOT_ACTIVE(hsai->SlotInit.SlotActive));
+
+ if(hsai->State == HAL_SAI_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
+ HAL_SAI_MspInit(hsai);
+ }
+
+ hsai->State = HAL_SAI_STATE_BUSY;
+
+ /* Disable the selected SAI peripheral */
+ __HAL_SAI_DISABLE(hsai);
+
+ /* SAI Block Configuration ------------------------------------------------------------*/
+ /* SAI Block_x CR1 Configuration */
+ /* Get the SAI Block_x CR1 value */
+ tmpreg = hsai->Instance->CR1;
+ /* Clear MODE, PRTCFG, DS, LSBFIRST, CKSTR, SYNCEN, OUTDRIV, NODIV, and MCKDIV bits */
+ tmpreg &= CR1_CLEAR_MASK;
+ /* Configure SAI_Block_x: Audio Protocol, Data Size, first transmitted bit, Clock strobing
+ edge, Synchronization mode, Output drive, Master Divider and FIFO level */
+ /* Set PRTCFG bits according to Protocol value */
+ /* Set DS bits according to DataSize value */
+ /* Set LSBFIRST bit according to FirstBit value */
+ /* Set CKSTR bit according to ClockStrobing value */
+ /* Set SYNCEN bit according to Synchro value */
+ /* Set OUTDRIV bit according to OutputDrive value */
+ /* Set NODIV bit according to NoDivider value */
+ tmpreg |= (uint32_t)(hsai->Init.Protocol |
+ hsai->Init.AudioMode |
+ hsai->Init.DataSize |
+ hsai->Init.FirstBit |
+ hsai->Init.ClockStrobing |
+ hsai->Init.Synchro |
+ hsai->Init.OutputDrive |
+ hsai->Init.NoDivider);
+ /* Write to SAI_Block_x CR1 */
+ hsai->Instance->CR1 = tmpreg;
+
+ /* SAI Block_x CR2 Configuration */
+ /* Get the SAIBlock_x CR2 value */
+ tmpreg = hsai->Instance->CR2;
+ /* Clear FTH bits */
+ tmpreg &= ~(SAI_xCR2_FTH);
+ /* Configure the FIFO Level */
+ /* Set FTH bits according to SAI_FIFOThreshold value */
+ tmpreg |= (uint32_t)(hsai->Init.FIFOThreshold);
+ /* Write to SAI_Block_x CR2 */
+ hsai->Instance->CR2 = tmpreg;
+
+ /* SAI Block_x Frame Configuration -----------------------------------------*/
+ /* Get the SAI Block_x FRCR value */
+ tmpreg = hsai->Instance->FRCR;
+ /* Clear FRL, FSALL, FSDEF, FSPOL, FSOFF bits */
+ tmpreg &= FRCR_CLEAR_MASK;
+ /* Configure SAI_Block_x Frame: Frame Length, Active Frame Length, Frame Synchronization
+ Definition, Frame Synchronization Polarity and Frame Synchronization Polarity */
+ /* Set FRL bits according to SAI_FrameLength value */
+ /* Set FSALL bits according to SAI_ActiveFrameLength value */
+ /* Set FSDEF bit according to SAI_FSDefinition value */
+ /* Set FSPOL bit according to SAI_FSPolarity value */
+ /* Set FSOFF bit according to SAI_FSOffset value */
+ tmpreg |= (uint32_t)((uint32_t)(hsai->FrameInit.FrameLength - 1) |
+ hsai->FrameInit.FSOffset |
+ hsai->FrameInit.FSDefinition |
+ hsai->FrameInit.FSPolarity |
+ (uint32_t)((hsai->FrameInit.ActiveFrameLength - 1) << 8));
+
+ /* Write to SAI_Block_x FRCR */
+ hsai->Instance->FRCR = tmpreg;
+
+ /* SAI Block_x SLOT Configuration ------------------------------------------*/
+ /* Get the SAI Block_x SLOTR value */
+ tmpreg = hsai->Instance->SLOTR;
+ /* Clear FBOFF, SLOTSZ, NBSLOT, SLOTEN bits */
+ tmpreg &= SLOTR_CLEAR_MASK;
+ /* Configure SAI_Block_x Slot: First bit offset, Slot size, Number of Slot in
+ audio frame and slots activated in audio frame */
+ /* Set FBOFF bits according to SAI_FirstBitOffset value */
+ /* Set SLOTSZ bits according to SAI_SlotSize value */
+ /* Set NBSLOT bits according to SAI_SlotNumber value */
+ /* Set SLOTEN bits according to SAI_SlotActive value */
+ tmpreg |= (uint32_t)(hsai->SlotInit.FirstBitOffset |
+ hsai->SlotInit.SlotSize |
+ hsai->SlotInit.SlotActive |
+ (uint32_t)((hsai->SlotInit.SlotNumber - 1) << 8));
+
+ /* Write to SAI_Block_x SLOTR */
+ hsai->Instance->SLOTR = tmpreg;
+
+ /* SAI Block_x Clock Configuration -----------------------------------------*/
+ /* Check the Clock parameters */
+ assert_param(IS_SAI_CLK_SOURCE(hsai->Init.ClockSource));
+
+ /* SAI Block clock source selection */
+ if(hsai->Instance == SAI1_Block_A)
+ {
+ __HAL_RCC_SAI_BLOCKACLKSOURCE_CONFIG(hsai->Init.ClockSource);
+ }
+ else
+ {
+ __HAL_RCC_SAI_BLOCKBCLKSOURCE_CONFIG((uint32_t)(hsai->Init.ClockSource << 2));
+ }
+
+ /* VCO Input Clock value calculation */
+ if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSI)
+ {
+ /* In Case the PLL Source is HSI (Internal Clock) */
+ vcoinput = (HSI_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM));
+ }
+ else
+ {
+ /* In Case the PLL Source is HSE (External Clock) */
+ vcoinput = ((HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)));
+ }
+
+ /* SAI_CLK_x : SAI Block Clock configuration for different clock sources selected */
+ if(hsai->Init.ClockSource == SAI_CLKSOURCE_PLLSAI)
+ {
+ /* Configure the PLLI2S division factor */
+ /* PLLSAI_VCO Input = PLL_SOURCE/PLLM */
+ /* PLLSAI_VCO Output = PLLSAI_VCO Input * PLLSAIN */
+ /* SAI_CLK(first level) = PLLSAI_VCO Output/PLLSAIQ */
+ tmpreg = (RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIQ) >> 24;
+ saiclocksource = (vcoinput * ((RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIN) >> 6))/(tmpreg);
+
+ /* SAI_CLK_x = SAI_CLK(first level)/PLLSAIDIVQ */
+ tmpreg = (((RCC->DCKCFGR & RCC_DCKCFGR_PLLSAIDIVQ) >> 8) + 1);
+ saiclocksource = saiclocksource/(tmpreg);
+
+ }
+ else if(hsai->Init.ClockSource == SAI_CLKSOURCE_PLLI2S)
+ {
+ /* Configure the PLLI2S division factor */
+ /* PLLI2S_VCO Input = PLL_SOURCE/PLLM */
+ /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */
+ /* SAI_CLK(first level) = PLLI2S_VCO Output/PLLI2SQ */
+ tmpreg = (RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SQ) >> 24;
+ saiclocksource = (vcoinput * ((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6))/(tmpreg);
+
+ /* SAI_CLK_x = SAI_CLK(first level)/PLLI2SDIVQ */
+ tmpreg = ((RCC->DCKCFGR & RCC_DCKCFGR_PLLI2SDIVQ) + 1);
+ saiclocksource = saiclocksource/(tmpreg);
+ }
+ else /* sConfig->ClockSource == SAI_CLKSource_Ext */
+ {
+ /* Enable the External Clock selection */
+ __HAL_RCC_I2SCLK(RCC_I2SCLKSOURCE_EXT);
+
+ saiclocksource = EXTERNAL_CLOCK_VALUE;
+ }
+
+ /* Configure Master Clock using the following formula :
+ MCLK_x = SAI_CK_x / (MCKDIV[3:0] * 2) with MCLK_x = 256 * FS
+ FS = SAI_CK_x / (MCKDIV[3:0] * 2) * 256
+ MCKDIV[3:0] = SAI_CK_x / FS * 512 */
+ if(hsai->Init.NoDivider == SAI_MASTERDIVIDER_ENABLED)
+ {
+ /* (saiclocksource x 10) to keep Significant digits */
+ tmpclock = (((saiclocksource * 10) / ((hsai->Init.AudioFrequency) * 512)));
+
+ /* Get the result of modulo division */
+ tmp2clock = (tmpclock % 10);
+
+ /* Round result to the nearest integer*/
+ if (tmp2clock > 8)
+ {
+ tmpclock = ((tmpclock / 10) + 1);
+ }
+ else
+ {
+ tmpclock = (tmpclock / 10);
+ }
+ /*Set MCKDIV value in CR1 register*/
+ hsai->Instance->CR1 |= (tmpclock << 20);
+
+ }
+
+ /* Initialise the error code */
+ hsai->ErrorCode = HAL_SAI_ERROR_NONE;
+
+ /* Initialize the SAI state */
+ hsai->State= HAL_SAI_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the SAI peripheral.
+ * @param hsai: SAI handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SAI_DeInit(SAI_HandleTypeDef *hsai)
+{
+ /* Check the SAI handle allocation */
+ if(hsai == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ hsai->State = HAL_SAI_STATE_BUSY;
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */
+ HAL_SAI_MspDeInit(hsai);
+
+ /* Initialize the error code */
+ hsai->ErrorCode = HAL_SAI_ERROR_NONE;
+
+ /* Initialize the SAI state */
+ hsai->State = HAL_SAI_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief SAI MSP Init.
+ * @param hsai: SAI handle
+ * @retval None
+ */
+__weak void HAL_SAI_MspInit(SAI_HandleTypeDef *hsai)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SAI_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief SAI MSP DeInit.
+ * @param hsai: SAI handle
+ * @retval None
+ */
+__weak void HAL_SAI_MspDeInit(SAI_HandleTypeDef *hsai)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SAI_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SAI_Group2 IO operation functions
+ * @brief Data transfers functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the SAI data
+ transfers.
+
+ (+) There is two mode of transfer:
+ (++) Blocking mode : The communication is performed in the polling mode.
+ The status of all data processing is returned by the same function
+ after finishing transfer.
+ (++) No-Blocking mode : The communication is performed using Interrupts
+ or DMA. These functions return the status of the transfer startup.
+ The end of the data processing will be indicated through the
+ dedicated SAI IRQ when using Interrupt mode or the DMA IRQ when
+ using DMA mode.
+
+ (+) Blocking mode functions are :
+ (++) HAL_SAI_Transmit()
+ (++) HAL_SAI_Receive()
+ (++) HAL_SAI_TransmitReceive()
+
+ (+) No-Blocking mode functions with Interrupt are :
+ (++) HAL_SAI_Transmit_IT()
+ (++) HAL_SAI_Receive_IT()
+ (++) HAL_SAI_TransmitReceive_IT()
+
+ (+) No-Blocking mode functions with DMA are :
+ (++) HAL_SAI_Transmit_DMA()
+ (++) HAL_SAI_Receive_DMA()
+ (++) HAL_SAI_TransmitReceive_DMA()
+
+ (+) A set of Transfer Complete Callbacks are provided in No_Blocking mode:
+ (++) HAL_SAI_TxCpltCallback()
+ (++) HAL_SAI_RxCpltCallback()
+ (++) HAL_SAI_ErrorCallback()
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Transmits an amount of data in blocking mode.
+ * @param hsai: SAI handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SAI_Transmit(SAI_HandleTypeDef *hsai, uint16_t* pData, uint16_t Size, uint32_t Timeout)
+{
+ uint32_t timeout = 0x00;
+
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(hsai->State == HAL_SAI_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ hsai->State = HAL_SAI_STATE_BUSY_TX;
+
+ /* Check if the SAI is already enabled */
+ if((hsai->Instance->CR1 & SAI_xCR1_SAIEN) != SAI_xCR1_SAIEN)
+ {
+ /* Enable SAI peripheral */
+ __HAL_SAI_ENABLE(hsai);
+ }
+
+ while(Size > 0)
+ {
+ /* Wait the FIFO to be empty */
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+ while(__HAL_SAI_GET_FLAG(hsai, SAI_xSR_FREQ) == RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+
+ /* Update error code */
+ hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ /* Change the SAI state */
+ hsai->State = HAL_SAI_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ hsai->Instance->DR = (*pData++);
+ Size--;
+ }
+
+ hsai->State = HAL_SAI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receives an amount of data in blocking mode.
+ * @param hsai: SAI handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SAI_Receive(SAI_HandleTypeDef *hsai, uint16_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ uint32_t timeout = 0x00;
+
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(hsai->State == HAL_SAI_STATE_READY)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ hsai->State = HAL_SAI_STATE_BUSY_RX;
+
+ /* Check if the SAI is already enabled */
+ if((hsai->Instance->CR1 & SAI_xCR1_SAIEN) != SAI_xCR1_SAIEN)
+ {
+ /* Enable SAI peripheral */
+ __HAL_SAI_ENABLE(hsai);
+ }
+
+ /* Receive data */
+ while(Size > 0)
+ {
+ /* Wait until RXNE flag is set */
+ /* Get timeout */
+ timeout = HAL_GetTick() + Timeout;
+
+ while(__HAL_SAI_GET_FLAG(hsai, SAI_xSR_FREQ) == RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+
+ /* Update error code */
+ hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ /* Change the SAI state */
+ hsai->State = HAL_SAI_STATE_TIMEOUT;
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ (*pData++) = hsai->Instance->DR;
+ Size--;
+ }
+
+ hsai->State = HAL_SAI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmits an amount of data in no-blocking mode with Interrupt.
+ * @param hsai: SAI handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SAI_Transmit_IT(SAI_HandleTypeDef *hsai, uint16_t *pData, uint16_t Size)
+{
+ if(hsai->State == HAL_SAI_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ hsai->pTxBuffPtr = pData;
+ hsai->TxXferSize = Size;
+ hsai->TxXferCount = Size;
+
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ hsai->State = HAL_SAI_STATE_BUSY_TX;
+
+ /* Transmit data */
+ hsai->Instance->DR = (*hsai->pTxBuffPtr++);
+ hsai->TxXferCount--;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ /* Enable FRQ and OVRUDR interrupts */
+ __HAL_SAI_ENABLE_IT(hsai, (SAI_IT_FREQ | SAI_IT_OVRUDR));
+
+ /* Check if the SAI is already enabled */
+ if((hsai->Instance->CR1 & SAI_xCR1_SAIEN) != SAI_xCR1_SAIEN)
+ {
+ /* Enable SAI peripheral */
+ __HAL_SAI_ENABLE(hsai);
+ }
+
+
+ return HAL_OK;
+ }
+ else if(hsai->State == HAL_SAI_STATE_BUSY_TX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ /* Transmit data */
+ hsai->Instance->DR = (*hsai->pTxBuffPtr++);
+
+ hsai->TxXferCount--;
+
+ if(hsai->TxXferCount == 0)
+ {
+ /* Disable FREQ and OVRUDR interrupts */
+ __HAL_SAI_DISABLE_IT(hsai, (SAI_IT_FREQ | SAI_IT_OVRUDR));
+
+ hsai->State = HAL_SAI_STATE_READY;
+
+ HAL_SAI_TxCpltCallback(hsai);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+ }
+
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receives an amount of data in no-blocking mode with Interrupt.
+ * @param hsai: SAI handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SAI_Receive_IT(SAI_HandleTypeDef *hsai, uint16_t *pData, uint16_t Size)
+{
+ if(hsai->State == HAL_SAI_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ hsai->pRxBuffPtr = pData;
+ hsai->RxXferSize = Size;
+ hsai->RxXferCount = Size;
+
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ hsai->State = HAL_SAI_STATE_BUSY_RX;
+
+ /* Enable TXE and OVRUDR interrupts */
+ __HAL_SAI_ENABLE_IT(hsai, (SAI_IT_FREQ | SAI_IT_OVRUDR));
+
+ /* Check if the SAI is already enabled */
+ if((hsai->Instance->CR1 & SAI_xCR1_SAIEN) != SAI_xCR1_SAIEN)
+ {
+ /* Enable SAI peripheral */
+ __HAL_SAI_ENABLE(hsai);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+ }
+ else if(hsai->State == HAL_SAI_STATE_BUSY_RX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ /* Receive data */
+ (*hsai->pRxBuffPtr++) = hsai->Instance->DR;
+
+ hsai->RxXferCount--;
+
+ if(hsai->RxXferCount == 0)
+ {
+ /* Disable TXE and OVRUDR interrupts */
+ __HAL_SAI_DISABLE_IT(hsai, (SAI_IT_FREQ | SAI_IT_OVRUDR));
+
+ hsai->State = HAL_SAI_STATE_READY;
+ HAL_SAI_RxCpltCallback(hsai);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+ }
+
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Pauses the audio stream playing from the Media.
+ * @param hsai: SAI handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_SAI_DMAPause(SAI_HandleTypeDef *hsai)
+{
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ /* Pause the audio file playing by disabling the SAI DMA requests */
+ hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN;
+
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Resumes the audio stream playing from the Media.
+ * @param hsai: SAI handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_SAI_DMAResume(SAI_HandleTypeDef *hsai)
+{
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ /* Enable the SAI DMA requests */
+ hsai->Instance->CR1 |= SAI_xCR1_DMAEN;
+
+
+ /* If the SAI peripheral is still not enabled, enable it */
+ if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0)
+ {
+ /* Enable SAI peripheral */
+ __HAL_SAI_ENABLE(hsai);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Resumes the audio stream playing from the Media.
+ * @param hsai: SAI handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_SAI_DMAStop(SAI_HandleTypeDef *hsai)
+{
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ /* Disable the SAI DMA request */
+ hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN;
+
+ /* Abort the SAI DMA Tx Stream */
+ if(hsai->hdmatx != NULL)
+ {
+ HAL_DMA_Abort(hsai->hdmatx);
+ }
+ /* Abort the SAI DMA Rx Stream */
+ if(hsai->hdmarx != NULL)
+ {
+ HAL_DMA_Abort(hsai->hdmarx);
+ }
+
+ /* Disable SAI peripheral */
+ __HAL_SAI_DISABLE(hsai);
+
+ hsai->State = HAL_SAI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+}
+/**
+ * @brief Transmits an amount of data in no-blocking mode with DMA.
+ * @param hsai: SAI handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SAI_Transmit_DMA(SAI_HandleTypeDef *hsai, uint16_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(hsai->State == HAL_SAI_STATE_READY)
+ {
+ hsai->pTxBuffPtr = pData;
+ hsai->TxXferSize = Size;
+ hsai->TxXferCount = Size;
+
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ hsai->State = HAL_SAI_STATE_BUSY_TX;
+
+ /* Set the SAI Tx DMA Half transfert complete callback */
+ hsai->hdmatx->XferHalfCpltCallback = SAI_DMATxHalfCplt;
+
+ /* Set the SAI TxDMA transfer complete callback */
+ hsai->hdmatx->XferCpltCallback = SAI_DMATxCplt;
+
+ /* Set the DMA error callback */
+ hsai->hdmatx->XferErrorCallback = SAI_DMAError;
+
+ /* Enable the Tx DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(hsai->hdmatx, *(uint32_t*)tmp, (uint32_t)&hsai->Instance->DR, hsai->TxXferSize);
+
+ /* Check if the SAI is already enabled */
+ if((hsai->Instance->CR1 & SAI_xCR1_SAIEN) != SAI_xCR1_SAIEN)
+ {
+ /* Enable SAI peripheral */
+ __HAL_SAI_ENABLE(hsai);
+ }
+
+ /* Enable SAI Tx DMA Request */
+ hsai->Instance->CR1 |= SAI_xCR1_DMAEN;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in no-blocking mode with DMA.
+ * @param hsai: SAI handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SAI_Receive_DMA(SAI_HandleTypeDef *hsai, uint16_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ if(hsai->State == HAL_SAI_STATE_READY)
+ {
+ hsai->pRxBuffPtr = pData;
+ hsai->RxXferSize = Size;
+ hsai->RxXferCount = Size;
+
+ /* Process Locked */
+ __HAL_LOCK(hsai);
+
+ hsai->State = HAL_SAI_STATE_BUSY_RX;
+
+ /* Set the SAI Rx DMA Half transfert complete callback */
+ hsai->hdmarx->XferHalfCpltCallback = SAI_DMARxHalfCplt;
+
+ /* Set the SAI Rx DMA transfert complete callback */
+ hsai->hdmarx->XferCpltCallback = SAI_DMARxCplt;
+
+ /* Set the DMA error callback */
+ hsai->hdmarx->XferErrorCallback = SAI_DMAError;
+
+ /* Enable the Rx DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(hsai->hdmarx, (uint32_t)&hsai->Instance->DR, *(uint32_t*)tmp, hsai->RxXferSize);
+
+ /* Check if the SAI is already enabled */
+ if((hsai->Instance->CR1 & SAI_xCR1_SAIEN) != SAI_xCR1_SAIEN)
+ {
+ /* Enable SAI peripheral */
+ __HAL_SAI_ENABLE(hsai);
+ }
+
+ /* Enable SAI Rx DMA Request */
+ hsai->Instance->CR1 |= SAI_xCR1_DMAEN;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsai);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief This function handles SAI interrupt request.
+ * @param hsai: SAI handle
+ * @retval HAL status
+ */
+void HAL_SAI_IRQHandler(SAI_HandleTypeDef *hsai)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ if(hsai->State == HAL_SAI_STATE_BUSY_RX)
+ {
+ tmp1 = __HAL_SAI_GET_FLAG(hsai, SAI_xSR_FREQ);
+ tmp2 = __HAL_SAI_GET_IT_SOURCE(hsai, SAI_IT_FREQ);
+ /* SAI in mode Receiver --------------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ HAL_SAI_Receive_IT(hsai, NULL, 0);
+ }
+
+ tmp1 = __HAL_SAI_GET_FLAG(hsai, SAI_FLAG_OVRUDR);
+ tmp2 = __HAL_SAI_GET_IT_SOURCE(hsai, SAI_IT_OVRUDR);
+ /* SAI Overrun error interrupt occurred ----------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ /* Change the SAI error code */
+ hsai->ErrorCode = HAL_SAI_ERROR_OVR;
+
+ /* Clear the SAI Overrun flag */
+ __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR);
+ /* Set the SAI state ready to be able to start again the process */
+ hsai->State = HAL_SAI_STATE_READY;
+ HAL_SAI_ErrorCallback(hsai);
+ }
+ }
+
+ if(hsai->State == HAL_SAI_STATE_BUSY_TX)
+ {
+ tmp1 = __HAL_SAI_GET_FLAG(hsai, SAI_xSR_FREQ);
+ tmp2 = __HAL_SAI_GET_IT_SOURCE(hsai, SAI_IT_FREQ);
+ /* SAI in mode Transmitter -----------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ HAL_SAI_Transmit_IT(hsai, NULL, 0);
+ }
+
+ tmp1 = __HAL_SAI_GET_FLAG(hsai, SAI_FLAG_OVRUDR);
+ tmp2 = __HAL_SAI_GET_IT_SOURCE(hsai, SAI_IT_OVRUDR);
+ /* SAI Underrun error interrupt occurred ---------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ /* Change the SAI error code */
+ hsai->ErrorCode = HAL_SAI_ERROR_UDR;
+
+ /* Clear the SAI Underrun flag */
+ __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR);
+ /* Set the SAI state ready to be able to start again the process */
+ hsai->State = HAL_SAI_STATE_READY;
+ HAL_SAI_ErrorCallback(hsai);
+ }
+ }
+}
+
+/**
+ * @brief Tx Transfer completed callbacks.
+ * @param hsai: SAI handle
+ * @retval None
+ */
+ __weak void HAL_SAI_TxCpltCallback(SAI_HandleTypeDef *hsai)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SAI_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Tx Transfer Half completed callbacks
+ * @param hsai: SAI handle
+ * @retval None
+ */
+ __weak void HAL_SAI_TxHalfCpltCallback(SAI_HandleTypeDef *hsai)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SAI_TxHalfCpltCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer completed callbacks.
+ * @param hsai: SAI handle
+ * @retval None
+ */
+__weak void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SAI_RxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer half completed callbacks
+ * @param hsai: SAI handle
+ * @retval None
+ */
+__weak void HAL_SAI_RxHalfCpltCallback(SAI_HandleTypeDef *hsai)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SAI_RxCpltCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief SAI error callbacks.
+ * @param hsai: SAI handle
+ * @retval None
+ */
+__weak void HAL_SAI_ErrorCallback(SAI_HandleTypeDef *hsai)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SAI_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+
+/** @defgroup SAI_Group3 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State and Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the SAI state.
+ * @param hsai: SAI handle
+ * @retval HAL state
+ */
+HAL_SAI_StateTypeDef HAL_SAI_GetState(SAI_HandleTypeDef *hsai)
+{
+ return hsai->State;
+}
+
+/**
+* @brief Return the SAI error code
+* @param hsai : pointer to a SAI_HandleTypeDef structure that contains
+ * the configuration information for the specified SAI Block.
+* @retval SAI Error Code
+*/
+uint32_t HAL_SAI_GetError(SAI_HandleTypeDef *hsai)
+{
+ return hsai->ErrorCode;
+}
+/**
+ * @}
+ */
+
+/**
+ * @brief DMA SAI transmit process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void SAI_DMATxCplt(DMA_HandleTypeDef *hdma)
+{
+ uint32_t timeout = 0x00;
+
+ SAI_HandleTypeDef* hsai = (SAI_HandleTypeDef*)((DMA_HandleTypeDef* )hdma)->Parent;
+
+ if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
+ {
+ hsai->TxXferCount = 0;
+ hsai->RxXferCount = 0;
+
+ /* Disable SAI Tx DMA Request */
+ hsai->Instance->CR1 &= (uint32_t)(~SAI_xCR1_DMAEN);
+
+ /* Set timeout: 10 is the max delay to send the remaining data in the SAI FIFO */
+ timeout = HAL_GetTick() + 10;
+
+ /* Wait until FIFO is empty */
+ while(__HAL_SAI_GET_FLAG(hsai, SAI_xSR_FLVL) != RESET)
+ {
+ /* Check for the Timeout */
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Update error code */
+ hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT;
+
+ /* Change the SAI state */
+ HAL_SAI_ErrorCallback(hsai);
+ }
+ }
+
+ hsai->State= HAL_SAI_STATE_READY;
+ }
+ HAL_SAI_TxCpltCallback(hsai);
+}
+
+/**
+ * @brief DMA SAI transmit process half complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void SAI_DMATxHalfCplt(DMA_HandleTypeDef *hdma)
+{
+ SAI_HandleTypeDef* hsai = (SAI_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ HAL_SAI_TxHalfCpltCallback(hsai);
+}
+
+/**
+ * @brief DMA SAI receive process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void SAI_DMARxCplt(DMA_HandleTypeDef *hdma)
+{
+ SAI_HandleTypeDef* hsai = ( SAI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
+ {
+ /* Disable Rx DMA Request */
+ hsai->Instance->CR1 &= (uint32_t)(~SAI_xCR1_DMAEN);
+ hsai->RxXferCount = 0;
+
+ hsai->State = HAL_SAI_STATE_READY;
+ }
+ HAL_SAI_RxCpltCallback(hsai);
+}
+
+/**
+ * @brief DMA SAI receive process half complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void SAI_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
+{
+ SAI_HandleTypeDef* hsai = (SAI_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ HAL_SAI_RxHalfCpltCallback(hsai);
+}
+/**
+ * @brief DMA SAI communication error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void SAI_DMAError(DMA_HandleTypeDef *hdma)
+{
+ SAI_HandleTypeDef* hsai = ( SAI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ /* Set the SAI state ready to be able to start again the process */
+ hsai->State= HAL_SAI_STATE_READY;
+ HAL_SAI_ErrorCallback(hsai);
+
+ hsai->TxXferCount = 0;
+ hsai->RxXferCount = 0;
+}
+
+/**
+ * @}
+ */
+
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_SAI_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sd.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sd.c
new file mode 100644
index 0000000..f16ecfd
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sd.c
@@ -0,0 +1,3359 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_sd.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief SD card HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Secure Digital (SD) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ This driver implements a high level communication layer for read and write from/to
+ this memory. The needed STM32 hardware resources (SDIO and GPIO) are performed by
+ the user in HAL_SD_MspInit() function (MSP layer).
+ Basically, the MSP layer configuration should be the same as we provide in the
+ examples.
+ You can easily tailor this configuration according to hardware resources.
+
+ [..]
+ This driver is a generic layered driver for SDIO memories which uses the HAL
+ SDIO driver functions to interface with SD and uSD cards devices.
+ It is used as follows:
+
+ (#)Initialize the SDIO low level resources by implement the HAL_SD_MspInit() API:
+ (##) Enable the SDIO interface clock using __SDIO_CLK_ENABLE();
+ (##) SDIO pins configuration for SD card
+ (+++) Enable the clock for the SDIO GPIOs using the functions __GPIOx_CLK_ENABLE();
+ (+++) Configure these SDIO pins as alternate function pull-up using HAL_GPIO_Init()
+ and according to your pin assignment;
+ (##) DMA Configuration if you need to use DMA process (HAL_SD_ReadBlocks_DMA()
+ and HAL_SD_WriteBlocks_DMA() APIs).
+ (+++) Enable the DMAx interface clock using __DMAx_CLK_ENABLE();
+ (+++) Configure the DMA using the function HAL_DMA_Init() with predeclared and filled.
+ (##) NVIC configuration if you need to use interrupt process when using DMA transfer.
+ (+++) Configure the SDIO and DMA interrupt priorities using functions
+ HAL_NVIC_SetPriority(); DMA priority is superior to SDIO's priority
+ (+++) Enable the NVIC DMA and SDIO IRQs using function HAL_NVIC_EnableIRQ()
+ (+++) SDIO interrupts are managed using the macros __HAL_SD_SDIO_ENABLE_IT()
+ and __HAL_SD_SDIO_DISABLE_IT() inside the communication process.
+ (+++) SDIO interrupts pending bits are managed using the macros __HAL_SD_SDIO_GET_IT()
+ and __HAL_SD_SDIO_CLEAR_IT()
+ (#) At this stage, you can perform SD read/write/erase operations after SD card initialization
+
+
+ *** SD Card Initialization and configuration ***
+ ================================================
+ [..]
+ To initialize the SD Card, use the HAL_SD_Init() function. It Initializes
+ the SD Card and put it into StandBy State (Ready for data transfer).
+ This function provide the following operations:
+
+ (#) Apply the SD Card initialization process at 400KHz and check the SD Card
+ type (Standard Capacity or High Capacity). You can change or adapt this
+ frequency by adjusting the "ClockDiv" field.
+ The SD Card frequency (SDIO_CK) is computed as follows:
+
+ SDIO_CK = SDIOCLK / (ClockDiv + 2)
+
+ In initialization mode and according to the SD Card standard,
+ make sure that the SDIO_CK frequency doesn't exceed 400KHz.
+
+ (#) Get the SD CID and CSD data. All these information are managed by the SDCardInfo
+ structure. This structure provide also ready computed SD Card capacity
+ and Block size.
+
+ -@- These information are stored in SD handle structure in case of future use.
+
+ (#) Configure the SD Card Data transfer frequency. By Default, the card transfer
+ frequency is set to 24MHz. You can change or adapt this frequency by adjusting
+ the "ClockDiv" field.
+ The SD Card frequency (SDIO_CK) is computed as follows:
+
+ SDIO_CK = SDIOCLK / (ClockDiv + 2)
+
+ In transfer mode and according to the SD Card standard, make sure that the
+ SDIO_CK frequency doesn't exceed 25MHz and 50MHz in High-speed mode switch.
+ To be able to use a frequency higher than 24MHz, you should use the SDIO
+ peripheral in bypass mode. Refer to the corresponding reference manual
+ for more details.
+
+ (#) Select the corresponding SD Card according to the address read with the step 2.
+
+ (#) Configure the SD Card in wide bus mode: 4-bits data.
+
+ *** SD Card Read operation ***
+ ==============================
+ [..]
+ (+) You can read from SD card in polling mode by using function HAL_SD_ReadBlocks().
+ This function support only 512-byte block length (the block size should be
+ chosen as 512 byte).
+ You can choose either one block read operation or multiple block read operation
+ by adjusting the "NumberOfBlocks" parameter.
+
+ (+) You can read from SD card in DMA mode by using function HAL_SD_ReadBlocks_DMA().
+ This function support only 512-byte block length (the block size should be
+ chosen as 512 byte).
+ You can choose either one block read operation or multiple block read operation
+ by adjusting the "NumberOfBlocks" parameter.
+ After this, you have to call the function HAL_SD_CheckReadOperation(), to insure
+ that the read transfer is done correctly in both DMA and SD sides.
+
+ *** SD Card Write operation ***
+ ===============================
+ [..]
+ (+) You can write to SD card in polling mode by using function HAL_SD_WriteBlocks().
+ This function support only 512-byte block length (the block size should be
+ chosen as 512 byte).
+ You can choose either one block read operation or multiple block read operation
+ by adjusting the "NumberOfBlocks" parameter.
+
+ (+) You can write to SD card in DMA mode by using function HAL_SD_WriteBlocks_DMA().
+ This function support only 512-byte block length (the block size should be
+ chosen as 512 byte).
+ You can choose either one block read operation or multiple block read operation
+ by adjusting the "NumberOfBlocks" parameter.
+ After this, you have to call the function HAL_SD_CheckWriteOperation(), to insure
+ that the write transfer is done correctly in both DMA and SD sides.
+
+ *** SD card status ***
+ ======================
+ [..]
+ (+) At any time, you can check the SD Card status and get the SD card state
+ by using the HAL_SD_GetStatus() function. This function checks first if the
+ SD card is still connected and then get the internal SD Card transfer state.
+ (+) You can also get the SD card SD Status register by using the HAL_SD_SendSDStatus()
+ function.
+
+ *** SD HAL driver macros list ***
+ ==================================
+ [..]
+ Below the list of most used macros in SD HAL driver.
+
+ (+) __HAL_SD_SDIO_ENABLE : Enable the SD device
+ (+) __HAL_SD_SDIO_DISABLE : Disable the SD device
+ (+) __HAL_SD_SDIO_DMA_ENABLE: Enable the SDIO DMA transfer
+ (+) __HAL_SD_SDIO_DMA_DISABLE: Disable the SDIO DMA transfer
+ (+) __HAL_SD_SDIO_ENABLE_IT: Enable the SD device interrupt
+ (+) __HAL_SD_SDIO_DISABLE_IT: Disable the SD device interrupt
+ (+) __HAL_SD_SDIO_GET_FLAG:Check whether the specified SD flag is set or not
+ (+) __HAL_SD_SDIO_CLEAR_FLAG: Clear the SD's pending flags
+
+ (@) You can refer to the SD HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup SD
+ * @brief SD HAL module driver
+ * @{
+ */
+
+#ifdef HAL_SD_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+
+/**
+ * @brief SDIO Static flags, TimeOut, FIFO Address
+ */
+#define SDIO_STATIC_FLAGS ((uint32_t)0x000005FF)
+#define SDIO_CMD0TIMEOUT ((uint32_t)0x00010000)
+
+/**
+ * @brief Mask for errors Card Status R1 (OCR Register)
+ */
+#define SD_OCR_ADDR_OUT_OF_RANGE ((uint32_t)0x80000000)
+#define SD_OCR_ADDR_MISALIGNED ((uint32_t)0x40000000)
+#define SD_OCR_BLOCK_LEN_ERR ((uint32_t)0x20000000)
+#define SD_OCR_ERASE_SEQ_ERR ((uint32_t)0x10000000)
+#define SD_OCR_BAD_ERASE_PARAM ((uint32_t)0x08000000)
+#define SD_OCR_WRITE_PROT_VIOLATION ((uint32_t)0x04000000)
+#define SD_OCR_LOCK_UNLOCK_FAILED ((uint32_t)0x01000000)
+#define SD_OCR_COM_CRC_FAILED ((uint32_t)0x00800000)
+#define SD_OCR_ILLEGAL_CMD ((uint32_t)0x00400000)
+#define SD_OCR_CARD_ECC_FAILED ((uint32_t)0x00200000)
+#define SD_OCR_CC_ERROR ((uint32_t)0x00100000)
+#define SD_OCR_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00080000)
+#define SD_OCR_STREAM_READ_UNDERRUN ((uint32_t)0x00040000)
+#define SD_OCR_STREAM_WRITE_OVERRUN ((uint32_t)0x00020000)
+#define SD_OCR_CID_CSD_OVERWRIETE ((uint32_t)0x00010000)
+#define SD_OCR_WP_ERASE_SKIP ((uint32_t)0x00008000)
+#define SD_OCR_CARD_ECC_DISABLED ((uint32_t)0x00004000)
+#define SD_OCR_ERASE_RESET ((uint32_t)0x00002000)
+#define SD_OCR_AKE_SEQ_ERROR ((uint32_t)0x00000008)
+#define SD_OCR_ERRORBITS ((uint32_t)0xFDFFE008)
+
+/**
+ * @brief Masks for R6 Response
+ */
+#define SD_R6_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00002000)
+#define SD_R6_ILLEGAL_CMD ((uint32_t)0x00004000)
+#define SD_R6_COM_CRC_FAILED ((uint32_t)0x00008000)
+
+#define SD_VOLTAGE_WINDOW_SD ((uint32_t)0x80100000)
+#define SD_HIGH_CAPACITY ((uint32_t)0x40000000)
+#define SD_STD_CAPACITY ((uint32_t)0x00000000)
+#define SD_CHECK_PATTERN ((uint32_t)0x000001AA)
+
+#define SD_MAX_VOLT_TRIAL ((uint32_t)0x0000FFFF)
+#define SD_ALLZERO ((uint32_t)0x00000000)
+
+#define SD_WIDE_BUS_SUPPORT ((uint32_t)0x00040000)
+#define SD_SINGLE_BUS_SUPPORT ((uint32_t)0x00010000)
+#define SD_CARD_LOCKED ((uint32_t)0x02000000)
+
+#define SD_DATATIMEOUT ((uint32_t)0xFFFFFFFF)
+#define SD_0TO7BITS ((uint32_t)0x000000FF)
+#define SD_8TO15BITS ((uint32_t)0x0000FF00)
+#define SD_16TO23BITS ((uint32_t)0x00FF0000)
+#define SD_24TO31BITS ((uint32_t)0xFF000000)
+#define SD_MAX_DATA_LENGTH ((uint32_t)0x01FFFFFF)
+
+#define SD_HALFFIFO ((uint32_t)0x00000008)
+#define SD_HALFFIFOBYTES ((uint32_t)0x00000020)
+
+/**
+ * @brief Command Class Supported
+ */
+#define SD_CCCC_LOCK_UNLOCK ((uint32_t)0x00000080)
+#define SD_CCCC_WRITE_PROT ((uint32_t)0x00000040)
+#define SD_CCCC_ERASE ((uint32_t)0x00000020)
+
+/**
+ * @brief Following commands are SD Card Specific commands.
+ * SDIO_APP_CMD should be sent before sending these commands.
+ */
+#define SD_SDIO_SEND_IF_COND ((uint32_t)SD_CMD_HS_SEND_EXT_CSD)
+
+
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+static HAL_SD_ErrorTypedef SD_Initialize_Cards(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_Select_Deselect(SD_HandleTypeDef *hsd, uint64_t addr);
+static HAL_SD_ErrorTypedef SD_PowerON(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_PowerOFF(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus);
+static HAL_SD_CardStateTypedef SD_GetState(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_IsCardProgramming(SD_HandleTypeDef *hsd, uint8_t *pStatus);
+static HAL_SD_ErrorTypedef SD_CmdError(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_CmdResp1Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD);
+static HAL_SD_ErrorTypedef SD_CmdResp7Error(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_CmdResp3Error(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_CmdResp2Error(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_CmdResp6Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD, uint16_t *pRCA);
+static HAL_SD_ErrorTypedef SD_WideBus_Enable(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_WideBus_Disable(SD_HandleTypeDef *hsd);
+static HAL_SD_ErrorTypedef SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR);
+static void SD_DMA_RxCplt(DMA_HandleTypeDef *hdma);
+static void SD_DMA_RxError(DMA_HandleTypeDef *hdma);
+static void SD_DMA_TxCplt(DMA_HandleTypeDef *hdma);
+static void SD_DMA_TxError(DMA_HandleTypeDef *hdma);
+
+/** @defgroup SD_Private_Functions
+ * @{
+ */
+
+/** @defgroup SD_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de-initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to initialize/de-initialize the SD
+ card device to be ready for use.
+
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the SD card according to the specified parameters in the
+ SD_HandleTypeDef and create the associated handle.
+ * @param hsd: SD handle
+ * @param SDCardInfo: HAL_SD_CardInfoTypedef structure for SD card information
+ * @retval HAL SD error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_Init(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *SDCardInfo)
+{
+ __IO HAL_SD_ErrorTypedef errorState = SD_OK;
+ SD_InitTypeDef tmpInit;
+
+ /* Initialize the low level hardware (MSP) */
+ HAL_SD_MspInit(hsd);
+
+ /* Default SDIO peripheral configuration for SD card initialization */
+ tmpInit.ClockEdge = SDIO_CLOCK_EDGE_RISING;
+ tmpInit.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
+ tmpInit.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE;
+ tmpInit.BusWide = SDIO_BUS_WIDE_1B;
+ tmpInit.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
+ tmpInit.ClockDiv = SDIO_INIT_CLK_DIV;
+
+ /* Initialize SDIO peripheral interface with default configuration */
+ SDIO_Init(hsd->Instance, tmpInit);
+
+ /* Identify card operating voltage */
+ errorState = SD_PowerON(hsd);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Initialize the present SDIO card(s) and put them in idle state */
+ errorState = SD_Initialize_Cards(hsd);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Read CSD/CID MSD registers */
+ errorState = HAL_SD_Get_CardInfo(hsd, SDCardInfo);
+
+ if (errorState == SD_OK)
+ {
+ /* Select the Card */
+ errorState = SD_Select_Deselect(hsd, (uint32_t)(((uint32_t)SDCardInfo->RCA) << 16));
+ }
+
+ /* Configure SDIO peripheral interface */
+ SDIO_Init(hsd->Instance, hsd->Init);
+
+ return errorState;
+}
+
+/**
+ * @brief De-Initializes the SD card.
+ * @param hsd: SD handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SD_DeInit(SD_HandleTypeDef *hsd)
+{
+
+ /* Set SD power state to off */
+ SD_PowerOFF(hsd);
+
+ /* De-Initialize the MSP layer */
+ HAL_SD_MspDeInit(hsd);
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Initializes the SD MSP.
+ * @param hsd: SD handle
+ * @retval None
+ */
+__weak void HAL_SD_MspInit(SD_HandleTypeDef *hsd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SD_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief De-Initialize SD MSP.
+ * @param hsd: SD handle
+ * @retval None
+ */
+__weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SD_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SD_Group2 IO operation functions
+ * @brief Data transfer functions
+ *
+@verbatim
+ ==============================================================================
+ ##### IO operation functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the data
+ transfer from/to SD card.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Reads block(s) from a specified address in a card. The Data transfer
+ * is managed by polling mode.
+ * @param hsd: SD handle
+ * @param pReadBuffer: pointer to the buffer that will contain the received data
+ * @param ReadAddr: Address from where data is to be read
+ * @param BlockSize: SD card Data block size
+ * This parameter should be 512
+ * @param NumberOfBlocks: Number of SD blocks to read
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ SDIO_DataInitTypeDef SDIO_DataInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t count = 0, *tempbuff = (uint32_t *)pReadBuffer;
+
+ /* Initialize data control register */
+ hsd->Instance->DCTRL = 0;
+
+ if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
+ {
+ BlockSize = 512;
+ ReadAddr /= 512;
+ }
+
+ /* Set Block Size for Card */
+ SDIO_CmdInitStructure.Argument = (uint32_t) BlockSize;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SET_BLOCKLEN;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Configure the SD DPSM (Data Path State Machine) */
+ SDIO_DataInitStructure.DataTimeOut = SD_DATATIMEOUT;
+ SDIO_DataInitStructure.DataLength = NumberOfBlocks * BlockSize;
+ SDIO_DataInitStructure.DataBlockSize = (uint32_t)(9 << 4);
+ SDIO_DataInitStructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO;
+ SDIO_DataInitStructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK;
+ SDIO_DataInitStructure.DPSM = SDIO_DPSM_ENABLE;
+ SDIO_DataConfig(hsd->Instance, &SDIO_DataInitStructure);
+
+ if(NumberOfBlocks > 1)
+ {
+ /* Send CMD18 READ_MULT_BLOCK with argument data address */
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_READ_MULT_BLOCK;
+ }
+ else
+ {
+ /* Send CMD17 READ_SINGLE_BLOCK */
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_READ_SINGLE_BLOCK;
+ }
+
+ SDIO_CmdInitStructure.Argument = (uint32_t)ReadAddr;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Read block(s) in polling mode */
+ if(NumberOfBlocks > 1)
+ {
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_READ_MULT_BLOCK);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Poll on SDIO flags */
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR))
+ {
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF))
+ {
+ /* Read data from SDIO Rx FIFO */
+ for (count = 0; count < 8; count++)
+ {
+ *(tempbuff + count) = SDIO_ReadFIFO(hsd->Instance);
+ }
+
+ tempbuff += 8;
+ }
+ }
+ }
+ else
+ {
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_READ_SINGLE_BLOCK);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* In case of single block transfer, no need of stop transfer at all */
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
+ {
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF))
+ {
+ /* Read data from SDIO Rx FIFO */
+ for (count = 0; count < 8; count++)
+ {
+ *(tempbuff + count) = SDIO_ReadFIFO(hsd->Instance);
+ }
+
+ tempbuff += 8;
+ }
+ }
+ }
+
+ /* Send stop transmission command in case of multiblock read */
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1))
+ {
+ if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) ||\
+ (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
+ (hsd->CardType == HIGH_CAPACITY_SD_CARD))
+ {
+ /* Send stop transmission command */
+ errorState = HAL_SD_StopTransfer(hsd);
+ }
+ }
+
+ /* Get error state */
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
+
+ errorState = SD_DATA_TIMEOUT;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
+
+ errorState = SD_DATA_CRC_FAIL;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
+
+ errorState = SD_RX_OVERRUN;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
+
+ errorState = SD_START_BIT_ERR;
+
+ return errorState;
+ }
+
+ count = SD_DATATIMEOUT;
+
+ /* Empty FIFO if there is still any data */
+ while ((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (count > 0))
+ {
+ *tempbuff = SDIO_ReadFIFO(hsd->Instance);
+ tempbuff++;
+ count--;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ return errorState;
+}
+
+/**
+ * @brief Allows to write block(s) to a specified address in a card. The Data
+ * transfer is managed by polling mode.
+ * @param hsd: SD handle
+ * @param pWriteBuffer: pointer to the buffer that will contain the data to transmit
+ * @param WriteAddr: Address from where data is to be written
+ * @param BlockSize: SD card Data block size
+ * This parameter should be 512.
+ * @param NumberOfBlocks: Number of SD blocks to write
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ SDIO_DataInitTypeDef SDIO_DataInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t TotalNumberOfBytes = 0, bytestransferred = 0, count = 0, restwords = 0;
+ uint32_t *tempbuff = (uint32_t *)pWriteBuffer;
+ uint8_t cardstate = 0;
+
+ /* Initialize data control register */
+ hsd->Instance->DCTRL = 0;
+
+ if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
+ {
+ BlockSize = 512;
+ WriteAddr /= 512;
+ }
+
+ /* Set Block Size for Card */
+ SDIO_CmdInitStructure.Argument = (uint32_t)BlockSize;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SET_BLOCKLEN;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ if(NumberOfBlocks > 1)
+ {
+ /* Send CMD25 WRITE_MULT_BLOCK with argument data address */
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_WRITE_MULT_BLOCK;
+ }
+ else
+ {
+ /* Send CMD24 WRITE_SINGLE_BLOCK */
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_WRITE_SINGLE_BLOCK;
+ }
+
+ SDIO_CmdInitStructure.Argument = (uint32_t)WriteAddr;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ if(NumberOfBlocks > 1)
+ {
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_WRITE_MULT_BLOCK);
+ }
+ else
+ {
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_WRITE_SINGLE_BLOCK);
+ }
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Set total number of bytes to write */
+ TotalNumberOfBytes = NumberOfBlocks * BlockSize;
+
+ /* Configure the SD DPSM (Data Path State Machine) */
+ SDIO_DataInitStructure.DataTimeOut = SD_DATATIMEOUT;
+ SDIO_DataInitStructure.DataLength = NumberOfBlocks * BlockSize;
+ SDIO_DataInitStructure.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
+ SDIO_DataInitStructure.TransferDir = SDIO_TRANSFER_DIR_TO_CARD;
+ SDIO_DataInitStructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK;
+ SDIO_DataInitStructure.DPSM = SDIO_DPSM_ENABLE;
+ SDIO_DataConfig(hsd->Instance, &SDIO_DataInitStructure);
+
+ /* Write block(s) in polling mode */
+ if(NumberOfBlocks > 1)
+ {
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR))
+ {
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE))
+ {
+ if ((TotalNumberOfBytes - bytestransferred) < 32)
+ {
+ restwords = ((TotalNumberOfBytes - bytestransferred) % 4 == 0) ? ((TotalNumberOfBytes - bytestransferred) / 4) : (( TotalNumberOfBytes - bytestransferred) / 4 + 1);
+
+ /* Write data to SDIO Tx FIFO */
+ for (count = 0; count < restwords; count++)
+ {
+ SDIO_WriteFIFO(hsd->Instance, tempbuff);
+ tempbuff++;
+ bytestransferred += 4;
+ }
+ }
+ else
+ {
+ /* Write data to SDIO Tx FIFO */
+ for (count = 0; count < 8; count++)
+ {
+ SDIO_WriteFIFO(hsd->Instance, (tempbuff + count));
+ }
+
+ tempbuff += 8;
+ bytestransferred += 32;
+ }
+ }
+ }
+ }
+ else
+ {
+ /* In case of single data block transfer no need of stop command at all */
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
+ {
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE))
+ {
+ if ((TotalNumberOfBytes - bytestransferred) < 32)
+ {
+ restwords = ((TotalNumberOfBytes - bytestransferred) % 4 == 0) ? ((TotalNumberOfBytes - bytestransferred) / 4) : (( TotalNumberOfBytes - bytestransferred) / 4 + 1);
+
+ /* Write data to SDIO Tx FIFO */
+ for (count = 0; count < restwords; count++)
+ {
+ SDIO_WriteFIFO(hsd->Instance, tempbuff);
+ tempbuff++;
+ bytestransferred += 4;
+ }
+ }
+ else
+ {
+ /* Write data to SDIO Tx FIFO */
+ for (count = 0; count < 8; count++)
+ {
+ SDIO_WriteFIFO(hsd->Instance, (tempbuff + count));
+ }
+
+ tempbuff += 8;
+ bytestransferred += 32;
+ }
+ }
+ }
+ }
+
+ /* Send stop transmission command in case of multiblock write */
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1))
+ {
+ if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
+ (hsd->CardType == HIGH_CAPACITY_SD_CARD))
+ {
+ /* Send stop transmission command */
+ errorState = HAL_SD_StopTransfer(hsd);
+ }
+ }
+
+ /* Get error state */
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
+
+ errorState = SD_DATA_TIMEOUT;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
+
+ errorState = SD_DATA_CRC_FAIL;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_TXUNDERR);
+
+ errorState = SD_TX_UNDERRUN;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
+
+ errorState = SD_START_BIT_ERR;
+
+ return errorState;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ /* Wait till the card is in programming state */
+ errorState = SD_IsCardProgramming(hsd, &cardstate);
+
+ while ((errorState == SD_OK) && ((cardstate == SD_CARD_PROGRAMMING) || (cardstate == SD_CARD_RECEIVING)))
+ {
+ errorState = SD_IsCardProgramming(hsd, &cardstate);
+ }
+
+ return errorState;
+}
+
+/**
+ * @brief Reads block(s) from a specified address in a card. The Data transfer
+ * is managed by DMA mode.
+ * @note This API should be followed by the function HAL_SD_CheckReadOperation()
+ * to check the completion of the read process
+ * @param hsd: SD handle
+ * @param pReadBuffer: Pointer to the buffer that will contain the received data
+ * @param ReadAddr: Address from where data is to be read
+ * @param BlockSize: SD card Data block size
+ * This paramater should be 512.
+ * @param NumberOfBlocks: Number of blocks to read.
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ SDIO_DataInitTypeDef SDIO_DataInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ /* Initialize data control register */
+ hsd->Instance->DCTRL = 0;
+
+ /* Initialize handle flags */
+ hsd->SdTransferCplt = 0;
+ hsd->DmaTransferCplt = 0;
+ hsd->SdTransferErr = SD_OK;
+
+ /* Initialize SD Read operation */
+ if(NumberOfBlocks > 1)
+ {
+ hsd->SdOperation = SD_READ_MULTIPLE_BLOCK;
+ }
+ else
+ {
+ hsd->SdOperation = SD_READ_SINGLE_BLOCK;
+ }
+
+ /* Enable transfer interrupts */
+ __HAL_SD_SDIO_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL |\
+ SDIO_IT_DTIMEOUT |\
+ SDIO_IT_DATAEND |\
+ SDIO_IT_RXOVERR |\
+ SDIO_IT_STBITERR));
+
+ /* Enable SDIO DMA transfer */
+ __HAL_SD_SDIO_DMA_ENABLE();
+
+ /* Configure DMA user callbacks */
+ hsd->hdmarx->XferCpltCallback = SD_DMA_RxCplt;
+ hsd->hdmarx->XferErrorCallback = SD_DMA_RxError;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hsd->hdmarx, (uint32_t)SDIO_FIFO_ADDRESS, (uint32_t)pReadBuffer, (uint32_t)(BlockSize * NumberOfBlocks));
+
+ if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
+ {
+ BlockSize = 512;
+ ReadAddr /= 512;
+ }
+
+ /* Set Block Size for Card */
+ SDIO_CmdInitStructure.Argument = (uint32_t)BlockSize;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SET_BLOCKLEN;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Configure the SD DPSM (Data Path State Machine) */
+ SDIO_DataInitStructure.DataTimeOut = SD_DATATIMEOUT;
+ SDIO_DataInitStructure.DataLength = BlockSize * NumberOfBlocks;
+ SDIO_DataInitStructure.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
+ SDIO_DataInitStructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO;
+ SDIO_DataInitStructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK;
+ SDIO_DataInitStructure.DPSM = SDIO_DPSM_ENABLE;
+ SDIO_DataConfig(hsd->Instance, &SDIO_DataInitStructure);
+
+ /* Check number of blocks command */
+ if(NumberOfBlocks > 1)
+ {
+ /* Send CMD18 READ_MULT_BLOCK with argument data address */
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_READ_MULT_BLOCK;
+ }
+ else
+ {
+ /* Send CMD17 READ_SINGLE_BLOCK */
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_READ_SINGLE_BLOCK;
+ }
+
+ SDIO_CmdInitStructure.Argument = (uint32_t)ReadAddr;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ if(NumberOfBlocks > 1)
+ {
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_READ_MULT_BLOCK);
+ }
+ else
+ {
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_READ_SINGLE_BLOCK);
+ }
+
+ /* Update the SD transfer error in SD handle */
+ hsd->SdTransferErr = errorState;
+
+ return errorState;
+}
+
+
+/**
+ * @brief Writes block(s) to a specified address in a card. The Data transfer
+ * is managed by DMA mode.
+ * @note This API should be followed by the function HAL_SD_CheckWriteOperation()
+ * to check the completion of the write process (by SD current status polling).
+ * @param hsd: SD handle
+ * @param pWriteBuffer: pointer to the buffer that will contain the data to transmit
+ * @param WriteAddr: Address from where data is to be read
+ * @param BlockSize: the SD card Data block size
+ * This parameter should be 512.
+ * @param NumberOfBlocks: Number of blocks to write
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ SDIO_DataInitTypeDef SDIO_DataInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ /* Initialize data control register */
+ hsd->Instance->DCTRL = 0;
+
+ /* Initialize handle flags */
+ hsd->SdTransferCplt = 0;
+ hsd->DmaTransferCplt = 0;
+ hsd->SdTransferErr = SD_OK;
+
+ /* Initialize SD Write operation */
+ if(NumberOfBlocks > 1)
+ {
+ hsd->SdOperation = SD_WRITE_MULTIPLE_BLOCK;
+ }
+ else
+ {
+ hsd->SdOperation = SD_WRITE_SINGLE_BLOCK;
+ }
+
+ /* Enable transfer interrupts */
+ __HAL_SD_SDIO_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL |\
+ SDIO_IT_DTIMEOUT |\
+ SDIO_IT_DATAEND |\
+ SDIO_IT_TXUNDERR |\
+ SDIO_IT_STBITERR));
+
+ /* Configure DMA user callbacks */
+ hsd->hdmatx->XferCpltCallback = SD_DMA_TxCplt;
+ hsd->hdmatx->XferErrorCallback = SD_DMA_TxError;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hsd->hdmatx, (uint32_t)pWriteBuffer, (uint32_t)SDIO_FIFO_ADDRESS, (uint32_t)(BlockSize * NumberOfBlocks));
+
+ /* Enable SDIO DMA transfer */
+ __HAL_SD_SDIO_DMA_ENABLE();
+
+ if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
+ {
+ BlockSize = 512;
+ WriteAddr /= 512;
+ }
+
+ /* Set Block Size for Card */
+ SDIO_CmdInitStructure.Argument = (uint32_t)BlockSize;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SET_BLOCKLEN;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Check number of blocks command */
+ if(NumberOfBlocks <= 1)
+ {
+ /* Send CMD24 WRITE_SINGLE_BLOCK */
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_WRITE_SINGLE_BLOCK;
+ }
+ else
+ {
+ /* Send CMD25 WRITE_MULT_BLOCK with argument data address */
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_WRITE_MULT_BLOCK;
+ }
+
+ SDIO_CmdInitStructure.Argument = (uint32_t)WriteAddr;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ if(NumberOfBlocks > 1)
+ {
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_WRITE_MULT_BLOCK);
+ }
+ else
+ {
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_WRITE_SINGLE_BLOCK);
+ }
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Configure the SD DPSM (Data Path State Machine) */
+ SDIO_DataInitStructure.DataTimeOut = SD_DATATIMEOUT;
+ SDIO_DataInitStructure.DataLength = BlockSize * NumberOfBlocks;
+ SDIO_DataInitStructure.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
+ SDIO_DataInitStructure.TransferDir = SDIO_TRANSFER_DIR_TO_CARD;
+ SDIO_DataInitStructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK;
+ SDIO_DataInitStructure.DPSM = SDIO_DPSM_ENABLE;
+ SDIO_DataConfig(hsd->Instance, &SDIO_DataInitStructure);
+
+ hsd->SdTransferErr = errorState;
+
+ return errorState;
+}
+
+/**
+ * @brief This function waits until the SD DMA data read transfer is finished.
+ * This API should be called after HAL_SD_ReadBlocks_DMA() function
+ * to insure that all data sent by the card is already transferred by the
+ * DMA controller.
+ * @param hsd: SD handle
+ * @param Timeout: Timeout duration
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_CheckReadOperation(SD_HandleTypeDef *hsd, uint32_t Timeout)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t timeout = Timeout;
+ uint32_t tmp1, tmp2;
+ HAL_SD_ErrorTypedef tmp3;
+
+ /* Wait for DMA/SD transfer end or SD error variables to be in SD handle */
+ tmp1 = hsd->DmaTransferCplt;
+ tmp2 = hsd->SdTransferCplt;
+ tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr;
+
+ while ((tmp1 == 0) && (tmp2 == 0) && (tmp3 == SD_OK) && (timeout > 0))
+ {
+ tmp1 = hsd->DmaTransferCplt;
+ tmp2 = hsd->SdTransferCplt;
+ tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr;
+ timeout--;
+ }
+
+ timeout = Timeout;
+
+ /* Wait until the Rx transfer is no longer active */
+ while((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXACT)) && (timeout > 0))
+ {
+ timeout--;
+ }
+
+ /* Send stop command in multiblock read */
+ if (hsd->SdOperation == SD_READ_MULTIPLE_BLOCK)
+ {
+ errorState = HAL_SD_StopTransfer(hsd);
+ }
+
+ if ((timeout == 0) && (errorState == SD_OK))
+ {
+ errorState = SD_DATA_TIMEOUT;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ /* Return error state */
+ if (hsd->SdTransferErr != SD_OK)
+ {
+ return (HAL_SD_ErrorTypedef)(hsd->SdTransferErr);
+ }
+
+ return errorState;
+}
+
+/**
+ * @brief This function waits until the SD DMA data write transfer is finished.
+ * This API should be called after HAL_SD_WriteBlocks_DMA() function
+ * to insure that all data sent by the card is already transferred by the
+ * DMA controller.
+ * @param hsd: SD handle
+ * @param Timeout: Timeout duration
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_CheckWriteOperation(SD_HandleTypeDef *hsd, uint32_t Timeout)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t timeout = Timeout;
+ uint32_t tmp1, tmp2;
+ HAL_SD_ErrorTypedef tmp3;
+
+ /* Wait for DMA/SD transfer end or SD error variables to be in SD handle */
+ tmp1 = hsd->DmaTransferCplt;
+ tmp2 = hsd->SdTransferCplt;
+ tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr;
+
+ while ((tmp1 == 0) && (tmp2 == 0) && (tmp3 == SD_OK) && (timeout > 0))
+ {
+ tmp1 = hsd->DmaTransferCplt;
+ tmp2 = hsd->SdTransferCplt;
+ tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr;
+ timeout--;
+ }
+
+ timeout = Timeout;
+
+ /* Wait until the Tx transfer is no longer active */
+ while((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXACT)) && (timeout > 0))
+ {
+ timeout--;
+ }
+
+ /* Send stop command in multiblock write */
+ if (hsd->SdOperation == SD_WRITE_MULTIPLE_BLOCK)
+ {
+ errorState = HAL_SD_StopTransfer(hsd);
+ }
+
+ if ((timeout == 0) && (errorState == SD_OK))
+ {
+ errorState = SD_DATA_TIMEOUT;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ /* Return error state */
+ if (hsd->SdTransferErr != SD_OK)
+ {
+ return (HAL_SD_ErrorTypedef)(hsd->SdTransferErr);
+ }
+
+ /* Wait until write is complete */
+ while(HAL_SD_GetStatus(hsd) != SD_TRANSFER_OK)
+ {
+ }
+
+ return errorState;
+}
+
+/**
+ * @brief Erases the specified memory area of the given SD card.
+ * @param hsd: SD handle
+ * @param startaddr: Start byte address
+ * @param endaddr: End byte address
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint64_t startaddr, uint64_t endaddr)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+
+ uint32_t delay = 0;
+ __IO uint32_t maxdelay = 0;
+ uint8_t cardstate = 0;
+
+ /* Check if the card command class supports erase command */
+ if (((hsd->CSD[1] >> 20) & SD_CCCC_ERASE) == 0)
+ {
+ errorState = SD_REQUEST_NOT_APPLICABLE;
+
+ return errorState;
+ }
+
+ /* Get max delay value */
+ maxdelay = 120000 / (((hsd->Instance->CLKCR) & 0xFF) + 2);
+
+ if((SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED)
+ {
+ errorState = SD_LOCK_UNLOCK_FAILED;
+
+ return errorState;
+ }
+
+ /* Get start and end block for high capacity cards */
+ if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
+ {
+ startaddr /= 512;
+ endaddr /= 512;
+ }
+
+ /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */
+ if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
+ (hsd->CardType == HIGH_CAPACITY_SD_CARD))
+ {
+ /* Send CMD32 SD_ERASE_GRP_START with argument as addr */
+ SDIO_CmdInitStructure.Argument =(uint32_t)startaddr;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SD_ERASE_GRP_START;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SD_ERASE_GRP_START);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Send CMD33 SD_ERASE_GRP_END with argument as addr */
+ SDIO_CmdInitStructure.Argument = (uint32_t)endaddr;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SD_ERASE_GRP_END;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SD_ERASE_GRP_END);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+ }
+
+ /* Send CMD38 ERASE */
+ SDIO_CmdInitStructure.Argument = 0;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_ERASE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_ERASE);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ for (; delay < maxdelay; delay++)
+ {
+ }
+
+ /* Wait untill the card is in programming state */
+ errorState = SD_IsCardProgramming(hsd, &cardstate);
+
+ delay = SD_DATATIMEOUT;
+
+ while ((delay > 0) && (errorState == SD_OK) && ((cardstate == SD_CARD_PROGRAMMING) || (cardstate == SD_CARD_RECEIVING)))
+ {
+ errorState = SD_IsCardProgramming(hsd, &cardstate);
+ delay--;
+ }
+
+ return errorState;
+}
+
+/**
+ * @brief This function handles SD card interrupt request.
+ * @param hsd: SD handle
+ * @retval None
+ */
+void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd)
+{
+ /* Check for SDIO interrupt flags */
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_DATAEND))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_IT_DATAEND);
+
+ /* SD transfer is complete */
+ hsd->SdTransferCplt = 1;
+
+ /* No transfer error */
+ hsd->SdTransferErr = SD_OK;
+
+ HAL_SD_XferCpltCallback(hsd);
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_DCRCFAIL))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
+
+ hsd->SdTransferErr = SD_DATA_CRC_FAIL;
+
+ HAL_SD_XferErrorCallback(hsd);
+
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_DTIMEOUT))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
+
+ hsd->SdTransferErr = SD_DATA_TIMEOUT;
+
+ HAL_SD_XferErrorCallback(hsd);
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_RXOVERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
+
+ hsd->SdTransferErr = SD_RX_OVERRUN;
+
+ HAL_SD_XferErrorCallback(hsd);
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_TXUNDERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_TXUNDERR);
+
+ hsd->SdTransferErr = SD_TX_UNDERRUN;
+
+ HAL_SD_XferErrorCallback(hsd);
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_STBITERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
+
+ hsd->SdTransferErr = SD_START_BIT_ERR;
+
+ HAL_SD_XferErrorCallback(hsd);
+ }
+
+ /* Disable all SDIO peripheral interrupt sources */
+ __HAL_SD_SDIO_DISABLE_IT(hsd, SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND |\
+ SDIO_IT_TXFIFOHE | SDIO_IT_RXFIFOHF | SDIO_IT_TXUNDERR |\
+ SDIO_IT_RXOVERR | SDIO_IT_STBITERR);
+}
+
+
+/**
+ * @brief SD end of transfer callback.
+ * @param hsd: SD handle
+ * @retval None
+ */
+__weak void HAL_SD_XferCpltCallback(SD_HandleTypeDef *hsd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SD_XferCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief SD Transfer Error callback.
+ * @param hsd: SD handle
+ * @retval None
+ */
+__weak void HAL_SD_XferErrorCallback(SD_HandleTypeDef *hsd)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SD_XferErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief SD Transfer complete Rx callback in non blocking mode.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+__weak void HAL_SD_DMA_RxCpltCallback(DMA_HandleTypeDef *hdma)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SD_DMA_RxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief SD DMA transfer complete Rx error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+__weak void HAL_SD_DMA_RxErrorCallback(DMA_HandleTypeDef *hdma)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SD_DMA_RxErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief SD Transfer complete Tx callback in non blocking mode.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+__weak void HAL_SD_DMA_TxCpltCallback(DMA_HandleTypeDef *hdma)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SD_DMA_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief SD DMA transfer complete error Tx callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+__weak void HAL_SD_DMA_TxErrorCallback(DMA_HandleTypeDef *hdma)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SD_DMA_TxErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SD_Group3 Peripheral Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the SD card
+ operations.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns information about specific card.
+ * @param hsd: SD handle
+ * @param pCardInfo: Pointer to a HAL_SD_CardInfoTypedef structure that
+ * contains all SD cardinformation
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_Get_CardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *pCardInfo)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t tmp = 0;
+
+ pCardInfo->CardType = (uint8_t)(hsd->CardType);
+ pCardInfo->RCA = (uint16_t)(hsd->RCA);
+
+ /* Byte 0 */
+ tmp = (hsd->CSD[0] & 0xFF000000) >> 24;
+ pCardInfo->SD_csd.CSDStruct = (uint8_t)((tmp & 0xC0) >> 6);
+ pCardInfo->SD_csd.SysSpecVersion = (uint8_t)((tmp & 0x3C) >> 2);
+ pCardInfo->SD_csd.Reserved1 = tmp & 0x03;
+
+ /* Byte 1 */
+ tmp = (hsd->CSD[0] & 0x00FF0000) >> 16;
+ pCardInfo->SD_csd.TAAC = (uint8_t)tmp;
+
+ /* Byte 2 */
+ tmp = (hsd->CSD[0] & 0x0000FF00) >> 8;
+ pCardInfo->SD_csd.NSAC = (uint8_t)tmp;
+
+ /* Byte 3 */
+ tmp = hsd->CSD[0] & 0x000000FF;
+ pCardInfo->SD_csd.MaxBusClkFrec = (uint8_t)tmp;
+
+ /* Byte 4 */
+ tmp = (hsd->CSD[1] & 0xFF000000) >> 24;
+ pCardInfo->SD_csd.CardComdClasses = (uint16_t)(tmp << 4);
+
+ /* Byte 5 */
+ tmp = (hsd->CSD[1] & 0x00FF0000) >> 16;
+ pCardInfo->SD_csd.CardComdClasses |= (uint16_t)((tmp & 0xF0) >> 4);
+ pCardInfo->SD_csd.RdBlockLen = (uint8_t)(tmp & 0x0F);
+
+ /* Byte 6 */
+ tmp = (hsd->CSD[1] & 0x0000FF00) >> 8;
+ pCardInfo->SD_csd.PartBlockRead = (uint8_t)((tmp & 0x80) >> 7);
+ pCardInfo->SD_csd.WrBlockMisalign = (uint8_t)((tmp & 0x40) >> 6);
+ pCardInfo->SD_csd.RdBlockMisalign = (uint8_t)((tmp & 0x20) >> 5);
+ pCardInfo->SD_csd.DSRImpl = (uint8_t)((tmp & 0x10) >> 4);
+ pCardInfo->SD_csd.Reserved2 = 0; /*!< Reserved */
+
+ if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0))
+ {
+ pCardInfo->SD_csd.DeviceSize = (tmp & 0x03) << 10;
+
+ /* Byte 7 */
+ tmp = (uint8_t)(hsd->CSD[1] & 0x000000FF);
+ pCardInfo->SD_csd.DeviceSize |= (tmp) << 2;
+
+ /* Byte 8 */
+ tmp = (uint8_t)((hsd->CSD[2] & 0xFF000000) >> 24);
+ pCardInfo->SD_csd.DeviceSize |= (tmp & 0xC0) >> 6;
+
+ pCardInfo->SD_csd.MaxRdCurrentVDDMin = (tmp & 0x38) >> 3;
+ pCardInfo->SD_csd.MaxRdCurrentVDDMax = (tmp & 0x07);
+
+ /* Byte 9 */
+ tmp = (uint8_t)((hsd->CSD[2] & 0x00FF0000) >> 16);
+ pCardInfo->SD_csd.MaxWrCurrentVDDMin = (tmp & 0xE0) >> 5;
+ pCardInfo->SD_csd.MaxWrCurrentVDDMax = (tmp & 0x1C) >> 2;
+ pCardInfo->SD_csd.DeviceSizeMul = (tmp & 0x03) << 1;
+ /* Byte 10 */
+ tmp = (uint8_t)((hsd->CSD[2] & 0x0000FF00) >> 8);
+ pCardInfo->SD_csd.DeviceSizeMul |= (tmp & 0x80) >> 7;
+
+ pCardInfo->CardCapacity = (pCardInfo->SD_csd.DeviceSize + 1) ;
+ pCardInfo->CardCapacity *= (1 << (pCardInfo->SD_csd.DeviceSizeMul + 2));
+ pCardInfo->CardBlockSize = 1 << (pCardInfo->SD_csd.RdBlockLen);
+ pCardInfo->CardCapacity *= pCardInfo->CardBlockSize;
+ }
+ else if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
+ {
+ /* Byte 7 */
+ tmp = (uint8_t)(hsd->CSD[1] & 0x000000FF);
+ pCardInfo->SD_csd.DeviceSize = (tmp & 0x3F) << 16;
+
+ /* Byte 8 */
+ tmp = (uint8_t)((hsd->CSD[2] & 0xFF000000) >> 24);
+
+ pCardInfo->SD_csd.DeviceSize |= (tmp << 8);
+
+ /* Byte 9 */
+ tmp = (uint8_t)((hsd->CSD[2] & 0x00FF0000) >> 16);
+
+ pCardInfo->SD_csd.DeviceSize |= (tmp);
+
+ /* Byte 10 */
+ tmp = (uint8_t)((hsd->CSD[2] & 0x0000FF00) >> 8);
+
+ pCardInfo->CardCapacity = ((pCardInfo->SD_csd.DeviceSize + 1)) * 512 * 1024;
+ pCardInfo->CardBlockSize = 512;
+ }
+
+ pCardInfo->SD_csd.EraseGrSize = (tmp & 0x40) >> 6;
+ pCardInfo->SD_csd.EraseGrMul = (tmp & 0x3F) << 1;
+
+ /* Byte 11 */
+ tmp = (uint8_t)(hsd->CSD[2] & 0x000000FF);
+ pCardInfo->SD_csd.EraseGrMul |= (tmp & 0x80) >> 7;
+ pCardInfo->SD_csd.WrProtectGrSize = (tmp & 0x7F);
+
+ /* Byte 12 */
+ tmp = (uint8_t)((hsd->CSD[3] & 0xFF000000) >> 24);
+ pCardInfo->SD_csd.WrProtectGrEnable = (tmp & 0x80) >> 7;
+ pCardInfo->SD_csd.ManDeflECC = (tmp & 0x60) >> 5;
+ pCardInfo->SD_csd.WrSpeedFact = (tmp & 0x1C) >> 2;
+ pCardInfo->SD_csd.MaxWrBlockLen = (tmp & 0x03) << 2;
+
+ /* Byte 13 */
+ tmp = (uint8_t)((hsd->CSD[3] & 0x00FF0000) >> 16);
+ pCardInfo->SD_csd.MaxWrBlockLen |= (tmp & 0xC0) >> 6;
+ pCardInfo->SD_csd.WriteBlockPaPartial = (tmp & 0x20) >> 5;
+ pCardInfo->SD_csd.Reserved3 = 0;
+ pCardInfo->SD_csd.ContentProtectAppli = (tmp & 0x01);
+
+ /* Byte 14 */
+ tmp = (uint8_t)((hsd->CSD[3] & 0x0000FF00) >> 8);
+ pCardInfo->SD_csd.FileFormatGrouop = (tmp & 0x80) >> 7;
+ pCardInfo->SD_csd.CopyFlag = (tmp & 0x40) >> 6;
+ pCardInfo->SD_csd.PermWrProtect = (tmp & 0x20) >> 5;
+ pCardInfo->SD_csd.TempWrProtect = (tmp & 0x10) >> 4;
+ pCardInfo->SD_csd.FileFormat = (tmp & 0x0C) >> 2;
+ pCardInfo->SD_csd.ECC = (tmp & 0x03);
+
+ /* Byte 15 */
+ tmp = (uint8_t)(hsd->CSD[3] & 0x000000FF);
+ pCardInfo->SD_csd.CSD_CRC = (tmp & 0xFE) >> 1;
+ pCardInfo->SD_csd.Reserved4 = 1;
+
+ /* Byte 0 */
+ tmp = (uint8_t)((hsd->CID[0] & 0xFF000000) >> 24);
+ pCardInfo->SD_cid.ManufacturerID = tmp;
+
+ /* Byte 1 */
+ tmp = (uint8_t)((hsd->CID[0] & 0x00FF0000) >> 16);
+ pCardInfo->SD_cid.OEM_AppliID = tmp << 8;
+
+ /* Byte 2 */
+ tmp = (uint8_t)((hsd->CID[0] & 0x000000FF00) >> 8);
+ pCardInfo->SD_cid.OEM_AppliID |= tmp;
+
+ /* Byte 3 */
+ tmp = (uint8_t)(hsd->CID[0] & 0x000000FF);
+ pCardInfo->SD_cid.ProdName1 = tmp << 24;
+
+ /* Byte 4 */
+ tmp = (uint8_t)((hsd->CID[1] & 0xFF000000) >> 24);
+ pCardInfo->SD_cid.ProdName1 |= tmp << 16;
+
+ /* Byte 5 */
+ tmp = (uint8_t)((hsd->CID[1] & 0x00FF0000) >> 16);
+ pCardInfo->SD_cid.ProdName1 |= tmp << 8;
+
+ /* Byte 6 */
+ tmp = (uint8_t)((hsd->CID[1] & 0x0000FF00) >> 8);
+ pCardInfo->SD_cid.ProdName1 |= tmp;
+
+ /* Byte 7 */
+ tmp = (uint8_t)(hsd->CID[1] & 0x000000FF);
+ pCardInfo->SD_cid.ProdName2 = tmp;
+
+ /* Byte 8 */
+ tmp = (uint8_t)((hsd->CID[2] & 0xFF000000) >> 24);
+ pCardInfo->SD_cid.ProdRev = tmp;
+
+ /* Byte 9 */
+ tmp = (uint8_t)((hsd->CID[2] & 0x00FF0000) >> 16);
+ pCardInfo->SD_cid.ProdSN = tmp << 24;
+
+ /* Byte 10 */
+ tmp = (uint8_t)((hsd->CID[2] & 0x0000FF00) >> 8);
+ pCardInfo->SD_cid.ProdSN |= tmp << 16;
+
+ /* Byte 11 */
+ tmp = (uint8_t)(hsd->CID[2] & 0x000000FF);
+ pCardInfo->SD_cid.ProdSN |= tmp << 8;
+
+ /* Byte 12 */
+ tmp = (uint8_t)((hsd->CID[3] & 0xFF000000) >> 24);
+ pCardInfo->SD_cid.ProdSN |= tmp;
+
+ /* Byte 13 */
+ tmp = (uint8_t)((hsd->CID[3] & 0x00FF0000) >> 16);
+ pCardInfo->SD_cid.Reserved1 |= (tmp & 0xF0) >> 4;
+ pCardInfo->SD_cid.ManufactDate = (tmp & 0x0F) << 8;
+
+ /* Byte 14 */
+ tmp = (uint8_t)((hsd->CID[3] & 0x0000FF00) >> 8);
+ pCardInfo->SD_cid.ManufactDate |= tmp;
+
+ /* Byte 15 */
+ tmp = (uint8_t)(hsd->CID[3] & 0x000000FF);
+ pCardInfo->SD_cid.CID_CRC = (tmp & 0xFE) >> 1;
+ pCardInfo->SD_cid.Reserved2 = 1;
+
+ return errorState;
+}
+
+/**
+ * @brief Enables wide bus operation for the requested card if supported by
+ * card.
+ * @param hsd: SD handle
+ * @param WideMode: Specifies the SD card wide bus mode
+ * This parameter can be one of the following values:
+ * @arg SDIO_BUS_WIDE_8B: 8-bit data transfer (Only for MMC)
+ * @arg SDIO_BUS_WIDE_4B: 4-bit data transfer
+ * @arg SDIO_BUS_WIDE_1B: 1-bit data transfer
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_WideBusOperation_Config(SD_HandleTypeDef *hsd, uint32_t WideMode)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ SDIO_InitTypeDef Init;
+
+ /* MMC Card does not support this feature */
+ if (hsd->CardType == MULTIMEDIA_CARD)
+ {
+ errorState = SD_UNSUPPORTED_FEATURE;
+
+ return errorState;
+ }
+ else if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
+ (hsd->CardType == HIGH_CAPACITY_SD_CARD))
+ {
+ if (WideMode == SDIO_BUS_WIDE_8B)
+ {
+ errorState = SD_UNSUPPORTED_FEATURE;
+
+ return errorState;
+ }
+ else if (WideMode == SDIO_BUS_WIDE_4B)
+ {
+ errorState = SD_WideBus_Enable(hsd);
+
+ if (errorState == SD_OK)
+ {
+ /* Configure the SDIO peripheral */
+ Init.ClockEdge = SDIO_CLOCK_EDGE_RISING;
+ Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
+ Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE;
+ Init.BusWide = SDIO_BUS_WIDE_4B;
+ Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
+ Init.ClockDiv = SDIO_TRANSFER_CLK_DIV;
+
+ /* Configure SDIO peripheral interface */
+ SDIO_Init(hsd->Instance, Init);
+ }
+ }
+ else
+ {
+ errorState = SD_WideBus_Disable(hsd);
+
+ if (errorState == SD_OK)
+ {
+ /* Configure the SDIO peripheral */
+ Init.ClockEdge = SDIO_CLOCK_EDGE_RISING;
+ Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
+ Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE;
+ Init.BusWide = SDIO_BUS_WIDE_1B;
+ Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
+ Init.ClockDiv = SDIO_TRANSFER_CLK_DIV;
+
+ /* Configure SDIO peripheral interface */
+ SDIO_Init(hsd->Instance, Init);
+ }
+ }
+ }
+
+ return errorState;
+}
+
+/**
+ * @brief Aborts an ongoing data transfer.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_StopTransfer(SD_HandleTypeDef *hsd)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ /* Send CMD12 STOP_TRANSMISSION */
+ SDIO_CmdInitStructure.Argument = 0;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_STOP_TRANSMISSION;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_STOP_TRANSMISSION);
+
+ return errorState;
+}
+
+/**
+ * @brief Switches the SD card to High Speed mode.
+ * This API must be used after "Transfer State"
+ * @note This operation should be followed by the configuration
+ * of PLL to have SDIOCK clock between 67 and 75 MHz
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_HighSpeed (SD_HandleTypeDef *hsd)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ SDIO_DataInitTypeDef SDIO_DataInitStructure;
+
+ uint8_t SD_hs[64] = {0};
+ uint32_t SD_scr[2] = {0, 0};
+ uint32_t SD_SPEC = 0 ;
+ uint32_t count = 0, *tempbuff = (uint32_t *)SD_hs;
+
+ /* Initialize the Data control register */
+ hsd->Instance->DCTRL = 0;
+
+ /* Get SCR Register */
+ errorState = SD_FindSCR(hsd, SD_scr);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Test the Version supported by the card*/
+ SD_SPEC = (SD_scr[1] & 0x01000000) | (SD_scr[1] & 0x02000000);
+
+ if (SD_SPEC != SD_ALLZERO)
+ {
+ /* Set Block Size for Card */
+ SDIO_CmdInitStructure.Argument = (uint32_t)64;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SET_BLOCKLEN;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Configure the SD DPSM (Data Path State Machine) */
+ SDIO_DataInitStructure.DataTimeOut = SD_DATATIMEOUT;
+ SDIO_DataInitStructure.DataLength = 64;
+ SDIO_DataInitStructure.DataBlockSize = SDIO_DATABLOCK_SIZE_64B ;
+ SDIO_DataInitStructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO;
+ SDIO_DataInitStructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK;
+ SDIO_DataInitStructure.DPSM = SDIO_DPSM_ENABLE;
+ SDIO_DataConfig(hsd->Instance, &SDIO_DataInitStructure);
+
+ /* Send CMD6 switch mode */
+ SDIO_CmdInitStructure.Argument = 0x80FFFF01;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_HS_SWITCH;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_HS_SWITCH);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
+ {
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF))
+ {
+ for (count = 0; count < 8; count++)
+ {
+ *(tempbuff + count) = SDIO_ReadFIFO(hsd->Instance);
+ }
+
+ tempbuff += 8;
+ }
+ }
+
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
+
+ errorState = SD_DATA_TIMEOUT;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
+
+ errorState = SD_DATA_CRC_FAIL;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
+
+ errorState = SD_RX_OVERRUN;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
+
+ errorState = SD_START_BIT_ERR;
+
+ return errorState;
+ }
+
+ count = SD_DATATIMEOUT;
+
+ while ((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (count > 0))
+ {
+ *tempbuff = SDIO_ReadFIFO(hsd->Instance);
+ tempbuff++;
+ count--;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ /* Test if the switch mode HS is ok */
+ if ((SD_hs[13]& 2) != 2)
+ {
+ errorState = SD_UNSUPPORTED_FEATURE;
+ }
+ }
+
+ return errorState;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SD_Group4 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State functions #####
+ ==============================================================================
+ [..]
+ This subsection permits to get in runtime the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the current SD card's status.
+ * @param hsd: SD handle
+ * @param pSDstatus: Pointer to the buffer that will contain the SD card status
+ * SD Status register)
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ SDIO_DataInitTypeDef SDIO_DataInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t count = 0;
+
+ /* Check SD response */
+ if ((SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED)
+ {
+ errorState = SD_LOCK_UNLOCK_FAILED;
+
+ return errorState;
+ }
+
+ /* Set block size for card if it is not equal to current block size for card */
+ SDIO_CmdInitStructure.Argument = 64;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SET_BLOCKLEN;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Send CMD55 */
+ SDIO_CmdInitStructure.Argument = (uint32_t)(hsd->RCA << 16);
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_APP_CMD;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Configure the SD DPSM (Data Path State Machine) */
+ SDIO_DataInitStructure.DataTimeOut = SD_DATATIMEOUT;
+ SDIO_DataInitStructure.DataLength = 64;
+ SDIO_DataInitStructure.DataBlockSize = SDIO_DATABLOCK_SIZE_64B;
+ SDIO_DataInitStructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO;
+ SDIO_DataInitStructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK;
+ SDIO_DataInitStructure.DPSM = SDIO_DPSM_ENABLE;
+ SDIO_DataConfig(hsd->Instance, &SDIO_DataInitStructure);
+
+ /* Send ACMD13 (SD_APP_STAUS) with argument as card's RCA */
+ SDIO_CmdInitStructure.Argument = 0;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SD_APP_STAUS;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SD_APP_STAUS);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Get status data */
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
+ {
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF))
+ {
+ for (count = 0; count < 8; count++)
+ {
+ *(pSDstatus + count) = SDIO_ReadFIFO(hsd->Instance);
+ }
+
+ pSDstatus += 8;
+ }
+ }
+
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
+
+ errorState = SD_DATA_TIMEOUT;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
+
+ errorState = SD_DATA_CRC_FAIL;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
+
+ errorState = SD_RX_OVERRUN;
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
+
+ errorState = SD_START_BIT_ERR;
+
+ return errorState;
+ }
+
+ count = SD_DATATIMEOUT;
+ while ((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (count > 0))
+ {
+ *pSDstatus = SDIO_ReadFIFO(hsd->Instance);
+ pSDstatus++;
+ count--;
+ }
+
+ /* Clear all the static status flags*/
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ return errorState;
+}
+
+/**
+ * @brief Gets the current sd card data status.
+ * @param hsd: SD handle
+ * @retval Data Transfer state
+ */
+HAL_SD_TransferStateTypedef HAL_SD_GetStatus(SD_HandleTypeDef *hsd)
+{
+ HAL_SD_CardStateTypedef cardstate = SD_CARD_TRANSFER;
+
+ /* Get SD card state */
+ cardstate = SD_GetState(hsd);
+
+ /* Find SD status according to card state*/
+ if (cardstate == SD_CARD_TRANSFER)
+ {
+ return SD_TRANSFER_OK;
+ }
+ else if(cardstate == SD_CARD_ERROR)
+ {
+ return SD_TRANSFER_ERROR;
+ }
+ else
+ {
+ return SD_TRANSFER_BUSY;
+ }
+}
+
+/**
+ * @brief Gets the SD card status.
+ * @param hsd: SD handle
+ * @param pCardStatus: Pointer to the HAL_SD_CardStatusTypedef structure that
+ * will contain the SD card status information
+ * @retval SD Card error state
+ */
+HAL_SD_ErrorTypedef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypedef *pCardStatus)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t tmp = 0;
+ uint32_t SD_STATUS[16];
+
+ errorState = HAL_SD_SendSDStatus(hsd, SD_STATUS);
+
+ if (errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Byte 0 */
+ tmp = (SD_STATUS[0] & 0xC0) >> 6;
+ pCardStatus->DAT_BUS_WIDTH = (uint8_t)tmp;
+
+ /* Byte 0 */
+ tmp = (SD_STATUS[0] & 0x20) >> 5;
+ pCardStatus->SECURED_MODE = (uint8_t)tmp;
+
+ /* Byte 2 */
+ tmp = (SD_STATUS[2] & 0xFF);
+ pCardStatus->SD_CARD_TYPE = (uint8_t)(tmp << 8);
+
+ /* Byte 3 */
+ tmp = (SD_STATUS[3] & 0xFF);
+ pCardStatus->SD_CARD_TYPE |= (uint8_t)tmp;
+
+ /* Byte 4 */
+ tmp = (SD_STATUS[4] & 0xFF);
+ pCardStatus->SIZE_OF_PROTECTED_AREA = (uint8_t)(tmp << 24);
+
+ /* Byte 5 */
+ tmp = (SD_STATUS[5] & 0xFF);
+ pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)(tmp << 16);
+
+ /* Byte 6 */
+ tmp = (SD_STATUS[6] & 0xFF);
+ pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)(tmp << 8);
+
+ /* Byte 7 */
+ tmp = (SD_STATUS[7] & 0xFF);
+ pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)tmp;
+
+ /* Byte 8 */
+ tmp = (SD_STATUS[8] & 0xFF);
+ pCardStatus->SPEED_CLASS = (uint8_t)tmp;
+
+ /* Byte 9 */
+ tmp = (SD_STATUS[9] & 0xFF);
+ pCardStatus->PERFORMANCE_MOVE = (uint8_t)tmp;
+
+ /* Byte 10 */
+ tmp = (SD_STATUS[10] & 0xF0) >> 4;
+ pCardStatus->AU_SIZE = (uint8_t)tmp;
+
+ /* Byte 11 */
+ tmp = (SD_STATUS[11] & 0xFF);
+ pCardStatus->ERASE_SIZE = (uint8_t)(tmp << 8);
+
+ /* Byte 12 */
+ tmp = (SD_STATUS[12] & 0xFF);
+ pCardStatus->ERASE_SIZE |= (uint8_t)tmp;
+
+ /* Byte 13 */
+ tmp = (SD_STATUS[13] & 0xFC) >> 2;
+ pCardStatus->ERASE_TIMEOUT = (uint8_t)tmp;
+
+ /* Byte 13 */
+ tmp = (SD_STATUS[13] & 0x3);
+ pCardStatus->ERASE_OFFSET = (uint8_t)tmp;
+
+ return errorState;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief SD DMA transfer complete Rx callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void SD_DMA_RxCplt(DMA_HandleTypeDef *hdma)
+{
+ SD_HandleTypeDef *hsd = (SD_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* DMA transfer is complete */
+ hsd->DmaTransferCplt = 1;
+
+ /* Wait until SD transfer is complete */
+ while(hsd->SdTransferCplt == 0)
+ {
+ }
+
+ /* Transfer complete user callback */
+ HAL_SD_DMA_RxCpltCallback(hsd->hdmarx);
+}
+
+/**
+ * @brief SD DMA transfer Error Rx callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void SD_DMA_RxError(DMA_HandleTypeDef *hdma)
+{
+ SD_HandleTypeDef *hsd = (SD_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* Transfer complete user callback */
+ HAL_SD_DMA_RxErrorCallback(hsd->hdmarx);
+}
+
+/**
+ * @brief SD DMA transfer complete Tx callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void SD_DMA_TxCplt(DMA_HandleTypeDef *hdma)
+{
+ SD_HandleTypeDef *hsd = (SD_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ /* DMA transfer is complete */
+ hsd->DmaTransferCplt = 1;
+
+ /* Wait until SD transfer is complete */
+ while(hsd->SdTransferCplt == 0)
+ {
+ }
+
+ /* Transfer complete user callback */
+ HAL_SD_DMA_TxCpltCallback(hsd->hdmatx);
+}
+
+/**
+ * @brief SD DMA transfer Error Tx callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void SD_DMA_TxError(DMA_HandleTypeDef *hdma)
+{
+ SD_HandleTypeDef *hsd = ( SD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ /* Transfer complete user callback */
+ HAL_SD_DMA_TxErrorCallback(hsd->hdmatx);
+}
+
+/**
+ * @brief Returns the SD current state.
+ * @param hsd: SD handle
+ * @retval SD card current state
+ */
+static HAL_SD_CardStateTypedef SD_GetState(SD_HandleTypeDef *hsd)
+{
+ uint32_t resp1 = 0;
+
+ if (SD_SendStatus(hsd, &resp1) != SD_OK)
+ {
+ return SD_CARD_ERROR;
+ }
+ else
+ {
+ return (HAL_SD_CardStateTypedef)((resp1 >> 9) & 0x0F);
+ }
+}
+
+/**
+ * @brief Initializes all cards or single card as the case may be Card(s) come
+ * into standby state.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_Initialize_Cards(SD_HandleTypeDef *hsd)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint16_t sd_rca = 1;
+
+ if(SDIO_GetPowerState(hsd->Instance) == 0) /* Power off */
+ {
+ errorState = SD_REQUEST_NOT_APPLICABLE;
+
+ return errorState;
+ }
+
+ if(hsd->CardType != SECURE_DIGITAL_IO_CARD)
+ {
+ /* Send CMD2 ALL_SEND_CID */
+ SDIO_CmdInitStructure.Argument = 0;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_ALL_SEND_CID;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_LONG;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp2Error(hsd);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Get Card identification number data */
+ hsd->CID[0] = SDIO_GetResponse(SDIO_RESP1);
+ hsd->CID[1] = SDIO_GetResponse(SDIO_RESP2);
+ hsd->CID[2] = SDIO_GetResponse(SDIO_RESP3);
+ hsd->CID[3] = SDIO_GetResponse(SDIO_RESP4);
+ }
+
+ if((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
+ (hsd->CardType == SECURE_DIGITAL_IO_COMBO_CARD) || (hsd->CardType == HIGH_CAPACITY_SD_CARD))
+ {
+ /* Send CMD3 SET_REL_ADDR with argument 0 */
+ /* SD Card publishes its RCA. */
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SET_REL_ADDR;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp6Error(hsd, SD_CMD_SET_REL_ADDR, &sd_rca);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+ }
+
+ if (hsd->CardType != SECURE_DIGITAL_IO_CARD)
+ {
+ /* Get the SD card RCA */
+ hsd->RCA = sd_rca;
+
+ /* Send CMD9 SEND_CSD with argument as card's RCA */
+ SDIO_CmdInitStructure.Argument = (uint32_t)(hsd->RCA << 16);
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SEND_CSD;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_LONG;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp2Error(hsd);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Get Card Specific Data */
+ hsd->CSD[0] = SDIO_GetResponse(SDIO_RESP1);
+ hsd->CSD[1] = SDIO_GetResponse(SDIO_RESP2);
+ hsd->CSD[2] = SDIO_GetResponse(SDIO_RESP3);
+ hsd->CSD[3] = SDIO_GetResponse(SDIO_RESP4);
+ }
+
+ /* All cards are initialized */
+ return errorState;
+}
+
+/**
+ * @brief Selects od Deselects the corresponding card.
+ * @param hsd: SD handle
+ * @param addr: Address of the card to be selected
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_Select_Deselect(SD_HandleTypeDef *hsd, uint64_t addr)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ /* Send CMD7 SDIO_SEL_DESEL_CARD */
+ SDIO_CmdInitStructure.Argument = (uint32_t)addr;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SEL_DESEL_CARD;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SEL_DESEL_CARD);
+
+ return errorState;
+}
+
+/**
+ * @brief Enquires cards about their operating voltage and configures clock
+ * controls and stores SD information that will be needed in future
+ * in the SD handle.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_PowerON(SD_HandleTypeDef *hsd)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ __IO HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t response = 0, count = 0, validvoltage = 0;
+ uint32_t SDType = SD_STD_CAPACITY;
+
+ /* Power ON Sequence -------------------------------------------------------*/
+ /* Disable SDIO Clock */
+ __HAL_SD_SDIO_DISABLE();
+
+ /* Set Power State to ON */
+ SDIO_PowerState_ON(hsd->Instance);
+
+ /* Enable SDIO Clock */
+ __HAL_SD_SDIO_ENABLE();
+
+ /* CMD0: GO_IDLE_STATE -----------------------------------------------------*/
+ /* No CMD response required */
+ SDIO_CmdInitStructure.Argument = 0;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_GO_IDLE_STATE;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_NO;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdError(hsd);
+
+ if(errorState != SD_OK)
+ {
+ /* CMD Response TimeOut (wait for CMDSENT flag) */
+ return errorState;
+ }
+
+ /* CMD8: SEND_IF_COND ------------------------------------------------------*/
+ /* Send CMD8 to verify SD card interface operating condition */
+ /* Argument: - [31:12]: Reserved (shall be set to '0')
+ - [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V)
+ - [7:0]: Check Pattern (recommended 0xAA) */
+ /* CMD Response: R7 */
+ SDIO_CmdInitStructure.Argument = SD_CHECK_PATTERN;
+ SDIO_CmdInitStructure.CmdIndex = SD_SDIO_SEND_IF_COND;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp7Error(hsd);
+
+ if (errorState == SD_OK)
+ {
+ /* SD Card 2.0 */
+ hsd->CardType = STD_CAPACITY_SD_CARD_V2_0;
+ SDType = SD_HIGH_CAPACITY;
+ }
+
+ /* Send CMD55 */
+ SDIO_CmdInitStructure.Argument = 0;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_APP_CMD;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
+
+ /* If errorState is Command TimeOut, it is a MMC card */
+ /* If errorState is SD_OK it is a SD card: SD card 2.0 (voltage range mismatch)
+ or SD card 1.x */
+ if(errorState == SD_OK)
+ {
+ /* SD CARD */
+ /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */
+ while((!validvoltage) && (count < SD_MAX_VOLT_TRIAL))
+ {
+
+ /* SEND CMD55 APP_CMD with RCA as 0 */
+ SDIO_CmdInitStructure.Argument = 0;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_APP_CMD;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Send CMD41 */
+ SDIO_CmdInitStructure.Argument = SD_VOLTAGE_WINDOW_SD | SDType;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SD_APP_OP_COND;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp3Error(hsd);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Get command response */
+ response = SDIO_GetResponse(SDIO_RESP1);
+
+ /* Get operating voltage*/
+ validvoltage = (((response >> 31) == 1) ? 1 : 0);
+
+ count++;
+ }
+
+ if(count >= SD_MAX_VOLT_TRIAL)
+ {
+ errorState = SD_INVALID_VOLTRANGE;
+
+ return errorState;
+ }
+
+ if((response & SD_HIGH_CAPACITY) == SD_HIGH_CAPACITY) /* (response &= SD_HIGH_CAPACITY) */
+ {
+ hsd->CardType = HIGH_CAPACITY_SD_CARD;
+ }
+
+ } /* else MMC Card */
+
+ return errorState;
+}
+
+/**
+ * @brief Turns the SDIO output signals off.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_PowerOFF(SD_HandleTypeDef *hsd)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ /* Set Power State to OFF */
+ SDIO_PowerState_OFF(hsd->Instance);
+
+ return errorState;
+}
+
+/**
+ * @brief Returns the current card's status.
+ * @param hsd: SD handle
+ * @param pCardStatus: pointer to the buffer that will contain the SD card
+ * status (Card Status register)
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ if(pCardStatus == NULL)
+ {
+ errorState = SD_INVALID_PARAMETER;
+
+ return errorState;
+ }
+
+ /* Send Status command */
+ SDIO_CmdInitStructure.Argument = (uint32_t)(hsd->RCA << 16);
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SEND_STATUS;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SEND_STATUS);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Get SD card status */
+ *pCardStatus = SDIO_GetResponse(SDIO_RESP1);
+
+ return errorState;
+}
+
+/**
+ * @brief Checks for error conditions for CMD0.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_CmdError(SD_HandleTypeDef *hsd)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t timeout, tmp;
+
+ timeout = SDIO_CMD0TIMEOUT;
+
+ tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CMDSENT);
+
+ while((timeout > 0) && (!tmp))
+ {
+ tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CMDSENT);
+ timeout--;
+ }
+
+ if(timeout == 0)
+ {
+ errorState = SD_CMD_RSP_TIMEOUT;
+ return errorState;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ return errorState;
+}
+
+/**
+ * @brief Checks for error conditions for R7 response.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_CmdResp7Error(SD_HandleTypeDef *hsd)
+{
+ HAL_SD_ErrorTypedef errorState = SD_ERROR;
+ uint32_t timeout = SDIO_CMD0TIMEOUT, tmp;
+
+ tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT);
+
+ while((!tmp) && (timeout > 0))
+ {
+ tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT);
+ timeout--;
+ }
+
+ tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
+
+ if((timeout == 0) || tmp)
+ {
+ /* Card is not V2.0 compliant or card does not support the set voltage range */
+ errorState = SD_CMD_RSP_TIMEOUT;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
+
+ return errorState;
+ }
+
+ if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CMDREND))
+ {
+ /* Card is SD V2.0 compliant */
+ errorState = SD_OK;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CMDREND);
+
+ return errorState;
+ }
+
+ return errorState;
+}
+
+/**
+ * @brief Checks for error conditions for R1 response.
+ * @param hsd: SD handle
+ * @param SD_CMD: The sent command index
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_CmdResp1Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t response_R1;
+
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
+ {
+ }
+
+ if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
+ {
+ errorState = SD_CMD_RSP_TIMEOUT;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
+
+ return errorState;
+ }
+ else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL))
+ {
+ errorState = SD_CMD_CRC_FAIL;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL);
+
+ return errorState;
+ }
+
+ /* Check response received is of desired command */
+ if(SDIO_GetCommandResponse(hsd->Instance) != SD_CMD)
+ {
+ errorState = SD_ILLEGAL_CMD;
+
+ return errorState;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ /* We have received response, retrieve it for analysis */
+ response_R1 = SDIO_GetResponse(SDIO_RESP1);
+
+ if((response_R1 & SD_OCR_ERRORBITS) == SD_ALLZERO)
+ {
+ return errorState;
+ }
+
+ if((response_R1 & SD_OCR_ADDR_OUT_OF_RANGE) == SD_OCR_ADDR_OUT_OF_RANGE)
+ {
+ return(SD_ADDR_OUT_OF_RANGE);
+ }
+
+ if((response_R1 & SD_OCR_ADDR_MISALIGNED) == SD_OCR_ADDR_MISALIGNED)
+ {
+ return(SD_ADDR_MISALIGNED);
+ }
+
+ if((response_R1 & SD_OCR_BLOCK_LEN_ERR) == SD_OCR_BLOCK_LEN_ERR)
+ {
+ return(SD_BLOCK_LEN_ERR);
+ }
+
+ if((response_R1 & SD_OCR_ERASE_SEQ_ERR) == SD_OCR_ERASE_SEQ_ERR)
+ {
+ return(SD_ERASE_SEQ_ERR);
+ }
+
+ if((response_R1 & SD_OCR_BAD_ERASE_PARAM) == SD_OCR_BAD_ERASE_PARAM)
+ {
+ return(SD_BAD_ERASE_PARAM);
+ }
+
+ if((response_R1 & SD_OCR_WRITE_PROT_VIOLATION) == SD_OCR_WRITE_PROT_VIOLATION)
+ {
+ return(SD_WRITE_PROT_VIOLATION);
+ }
+
+ if((response_R1 & SD_OCR_LOCK_UNLOCK_FAILED) == SD_OCR_LOCK_UNLOCK_FAILED)
+ {
+ return(SD_LOCK_UNLOCK_FAILED);
+ }
+
+ if((response_R1 & SD_OCR_COM_CRC_FAILED) == SD_OCR_COM_CRC_FAILED)
+ {
+ return(SD_COM_CRC_FAILED);
+ }
+
+ if((response_R1 & SD_OCR_ILLEGAL_CMD) == SD_OCR_ILLEGAL_CMD)
+ {
+ return(SD_ILLEGAL_CMD);
+ }
+
+ if((response_R1 & SD_OCR_CARD_ECC_FAILED) == SD_OCR_CARD_ECC_FAILED)
+ {
+ return(SD_CARD_ECC_FAILED);
+ }
+
+ if((response_R1 & SD_OCR_CC_ERROR) == SD_OCR_CC_ERROR)
+ {
+ return(SD_CC_ERROR);
+ }
+
+ if((response_R1 & SD_OCR_GENERAL_UNKNOWN_ERROR) == SD_OCR_GENERAL_UNKNOWN_ERROR)
+ {
+ return(SD_GENERAL_UNKNOWN_ERROR);
+ }
+
+ if((response_R1 & SD_OCR_STREAM_READ_UNDERRUN) == SD_OCR_STREAM_READ_UNDERRUN)
+ {
+ return(SD_STREAM_READ_UNDERRUN);
+ }
+
+ if((response_R1 & SD_OCR_STREAM_WRITE_OVERRUN) == SD_OCR_STREAM_WRITE_OVERRUN)
+ {
+ return(SD_STREAM_WRITE_OVERRUN);
+ }
+
+ if((response_R1 & SD_OCR_CID_CSD_OVERWRIETE) == SD_OCR_CID_CSD_OVERWRIETE)
+ {
+ return(SD_CID_CSD_OVERWRITE);
+ }
+
+ if((response_R1 & SD_OCR_WP_ERASE_SKIP) == SD_OCR_WP_ERASE_SKIP)
+ {
+ return(SD_WP_ERASE_SKIP);
+ }
+
+ if((response_R1 & SD_OCR_CARD_ECC_DISABLED) == SD_OCR_CARD_ECC_DISABLED)
+ {
+ return(SD_CARD_ECC_DISABLED);
+ }
+
+ if((response_R1 & SD_OCR_ERASE_RESET) == SD_OCR_ERASE_RESET)
+ {
+ return(SD_ERASE_RESET);
+ }
+
+ if((response_R1 & SD_OCR_AKE_SEQ_ERROR) == SD_OCR_AKE_SEQ_ERROR)
+ {
+ return(SD_AKE_SEQ_ERROR);
+ }
+
+ return errorState;
+}
+
+/**
+ * @brief Checks for error conditions for R3 (OCR) response.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_CmdResp3Error(SD_HandleTypeDef *hsd)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ while (!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
+ {
+ }
+
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
+ {
+ errorState = SD_CMD_RSP_TIMEOUT;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
+
+ return errorState;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ return errorState;
+}
+
+/**
+ * @brief Checks for error conditions for R2 (CID or CSD) response.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_CmdResp2Error(SD_HandleTypeDef *hsd)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ while (!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
+ {
+ }
+
+ if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
+ {
+ errorState = SD_CMD_RSP_TIMEOUT;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
+
+ return errorState;
+ }
+ else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL))
+ {
+ errorState = SD_CMD_CRC_FAIL;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL);
+
+ return errorState;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ return errorState;
+}
+
+/**
+ * @brief Checks for error conditions for R6 (RCA) response.
+ * @param hsd: SD handle
+ * @param SD_CMD: The sent command index
+ * @param pRCA: Pointer to the variable that will contain the SD card relative
+ * address RCA
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_CmdResp6Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD, uint16_t *pRCA)
+{
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t response_R1;
+
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
+ {
+ }
+
+ if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
+ {
+ errorState = SD_CMD_RSP_TIMEOUT;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
+
+ return errorState;
+ }
+ else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL))
+ {
+ errorState = SD_CMD_CRC_FAIL;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL);
+
+ return errorState;
+ }
+
+ /* Check response received is of desired command */
+ if(SDIO_GetCommandResponse(hsd->Instance) != SD_CMD)
+ {
+ errorState = SD_ILLEGAL_CMD;
+
+ return errorState;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ /* We have received response, retrieve it. */
+ response_R1 = SDIO_GetResponse(SDIO_RESP1);
+
+ if((response_R1 & (SD_R6_GENERAL_UNKNOWN_ERROR | SD_R6_ILLEGAL_CMD | SD_R6_COM_CRC_FAILED)) == SD_ALLZERO)
+ {
+ *pRCA = (uint16_t) (response_R1 >> 16);
+
+ return errorState;
+ }
+
+ if((response_R1 & SD_R6_GENERAL_UNKNOWN_ERROR) == SD_R6_GENERAL_UNKNOWN_ERROR)
+ {
+ return(SD_GENERAL_UNKNOWN_ERROR);
+ }
+
+ if((response_R1 & SD_R6_ILLEGAL_CMD) == SD_R6_ILLEGAL_CMD)
+ {
+ return(SD_ILLEGAL_CMD);
+ }
+
+ if((response_R1 & SD_R6_COM_CRC_FAILED) == SD_R6_COM_CRC_FAILED)
+ {
+ return(SD_COM_CRC_FAILED);
+ }
+
+ return errorState;
+}
+
+/**
+ * @brief Enables the SDIO wide bus mode.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_WideBus_Enable(SD_HandleTypeDef *hsd)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ uint32_t scr[2] = {0, 0};
+
+ if((SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED)
+ {
+ errorState = SD_LOCK_UNLOCK_FAILED;
+
+ return errorState;
+ }
+
+ /* Get SCR Register */
+ errorState = SD_FindSCR(hsd, scr);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* If requested card supports wide bus operation */
+ if((scr[1] & SD_WIDE_BUS_SUPPORT) != SD_ALLZERO)
+ {
+ /* Send CMD55 APP_CMD with argument as card's RCA.*/
+ SDIO_CmdInitStructure.Argument = (uint32_t)(hsd->RCA << 16);
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_APP_CMD;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */
+ SDIO_CmdInitStructure.Argument = 2;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_APP_SD_SET_BUSWIDTH;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_APP_SD_SET_BUSWIDTH);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ return errorState;
+ }
+ else
+ {
+ errorState = SD_REQUEST_NOT_APPLICABLE;
+
+ return errorState;
+ }
+}
+
+/**
+ * @brief Disables the SDIO wide bus mode.
+ * @param hsd: SD handle
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_WideBus_Disable(SD_HandleTypeDef *hsd)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+
+ uint32_t scr[2] = {0, 0};
+
+ if((SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED)
+ {
+ errorState = SD_LOCK_UNLOCK_FAILED;
+
+ return errorState;
+ }
+
+ /* Get SCR Register */
+ errorState = SD_FindSCR(hsd, scr);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* If requested card supports 1 bit mode operation */
+ if((scr[1] & SD_SINGLE_BUS_SUPPORT) != SD_ALLZERO)
+ {
+ /* Send CMD55 APP_CMD with argument as card's RCA */
+ SDIO_CmdInitStructure.Argument = (uint32_t)(hsd->RCA << 16);
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_APP_CMD;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */
+ SDIO_CmdInitStructure.Argument = 0;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_APP_SD_SET_BUSWIDTH;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_APP_SD_SET_BUSWIDTH);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ return errorState;
+ }
+ else
+ {
+ errorState = SD_REQUEST_NOT_APPLICABLE;
+
+ return errorState;
+ }
+}
+
+
+/**
+ * @brief Finds the SD card SCR register value.
+ * @param hsd: SD handle
+ * @param pSCR: pointer to the buffer that will contain the SCR value
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ SDIO_DataInitTypeDef SDIO_DataInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ uint32_t index = 0;
+ uint32_t tempscr[2] = {0, 0};
+
+ /* Set Block Size To 8 Bytes */
+ /* Send CMD55 APP_CMD with argument as card's RCA */
+ SDIO_CmdInitStructure.Argument = (uint32_t)8;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SET_BLOCKLEN;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ /* Send CMD55 APP_CMD with argument as card's RCA */
+ SDIO_CmdInitStructure.Argument = (uint32_t)((hsd->RCA) << 16);
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_APP_CMD;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+ SDIO_DataInitStructure.DataTimeOut = SD_DATATIMEOUT;
+ SDIO_DataInitStructure.DataLength = 8;
+ SDIO_DataInitStructure.DataBlockSize = SDIO_DATABLOCK_SIZE_8B;
+ SDIO_DataInitStructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO;
+ SDIO_DataInitStructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK;
+ SDIO_DataInitStructure.DPSM = SDIO_DPSM_ENABLE;
+ SDIO_DataConfig(hsd->Instance, &SDIO_DataInitStructure);
+
+ /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */
+ SDIO_CmdInitStructure.Argument = 0;
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SD_APP_SEND_SCR;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ /* Check for error conditions */
+ errorState = SD_CmdResp1Error(hsd, SD_CMD_SD_APP_SEND_SCR);
+
+ if(errorState != SD_OK)
+ {
+ return errorState;
+ }
+
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
+ {
+ if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL))
+ {
+ *(tempscr + index) = SDIO_ReadFIFO(hsd->Instance);
+ index++;
+ }
+ }
+
+ if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
+
+ errorState = SD_DATA_TIMEOUT;
+
+ return errorState;
+ }
+ else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
+
+ errorState = SD_DATA_CRC_FAIL;
+
+ return errorState;
+ }
+ else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
+
+ errorState = SD_RX_OVERRUN;
+
+ return errorState;
+ }
+ else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
+ {
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
+
+ errorState = SD_START_BIT_ERR;
+
+ return errorState;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+ *(pSCR + 1) = ((tempscr[0] & SD_0TO7BITS) << 24) | ((tempscr[0] & SD_8TO15BITS) << 8) |\
+ ((tempscr[0] & SD_16TO23BITS) >> 8) | ((tempscr[0] & SD_24TO31BITS) >> 24);
+
+ *(pSCR) = ((tempscr[1] & SD_0TO7BITS) << 24) | ((tempscr[1] & SD_8TO15BITS) << 8) |\
+ ((tempscr[1] & SD_16TO23BITS) >> 8) | ((tempscr[1] & SD_24TO31BITS) >> 24);
+
+ return errorState;
+}
+
+/**
+ * @brief Checks if the SD card is in programming state.
+ * @param hsd: SD handle
+ * @param pStatus: pointer to the variable that will contain the SD card state
+ * @retval SD Card error state
+ */
+static HAL_SD_ErrorTypedef SD_IsCardProgramming(SD_HandleTypeDef *hsd, uint8_t *pStatus)
+{
+ SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
+ HAL_SD_ErrorTypedef errorState = SD_OK;
+ __IO uint32_t responseR1 = 0;
+
+ SDIO_CmdInitStructure.Argument = (uint32_t)(hsd->RCA << 16);
+ SDIO_CmdInitStructure.CmdIndex = SD_CMD_SEND_STATUS;
+ SDIO_CmdInitStructure.Response = SDIO_RESPONSE_SHORT;
+ SDIO_CmdInitStructure.WaitForInterrupt = SDIO_WAIT_NO;
+ SDIO_CmdInitStructure.CPSM = SDIO_CPSM_ENABLE;
+ SDIO_SendCommand(hsd->Instance, &SDIO_CmdInitStructure);
+
+ while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
+ {
+ }
+
+ if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
+ {
+ errorState = SD_CMD_RSP_TIMEOUT;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
+
+ return errorState;
+ }
+ else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL))
+ {
+ errorState = SD_CMD_CRC_FAIL;
+
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL);
+
+ return errorState;
+ }
+
+ /* Check response received is of desired command */
+ if((uint32_t)SDIO_GetCommandResponse(hsd->Instance) != SD_CMD_SEND_STATUS)
+ {
+ errorState = SD_ILLEGAL_CMD;
+
+ return errorState;
+ }
+
+ /* Clear all the static flags */
+ __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
+
+
+ /* We have received response, retrieve it for analysis */
+ responseR1 = SDIO_GetResponse(SDIO_RESP1);
+
+ /* Find out card status */
+ *pStatus = (uint8_t)((responseR1 >> 9) & 0x0000000F);
+
+ if((responseR1 & SD_OCR_ERRORBITS) == SD_ALLZERO)
+ {
+ return errorState;
+ }
+
+ if((responseR1 & SD_OCR_ADDR_OUT_OF_RANGE) == SD_OCR_ADDR_OUT_OF_RANGE)
+ {
+ return(SD_ADDR_OUT_OF_RANGE);
+ }
+
+ if((responseR1 & SD_OCR_ADDR_MISALIGNED) == SD_OCR_ADDR_MISALIGNED)
+ {
+ return(SD_ADDR_MISALIGNED);
+ }
+
+ if((responseR1 & SD_OCR_BLOCK_LEN_ERR) == SD_OCR_BLOCK_LEN_ERR)
+ {
+ return(SD_BLOCK_LEN_ERR);
+ }
+
+ if((responseR1 & SD_OCR_ERASE_SEQ_ERR) == SD_OCR_ERASE_SEQ_ERR)
+ {
+ return(SD_ERASE_SEQ_ERR);
+ }
+
+ if((responseR1 & SD_OCR_BAD_ERASE_PARAM) == SD_OCR_BAD_ERASE_PARAM)
+ {
+ return(SD_BAD_ERASE_PARAM);
+ }
+
+ if((responseR1 & SD_OCR_WRITE_PROT_VIOLATION) == SD_OCR_WRITE_PROT_VIOLATION)
+ {
+ return(SD_WRITE_PROT_VIOLATION);
+ }
+
+ if((responseR1 & SD_OCR_LOCK_UNLOCK_FAILED) == SD_OCR_LOCK_UNLOCK_FAILED)
+ {
+ return(SD_LOCK_UNLOCK_FAILED);
+ }
+
+ if((responseR1 & SD_OCR_COM_CRC_FAILED) == SD_OCR_COM_CRC_FAILED)
+ {
+ return(SD_COM_CRC_FAILED);
+ }
+
+ if((responseR1 & SD_OCR_ILLEGAL_CMD) == SD_OCR_ILLEGAL_CMD)
+ {
+ return(SD_ILLEGAL_CMD);
+ }
+
+ if((responseR1 & SD_OCR_CARD_ECC_FAILED) == SD_OCR_CARD_ECC_FAILED)
+ {
+ return(SD_CARD_ECC_FAILED);
+ }
+
+ if((responseR1 & SD_OCR_CC_ERROR) == SD_OCR_CC_ERROR)
+ {
+ return(SD_CC_ERROR);
+ }
+
+ if((responseR1 & SD_OCR_GENERAL_UNKNOWN_ERROR) == SD_OCR_GENERAL_UNKNOWN_ERROR)
+ {
+ return(SD_GENERAL_UNKNOWN_ERROR);
+ }
+
+ if((responseR1 & SD_OCR_STREAM_READ_UNDERRUN) == SD_OCR_STREAM_READ_UNDERRUN)
+ {
+ return(SD_STREAM_READ_UNDERRUN);
+ }
+
+ if((responseR1 & SD_OCR_STREAM_WRITE_OVERRUN) == SD_OCR_STREAM_WRITE_OVERRUN)
+ {
+ return(SD_STREAM_WRITE_OVERRUN);
+ }
+
+ if((responseR1 & SD_OCR_CID_CSD_OVERWRIETE) == SD_OCR_CID_CSD_OVERWRIETE)
+ {
+ return(SD_CID_CSD_OVERWRITE);
+ }
+
+ if((responseR1 & SD_OCR_WP_ERASE_SKIP) == SD_OCR_WP_ERASE_SKIP)
+ {
+ return(SD_WP_ERASE_SKIP);
+ }
+
+ if((responseR1 & SD_OCR_CARD_ECC_DISABLED) == SD_OCR_CARD_ECC_DISABLED)
+ {
+ return(SD_CARD_ECC_DISABLED);
+ }
+
+ if((responseR1 & SD_OCR_ERASE_RESET) == SD_OCR_ERASE_RESET)
+ {
+ return(SD_ERASE_RESET);
+ }
+
+ if((responseR1 & SD_OCR_AKE_SEQ_ERROR) == SD_OCR_AKE_SEQ_ERROR)
+ {
+ return(SD_AKE_SEQ_ERROR);
+ }
+
+ return errorState;
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_SD_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sdram.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sdram.c
new file mode 100644
index 0000000..66b635c
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sdram.c
@@ -0,0 +1,824 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_sdram.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief SDRAM HAL module driver.
+ * This file provides a generic firmware to drive SDRAM memories mounted
+ * as external device.
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ This driver is a generic layered driver which contains a set of APIs used to
+ control SDRAM memories. It uses the FMC layer functions to interface
+ with SDRAM devices.
+ The following sequence should be followed to configure the FMC to interface
+ with SDRAM memories:
+
+ (#) Declare a SDRAM_HandleTypeDef handle structure, for example:
+ SDRAM_HandleTypeDef hdsram; and:
+
+ (++) Fill the SDRAM_HandleTypeDef handle "Init" field with the allowed
+ values of the structure member.
+
+ (++) Fill the SDRAM_HandleTypeDef handle "Instance" field with a predefined
+ base register instance for NOR or SDRAM device
+
+ (#) Declare a FMC_SDRAM_TimingTypeDef structure; for example:
+ FMC_SDRAM_TimingTypeDef Timing;
+ and fill its fields with the allowed values of the structure member.
+
+ (#) Initialize the SDRAM Controller by calling the function HAL_SDRAM_Init(). This function
+ performs the following sequence:
+
+ (##) MSP hardware layer configuration using the function HAL_SDRAM_MspInit()
+ (##) Control register configuration using the FMC SDRAM interface function
+ FMC_SDRAM_Init()
+ (##) Timing register configuration using the FMC SDRAM interface function
+ FMC_SDRAM_Timing_Init()
+ (##) Program the SDRAM external device by applying its initialization sequence
+ according to the device plugged in your hardware. This step is mandatory
+ for accessing the SDRAM device.
+
+ (#) At this stage you can perform read/write accesses from/to the memory connected
+ to the SDRAM Bank. You can perform either polling or DMA transfer using the
+ following APIs:
+ (++) HAL_SDRAM_Read()/HAL_SDRAM_Write() for polling read/write access
+ (++) HAL_SDRAM_Read_DMA()/HAL_SDRAM_Write_DMA() for DMA read/write transfer
+
+ (#) You can also control the SDRAM device by calling the control APIs HAL_SDRAM_WriteOperation_Enable()/
+ HAL_SDRAM_WriteOperation_Disable() to respectively enable/disable the SDRAM write operation or
+ the function HAL_SDRAM_SendCommand() to send a specified command to the SDRAM
+ device. The command to be sent must be configured with the FMC_SDRAM_CommandTypeDef
+ structure.
+
+ (#) You can continuously monitor the SDRAM device HAL state by calling the function
+ HAL_SDRAM_GetState()
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup SDRAM
+ * @brief SDRAM driver modules
+ * @{
+ */
+#ifdef HAL_SDRAM_MODULE_ENABLED
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup SDRAM_Private_Functions
+ * @{
+ */
+
+/** @defgroup SDRAM_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### SDRAM Initialization and de_initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to initialize/de-initialize
+ the SDRAM memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Performs the SDRAM device initialization sequence.
+ * @param hsdram: SDRAM handle
+ * @param Timing: Pointer to SDRAM control timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_Init(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_TimingTypeDef *Timing)
+{
+ /* Check the SDRAM handle parameter */
+ if(hsdram == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ if(hsdram->State == HAL_SDRAM_STATE_RESET)
+ {
+ /* Initialize the low level hardware (MSP) */
+ HAL_SDRAM_MspInit(hsdram);
+ }
+
+ /* Initialize the SDRAM controller state */
+ hsdram->State = HAL_SDRAM_STATE_BUSY;
+
+ /* Initialize SDRAM control Interface */
+ FMC_SDRAM_Init(hsdram->Instance, &(hsdram->Init));
+
+ /* Initialize SDRAM timing Interface */
+ FMC_SDRAM_Timing_Init(hsdram->Instance, Timing, hsdram->Init.SDBank);
+
+ /* Update the SDRAM controller state */
+ hsdram->State = HAL_SDRAM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Perform the SDRAM device initialization sequence.
+ * @param hsdram: SDRAM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_DeInit(SDRAM_HandleTypeDef *hsdram)
+{
+ /* Initialize the low level hardware (MSP) */
+ HAL_SDRAM_MspDeInit(hsdram);
+
+ /* Configure the SDRAM registers with their reset values */
+ FMC_SDRAM_DeInit(hsdram->Instance, hsdram->Init.SDBank);
+
+ /* Reset the SDRAM controller state */
+ hsdram->State = HAL_SDRAM_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hsdram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief SDRAM MSP Init.
+ * @param hsdram: SDRAM handle
+ * @retval None
+ */
+__weak void HAL_SDRAM_MspInit(SDRAM_HandleTypeDef *hsdram)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_SDRAM_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief SDRAM MSP DeInit.
+ * @param hsdram: SDRAM handle
+ * @retval None
+ */
+__weak void HAL_SDRAM_MspDeInit(SDRAM_HandleTypeDef *hsdram)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_SDRAM_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief This function handles SDRAM refresh error interrupt request.
+ * @param hsdram: SDRAM handle
+ * @retval HAL status
+*/
+void HAL_SDRAM_IRQHandler(SDRAM_HandleTypeDef *hsdram)
+{
+ /* Check SDRAM interrupt Rising edge flag */
+ if(__FMC_SDRAM_GET_FLAG(hsdram->Instance, FMC_SDRAM_FLAG_REFRESH_IT))
+ {
+ /* SDRAM refresh error interrupt callback */
+ HAL_SDRAM_RefreshErrorCallback(hsdram);
+
+ /* Clear SDRAM refresh error interrupt pending bit */
+ __FMC_SDRAM_CLEAR_FLAG(hsdram->Instance, FMC_SDRAM_FLAG_REFRESH_ERROR);
+ }
+}
+
+/**
+ * @brief SDRAM Refresh error callback.
+ * @param hsdram: SDRAM handle
+ * @retval None
+ */
+__weak void HAL_SDRAM_RefreshErrorCallback(SDRAM_HandleTypeDef *hsdram)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_SDRAM_RefreshErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DMA transfer complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+__weak void HAL_SDRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_SDRAM_DMA_XferCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DMA transfer complete error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+__weak void HAL_SDRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_SDRAM_DMA_XferErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SDRAM_Group2 Input and Output functions
+ * @brief Input Output and memory control functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### SDRAM Input and Output functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to use and control the SDRAM memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Reads 8-bit data buffer from the SDRAM memory.
+ * @param hsdram: SDRAM handle
+ * @param pAddress: Pointer to read start address
+ * @param pDstBuffer: Pointer to destination buffer
+ * @param BufferSize: Size of the buffer to read from memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_Read_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pDstBuffer, uint32_t BufferSize)
+{
+ __IO uint8_t *pSdramAddress = (uint8_t *)pAddress;
+
+ /* Process Locked */
+ __HAL_LOCK(hsdram);
+
+ /* Check the SDRAM controller state */
+ if(hsdram->State == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+ else if(hsdram->State == HAL_SDRAM_STATE_PRECHARGED)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Read data from source */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *pDstBuffer = *(__IO uint8_t *)pSdramAddress;
+ pDstBuffer++;
+ pSdramAddress++;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsdram);
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Writes 8-bit data buffer to SDRAM memory.
+ * @param hsdram: SDRAM handle
+ * @param pAddress: Pointer to write start address
+ * @param pSrcBuffer: Pointer to source buffer to write
+ * @param BufferSize: Size of the buffer to write to memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_Write_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pSrcBuffer, uint32_t BufferSize)
+{
+ __IO uint8_t *pSdramAddress = (uint8_t *)pAddress;
+ uint32_t tmp = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hsdram);
+
+ /* Check the SDRAM controller state */
+ tmp = hsdram->State;
+
+ if(tmp == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+ else if((tmp == HAL_SDRAM_STATE_PRECHARGED) || (tmp == HAL_SDRAM_STATE_WRITE_PROTECTED))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Write data to memory */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *(__IO uint8_t *)pSdramAddress = *pSrcBuffer;
+ pSrcBuffer++;
+ pSdramAddress++;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsdram);
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Reads 16-bit data buffer from the SDRAM memory.
+ * @param hsdram: SDRAM handle
+ * @param pAddress: Pointer to read start address
+ * @param pDstBuffer: Pointer to destination buffer
+ * @param BufferSize: Size of the buffer to read from memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_Read_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pDstBuffer, uint32_t BufferSize)
+{
+ __IO uint16_t *pSdramAddress = (uint16_t *)pAddress;
+
+ /* Process Locked */
+ __HAL_LOCK(hsdram);
+
+ /* Check the SDRAM controller state */
+ if(hsdram->State == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+ else if(hsdram->State == HAL_SDRAM_STATE_PRECHARGED)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Read data from source */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *pDstBuffer = *(__IO uint16_t *)pSdramAddress;
+ pDstBuffer++;
+ pSdramAddress++;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsdram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Writes 16-bit data buffer to SDRAM memory.
+ * @param hsdram: SDRAM handle
+ * @param pAddress: Pointer to write start address
+ * @param pSrcBuffer: Pointer to source buffer to write
+ * @param BufferSize: Size of the buffer to write to memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_Write_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pSrcBuffer, uint32_t BufferSize)
+{
+ __IO uint16_t *pSdramAddress = (uint16_t *)pAddress;
+ uint32_t tmp = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hsdram);
+
+ /* Check the SDRAM controller state */
+ tmp = hsdram->State;
+
+ if(tmp == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+ else if((tmp == HAL_SDRAM_STATE_PRECHARGED) || (tmp == HAL_SDRAM_STATE_WRITE_PROTECTED))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Write data to memory */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *(__IO uint16_t *)pSdramAddress = *pSrcBuffer;
+ pSrcBuffer++;
+ pSdramAddress++;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsdram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Reads 32-bit data buffer from the SDRAM memory.
+ * @param hsdram: SDRAM handle
+ * @param pAddress: Pointer to read start address
+ * @param pDstBuffer: Pointer to destination buffer
+ * @param BufferSize: Size of the buffer to read from memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_Read_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize)
+{
+ __IO uint32_t *pSdramAddress = (uint32_t *)pAddress;
+
+ /* Process Locked */
+ __HAL_LOCK(hsdram);
+
+ /* Check the SDRAM controller state */
+ if(hsdram->State == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+ else if(hsdram->State == HAL_SDRAM_STATE_PRECHARGED)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Read data from source */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *pDstBuffer = *(__IO uint32_t *)pSdramAddress;
+ pDstBuffer++;
+ pSdramAddress++;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsdram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Writes 32-bit data buffer to SDRAM memory.
+ * @param hsdram: SDRAM handle
+ * @param pAddress: Pointer to write start address
+ * @param pSrcBuffer: Pointer to source buffer to write
+ * @param BufferSize: Size of the buffer to write to memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_Write_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize)
+{
+ __IO uint32_t *pSdramAddress = (uint32_t *)pAddress;
+ uint32_t tmp = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hsdram);
+
+ /* Check the SDRAM controller state */
+ tmp = hsdram->State;
+
+ if(tmp == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+ else if((tmp == HAL_SDRAM_STATE_PRECHARGED) || (tmp == HAL_SDRAM_STATE_WRITE_PROTECTED))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Write data to memory */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *(__IO uint32_t *)pSdramAddress = *pSrcBuffer;
+ pSrcBuffer++;
+ pSdramAddress++;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsdram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Reads a Words data from the SDRAM memory using DMA transfer.
+ * @param hsdram: SDRAM handle
+ * @param pAddress: Pointer to read start address
+ * @param pDstBuffer: Pointer to destination buffer
+ * @param BufferSize: Size of the buffer to read from memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_Read_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize)
+{
+ uint32_t tmp = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hsdram);
+
+ /* Check the SDRAM controller state */
+ tmp = hsdram->State;
+
+ if(tmp == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+ else if(tmp == HAL_SDRAM_STATE_PRECHARGED)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Configure DMA user callbacks */
+ hsdram->hdma->XferCpltCallback = HAL_SDRAM_DMA_XferCpltCallback;
+ hsdram->hdma->XferErrorCallback = HAL_SDRAM_DMA_XferErrorCallback;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hsdram->hdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, (uint32_t)BufferSize);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsdram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Writes a Words data buffer to SDRAM memory using DMA transfer.
+ * @param hsdram: SDRAM handle
+ * @param pAddress: Pointer to write start address
+ * @param pSrcBuffer: Pointer to source buffer to write
+ * @param BufferSize: Size of the buffer to write to memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_Write_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize)
+{
+ uint32_t tmp = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(hsdram);
+
+ /* Check the SDRAM controller state */
+ tmp = hsdram->State;
+
+ if(tmp == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+ else if((tmp == HAL_SDRAM_STATE_PRECHARGED) || (tmp == HAL_SDRAM_STATE_WRITE_PROTECTED))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Configure DMA user callbacks */
+ hsdram->hdma->XferCpltCallback = HAL_SDRAM_DMA_XferCpltCallback;
+ hsdram->hdma->XferErrorCallback = HAL_SDRAM_DMA_XferErrorCallback;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hsdram->hdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, (uint32_t)BufferSize);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsdram);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SDRAM_Group3 Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### SDRAM Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control dynamically
+ the SDRAM interface.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables dynamically SDRAM write protection.
+ * @param hsdram: SDRAM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_WriteProtection_Enable(SDRAM_HandleTypeDef *hsdram)
+{
+ /* Check the SDRAM controller state */
+ if(hsdram->State == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the SDRAM state */
+ hsdram->State = HAL_SDRAM_STATE_BUSY;
+
+ /* Enable write protection */
+ FMC_SDRAM_WriteProtection_Enable(hsdram->Instance, hsdram->Init.SDBank);
+
+ /* Update the SDRAM state */
+ hsdram->State = HAL_SDRAM_STATE_WRITE_PROTECTED;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables dynamically SDRAM write protection.
+ * @param hsdram: SDRAM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SDRAM_WriteProtection_Disable(SDRAM_HandleTypeDef *hsdram)
+{
+ /* Check the SDRAM controller state */
+ if(hsdram->State == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the SDRAM state */
+ hsdram->State = HAL_SDRAM_STATE_BUSY;
+
+ /* Disable write protection */
+ FMC_SDRAM_WriteProtection_Disable(hsdram->Instance, hsdram->Init.SDBank);
+
+ /* Update the SDRAM state */
+ hsdram->State = HAL_SDRAM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Sends Command to the SDRAM bank.
+ * @param hsdram: SDRAM handle
+ * @param Command: SDRAM command structure
+ * @param Timeout: Timeout duration
+ * @retval HAL state
+ */
+HAL_StatusTypeDef HAL_SDRAM_SendCommand(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_CommandTypeDef *Command, uint32_t Timeout)
+{
+ /* Check the SDRAM controller state */
+ if(hsdram->State == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the SDRAM state */
+ hsdram->State = HAL_SDRAM_STATE_BUSY;
+
+ /* Send SDRAM command */
+ FMC_SDRAM_SendCommand(hsdram->Instance, Command, Timeout);
+
+ /* Update the SDRAM controller state state */
+ if(Command->CommandMode == FMC_SDRAM_CMD_PALL)
+ {
+ hsdram->State = HAL_SDRAM_STATE_PRECHARGED;
+ }
+ else
+ {
+ hsdram->State = HAL_SDRAM_STATE_READY;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Programs the SDRAM Memory Refresh rate.
+ * @param hsdram: SDRAM handle
+ * @param RefreshRate: The SDRAM refresh rate value
+ * @retval HAL state
+ */
+HAL_StatusTypeDef HAL_SDRAM_ProgramRefreshRate(SDRAM_HandleTypeDef *hsdram, uint32_t RefreshRate)
+{
+ /* Check the SDRAM controller state */
+ if(hsdram->State == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the SDRAM state */
+ hsdram->State = HAL_SDRAM_STATE_BUSY;
+
+ /* Program the refresh rate */
+ FMC_SDRAM_ProgramRefreshRate(hsdram->Instance ,RefreshRate);
+
+ /* Update the SDRAM state */
+ hsdram->State = HAL_SDRAM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Sets the Number of consecutive SDRAM Memory auto Refresh commands.
+ * @param hsdram: SDRAM handle
+ * @param AutoRefreshNumber: The SDRAM auto Refresh number
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_SDRAM_SetAutoRefreshNumber(SDRAM_HandleTypeDef *hsdram, uint32_t AutoRefreshNumber)
+{
+ /* Check the SDRAM controller state */
+ if(hsdram->State == HAL_SDRAM_STATE_BUSY)
+ {
+ return HAL_BUSY;
+ }
+
+ /* Update the SDRAM state */
+ hsdram->State = HAL_SDRAM_STATE_BUSY;
+
+ /* Set the Auto-Refresh number */
+ FMC_SDRAM_SetAutoRefreshNumber(hsdram->Instance ,AutoRefreshNumber);
+
+ /* Update the SDRAM state */
+ hsdram->State = HAL_SDRAM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Returns the SDRAM memory current mode.
+ * @param hsdram: SDRAM handle
+ * @retval The SDRAM memory mode.
+ */
+uint32_t HAL_SDRAM_GetModeStatus(SDRAM_HandleTypeDef *hsdram)
+{
+ /* Return the SDRAM memory current mode */
+ return(FMC_SDRAM_GetModeStatus(hsdram->Instance, hsdram->Init.SDBank));
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SDRAM_Group4 State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ==============================================================================
+ ##### SDRAM State functions #####
+ ==============================================================================
+ [..]
+ This subsection permits to get in run-time the status of the SDRAM controller
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the SDRAM state.
+ * @param hsdram: SDRAM handle
+ * @retval HAL state
+ */
+HAL_SDRAM_StateTypeDef HAL_SDRAM_GetState(SDRAM_HandleTypeDef *hsdram)
+{
+ return hsdram->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_SDRAM_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_smartcard.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_smartcard.c
new file mode 100644
index 0000000..49ff894
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_smartcard.c
@@ -0,0 +1,1266 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_smartcard.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief SMARTCARD HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the SMARTCARD peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral State and Errors functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The SMARTCARD HAL driver can be used as follow:
+
+ (#) Declare a SMARTCARD_HandleTypeDef handle structure.
+ (#) Initialize the SMARTCARD low level resources by implement the HAL_SMARTCARD_MspInit ()API:
+ (##) Enable the USARTx interface clock.
+ (##) SMARTCARD pins configuration:
+ (+++) Enable the clock for the SMARTCARD GPIOs.
+ (+++) Configure these SMARTCARD pins as alternate function pull-up.
+ (##) NVIC configuration if you need to use interrupt process (HAL_SMARTCARD_Transmit_IT()
+ and HAL_SMARTCARD_Receive_IT() APIs):
+ (+++) Configure the USARTx interrupt priority.
+ (+++) Enable the NVIC USART IRQ handle.
+
+ -@@- The specific SMARTCARD interrupts (Transmission complete interrupt,
+ RXNE interrupt and Error Interrupts) will be managed using the macros
+ __SMARTCARD_ENABLE_IT() and __SMARTCARD_DISABLE_IT() inside the transmit and receive process.
+ (##) DMA Configuration if you need to use DMA process (HAL_SMARTCARD_Transmit_DMA()
+ and HAL_SMARTCARD_Receive_DMA() APIs):
+ (+++) Declare a DMA handle structure for the Tx/Rx stream.
+ (+++) Enable the DMAx interface clock.
+ (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.
+ (+++) Configure the DMA Tx/Rx Stream.
+ (+++) Associate the initilalized DMA handle to the SMARTCARD DMA Tx/Rx handle.
+ (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream.
+
+ (#) Program the Baud Rate, Word Length , Stop Bit, Parity, Hardware
+ flow control and Mode(Receiver/Transmitter) in the hsc Init structure.
+
+ (#) Initialize the SMARTCARD registers by calling the HAL_SMARTCARD_Init() API:
+ (++) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc)
+ by calling the customed HAL_SMARTCARD_MspInit(&hsc) API.
+
+ (#) Three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Send an amount of data in blocking mode using HAL_SMARTCARD_Transmit()
+ (+) Receive an amount of data in blocking mode using HAL_SMARTCARD_Receive()
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Send an amount of data in non blocking mode using HAL_SMARTCARD_Transmit_IT()
+ (+) At transmission end of transfer HAL_SMARTCARD_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_SMARTCARD_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode using HAL_SMARTCARD_Receive_IT()
+ (+) At reception end of transfer HAL_SMARTCARD_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_SMARTCARD_RxCpltCallback
+ (+) In case of transfer Error, HAL_SMARTCARD_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_SMARTCARD_ErrorCallback
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Send an amount of data in non blocking mode (DMA) using HAL_SMARTCARD_Transmit_DMA()
+ (+) At transmission end of transfer HAL_SMARTCARD_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_SMARTCARD_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode (DMA) using HAL_SMARTCARD_Receive_DMA()
+ (+) At reception end of transfer HAL_SMARTCARD_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_SMARTCARD_RxCpltCallback
+ (+) In case of transfer Error, HAL_SMARTCARD_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_SMARTCARD_ErrorCallback
+
+ *** SMARTCARD HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in SMARTCARD HAL driver.
+
+ (+) __HAL_SMARTCARD_ENABLE: Enable the SMARTCARD peripheral
+ (+) __HAL_SMARTCARD_DISABLE: Disable the SMARTCARD peripheral
+ (+) __HAL_SMARTCARD_GET_FLAG : Checks whether the specified SMARTCARD flag is set or not
+ (+) __HAL_SMARTCARD_CLEAR_FLAG : Clears the specified SMARTCARD pending flag
+ (+) __HAL_SMARTCARD_ENABLE_IT: Enables the specified SMARTCARD interrupt
+ (+) __HAL_SMARTCARD_DISABLE_IT: Disables the specified SMARTCARD interrupt
+
+ [..]
+ (@) You can refer to the SMARTCARD HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup SMARTCARD
+ * @brief HAL USART SMARTCARD module driver
+ * @{
+ */
+#ifdef HAL_SMARTCARD_MODULE_ENABLED
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define SMARTCARD_TIMEOUT_VALUE 22000
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void SMARTCARD_SetConfig (SMARTCARD_HandleTypeDef *hsc);
+static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc);
+static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc);
+static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma);
+static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
+static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma);
+static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup SMARTCARD_Private_Functions
+ * @{
+ */
+
+/** @defgroup SMARTCARD_Group1 SmartCard Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and Configuration functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to initialize the USART
+ in Smartcard mode.
+ [..]
+ The Smartcard interface is designed to support asynchronous protocol Smartcards as
+ defined in the ISO 7816-3 standard.
+ [..]
+ The USART can provide a clock to the smartcard through the SCLK output.
+ In smartcard mode, SCLK is not associated to the communication but is simply derived
+ from the internal peripheral input clock through a 5-bit prescaler.
+ [..]
+ (+) For the asynchronous mode only these parameters can be configured:
+ (++) Baud Rate
+ (++) Word Length
+ (++) Stop Bit
+ (++) Parity: If the parity is enabled, then the MSB bit of the data written
+ in the data register is transmitted but is changed by the parity bit.
+ Depending on the frame length defined by the M bit (8-bits or 9-bits),
+ the possible SmartCard frame formats are as listed in the following table:
+ +-------------------------------------------------------------+
+ | M bit | PCE bit | USART frame |
+ |---------------------|---------------------------------------|
+ | 0 | 0 | | SB | 8 bit data | STB | |
+ |---------|-----------|---------------------------------------|
+ | 0 | 1 | | SB | 7 bit data | PB | STB | |
+ |---------|-----------|---------------------------------------|
+ | 1 | 0 | | SB | 9 bit data | STB | |
+ |---------|-----------|---------------------------------------|
+ | 1 | 1 | | SB | 8 bit data | PB | STB | |
+ +-------------------------------------------------------------+
+ (++) USART polarity
+ (++) USART phase
+ (++) USART LastBit
+ (++) Receiver/transmitter modes
+ (++) Prescaler
+ (++) GuardTime
+ (++) NACKState: The Smartcard NACK state
+
+ (+) Recommended SmartCard interface configuration to get the Answer to Reset from the Card:
+ (++) Word Length = 9 Bits
+ (++) 1.5 Stop Bit
+ (++) Even parity
+ (++) BaudRate = 12096 baud
+ (++) Tx and Rx enabled
+ [..]
+ Please refer to the ISO 7816-3 specification for more details.
+
+ -@- It is also possible to choose 0.5 stop bit for receiving but it is recommended
+ to use 1.5 stop bits for both transmitting and receiving to avoid switching
+ between the two configurations.
+ [..]
+ The HAL_SMARTCARD_Init() function follows the USART SmartCard configuration
+ procedure (details for the procedure are available in reference manual (RM0329)).
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the SmartCard mode according to the specified
+ * parameters in the SMARTCARD_InitTypeDef and create the associated handle .
+ * @param hsc: usart handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc)
+{
+ /* Check the SMARTCARD handle allocation */
+ if(hsc == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance));
+ assert_param(IS_SMARTCARD_NACK_STATE(hsc->Init.NACKState));
+
+ if(hsc->State == HAL_SMARTCARD_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
+ HAL_SMARTCARD_MspInit(hsc);
+ }
+
+ hsc->State = HAL_SMARTCARD_STATE_BUSY;
+
+ /* Set the Prescaler */
+ MODIFY_REG(hsc->Instance->GTPR, USART_GTPR_PSC, hsc->Init.Prescaler);
+
+ /* Set the Guard Time */
+ MODIFY_REG(hsc->Instance->GTPR, USART_GTPR_GT, ((hsc->Init.GuardTime)<<8));
+
+ /* Set the Smartcard Communication parameters */
+ SMARTCARD_SetConfig(hsc);
+
+ /* In SmartCard mode, the following bits must be kept cleared:
+ - LINEN bit in the USART_CR2 register
+ - HDSEL and IREN bits in the USART_CR3 register.*/
+ hsc->Instance->CR2 &= ~USART_CR2_LINEN;
+ hsc->Instance->CR3 &= ~(USART_CR3_IREN | USART_CR3_HDSEL);
+
+ /* Enable the SMARTCARD Parity Error Interrupt */
+ __SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_PE);
+
+ /* Enable the SMARTCARD Framing Error Interrupt */
+ __SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_ERR);
+
+ /* Enable the Peripharal */
+ __SMARTCARD_ENABLE(hsc);
+
+ /* Configure the Smartcard NACK state */
+ MODIFY_REG(hsc->Instance->CR3, USART_CR3_NACK, hsc->Init.NACKState);
+
+ /* Enable the SC mode by setting the SCEN bit in the CR3 register */
+ hsc->Instance->CR3 |= (USART_CR3_SCEN);
+
+ /* Initialize the SMARTCARD state*/
+ hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
+ hsc->State= HAL_SMARTCARD_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the USART SmartCard peripheral
+ * @param hsc: usart handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc)
+{
+ /* Check the SMARTCARD handle allocation */
+ if(hsc == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance));
+
+ hsc->State = HAL_SMARTCARD_STATE_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_SMARTCARD_MspDeInit(hsc);
+
+ hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
+ hsc->State = HAL_SMARTCARD_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief SMARTCARD MSP Init
+ * @param hsc: usart handle
+ * @retval None
+ */
+ __weak void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SMARTCARD_MspInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief SMARTCARD MSP DeInit
+ * @param hsc: usart handle
+ * @retval None
+ */
+ __weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SMARTCARD_MspDeInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SMARTCARD_Group2 IO operation functions
+ * @brief SMARTCARD Transmit and Receive functions
+ *
+@verbatim
+ ===============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ This subsection provides a set of functions allowing to manage the SMARTCARD data transfers.
+ [..]
+ IrDA is a half duplex communication protocol. If the Transmitter is busy, any data
+ on the IrDA receive line will be ignored by the IrDA decoder and if the Receiver
+ is busy, data on the TX from the USART to IrDA will not be encoded by IrDA.
+ While receiving data, transmission should be avoided as the data to be transmitted
+ could be corrupted.
+
+ (#) There are two mode of transfer:
+ (++) Blocking mode: The communication is performed in polling mode.
+ The HAL status of all data processing is returned by the same function
+ after finishing transfer.
+ (++) No-Blocking mode: The communication is performed using Interrupts
+ or DMA, These API's return the HAL status.
+ The end of the data processing will be indicated through the
+ dedicated SMARTCARD IRQ when using Interrupt mode or the DMA IRQ when
+ using DMA mode.
+ The HAL_SMARTCARD_TxCpltCallback(), HAL_SMARTCARD_RxCpltCallback() user callbacks
+ will be executed respectivelly at the end of the transmit or Receive process
+ The HAL_SMARTCARD_ErrorCallback()user callback will be executed when a communication error is detected
+
+ (#) Blocking mode API's are :
+ (++) HAL_SMARTCARD_Transmit()
+ (++) HAL_SMARTCARD_Receive()
+
+ (#) Non-Blocking mode API's with Interrupt are :
+ (++) HAL_SMARTCARD_Transmit_IT()
+ (++) HAL_SMARTCARD_Receive_IT()
+ (++) HAL_SMARTCARD_IRQHandler()
+
+ (#) No-Blocking mode functions with DMA are :
+ (++) HAL_SMARTCARD_Transmit_DMA()
+ (++) HAL_SMARTCARD_Receive_DMA()
+
+ (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode:
+ (++) HAL_SMARTCARD_TxCpltCallback()
+ (++) HAL_SMARTCARD_RxCpltCallback()
+ (++) HAL_SMARTCARD_ErrorCallback()
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Send an amount of data in blocking mode
+ * @param hsc: usart handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ uint16_t* tmp;
+
+ if(hsc->State == HAL_SMARTCARD_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsc);
+
+ hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
+ hsc->State = HAL_SMARTCARD_STATE_BUSY_TX;
+
+ hsc->TxXferSize = Size;
+ hsc->TxXferCount = Size;
+ while(hsc->TxXferCount > 0)
+ {
+ hsc->TxXferCount--;
+ if(hsc->Init.WordLength == SMARTCARD_WORDLENGTH_9B)
+ {
+ if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pData;
+ hsc->Instance->DR = (*tmp & (uint16_t)0x01FF);
+ if(hsc->Init.Parity == SMARTCARD_PARITY_NONE)
+ {
+ pData +=2;
+ }
+ else
+ {
+ pData +=1;
+ }
+ }
+ else
+ {
+ if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ hsc->Instance->DR = (*pData++ & (uint8_t)0xFF);
+ }
+ }
+
+ if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TC, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hsc->State = HAL_SMARTCARD_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in blocking mode
+ * @param hsc: usart handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ uint16_t* tmp;
+
+ if(hsc->State == HAL_SMARTCARD_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsc);
+
+ hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
+ hsc->State = HAL_SMARTCARD_STATE_BUSY_RX;
+
+ hsc->RxXferSize = Size;
+ hsc->RxXferCount = Size;
+ /* Check the remain data to be received */
+ while(hsc->RxXferCount > 0)
+ {
+ hsc->RxXferCount--;
+ if(hsc->Init.WordLength == SMARTCARD_WORDLENGTH_9B)
+ {
+ if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pData;
+ if(hsc->Init.Parity == SMARTCARD_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(hsc->Instance->DR & (uint16_t)0x01FF);
+ pData +=2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(hsc->Instance->DR & (uint16_t)0x00FF);
+ pData +=1;
+ }
+ }
+ else
+ {
+ if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ if(hsc->Init.Parity == SMARTCARD_PARITY_NONE)
+ {
+ *pData++ = (uint8_t)(hsc->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ *pData++ = (uint8_t)(hsc->Instance->DR & (uint8_t)0x007F);
+ }
+ }
+ }
+ hsc->State = HAL_SMARTCARD_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Send an amount of data in non blocking mode
+ * @param hsc: usart handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size)
+{
+ if(hsc->State == HAL_SMARTCARD_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsc);
+
+ hsc->pTxBuffPtr = pData;
+ hsc->TxXferSize = Size;
+ hsc->TxXferCount = Size;
+
+ hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
+ hsc->State = HAL_SMARTCARD_STATE_BUSY_TX;
+
+ /* Enable the SMARTCARD Parity Error Interrupt */
+ __SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_PE);
+
+ /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */
+ __SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_ERR);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ /* Enable the SMARTCARD Transmit Complete Interrupt */
+ __SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_TC);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in non blocking mode
+ * @param hsc: usart handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size)
+{
+ if(hsc->State == HAL_SMARTCARD_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsc);
+
+ hsc->pRxBuffPtr = pData;
+ hsc->RxXferSize = Size;
+ hsc->RxXferCount = Size;
+
+ hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
+ hsc->State = HAL_SMARTCARD_STATE_BUSY_RX;
+
+ /* Enable the SMARTCARD Data Register not empty Interrupt */
+ __SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_RXNE);
+
+ /* Enable the SMARTCARD Parity Error Interrupt */
+ __SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_PE);
+
+ /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */
+ __SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_ERR);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Send an amount of data in non blocking mode
+ * @param hsc: usart handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+ uint32_t tmpstate;
+
+ tmpstate = hsc->State;
+ if((tmpstate == HAL_SMARTCARD_STATE_READY) || (tmpstate == HAL_SMARTCARD_STATE_BUSY_RX))
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsc);
+
+ hsc->pTxBuffPtr = pData;
+ hsc->TxXferSize = Size;
+ hsc->TxXferCount = Size;
+
+ hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
+ hsc->State = HAL_SMARTCARD_STATE_BUSY_TX;
+
+ /* Set the SMARTCARD DMA transfert complete callback */
+ hsc->hdmatx->XferCpltCallback = SMARTCARD_DMATransmitCplt;
+
+ /* Set the DMA error callback */
+ hsc->hdmatx->XferErrorCallback = SMARTCARD_DMAError;
+
+ /* Enable the SMARTCARD transmit DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(hsc->hdmatx, *(uint32_t*)tmp, (uint32_t)&hsc->Instance->DR, Size);
+
+ /* Enable the DMA transfer for transmit request by setting the DMAT bit
+ in the SMARTCARD CR3 register */
+ hsc->Instance->CR3 |= USART_CR3_DMAT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in non blocking mode
+ * @param hsc: usart handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be received
+ * @note When the SMARTCARD parity is enabled (PCE = 1) the data received contain the parity bit.s
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+ uint32_t tmpstate;
+
+ tmpstate = hsc->State;
+ if((tmpstate == HAL_SMARTCARD_STATE_READY) || (tmpstate == HAL_SMARTCARD_STATE_BUSY_TX))
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsc);
+
+ hsc->pRxBuffPtr = pData;
+ hsc->RxXferSize = Size;
+
+ hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
+ hsc->State = HAL_SMARTCARD_STATE_BUSY_RX;
+
+ /* Set the SMARTCARD DMA transfert complete callback */
+ hsc->hdmarx->XferCpltCallback = SMARTCARD_DMAReceiveCplt;
+
+ /* Set the DMA error callback */
+ hsc->hdmarx->XferErrorCallback = SMARTCARD_DMAError;
+
+ /* Enable the DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(hsc->hdmarx, (uint32_t)&hsc->Instance->DR, *(uint32_t*)tmp, Size);
+
+ /* Enable the DMA transfer for the receiver request by setting the DMAR bit
+ in the SMARTCARD CR3 register */
+ hsc->Instance->CR3 |= USART_CR3_DMAR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief This function handles SMARTCARD interrupt request.
+ * @param hsc: usart handle
+ * @retval None
+ */
+void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ tmp1 = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_PE);
+ tmp2 = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_PE);
+ /* SMARTCARD parity error interrupt occured --------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_SMARTCARD_CLEAR_FLAG(hsc, SMARTCARD_FLAG_PE);
+ hsc->ErrorCode |= HAL_SMARTCARD_ERROR_PE;
+ }
+
+ tmp1 = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_FE);
+ tmp2 = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_ERR);
+ /* SMARTCARD frame error interrupt occured ---------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_SMARTCARD_CLEAR_FLAG(hsc, SMARTCARD_FLAG_FE);
+ hsc->ErrorCode |= HAL_SMARTCARD_ERROR_FE;
+ }
+
+ tmp1 = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_NE);
+ tmp2 = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_ERR);
+ /* SMARTCARD noise error interrupt occured ---------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_SMARTCARD_CLEAR_FLAG(hsc, SMARTCARD_FLAG_NE);
+ hsc->ErrorCode |= HAL_SMARTCARD_ERROR_NE;
+ }
+
+ tmp1 = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_ORE);
+ tmp2 = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_ERR);
+ /* SMARTCARD Over-Run interrupt occured ------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_SMARTCARD_CLEAR_FLAG(hsc, SMARTCARD_FLAG_ORE);
+ hsc->ErrorCode |= HAL_SMARTCARD_ERROR_ORE;
+ }
+
+ tmp1 = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_RXNE);
+ tmp2 = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_RXNE);
+ /* SMARTCARD in mode Receiver ----------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ SMARTCARD_Receive_IT(hsc);
+ __HAL_SMARTCARD_CLEAR_FLAG(hsc, SMARTCARD_FLAG_RXNE);
+ }
+
+ tmp1 = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_TC);
+ tmp2 = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_TC);
+ /* SMARTCARD in mode Transmitter -------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ SMARTCARD_Transmit_IT(hsc);
+ __HAL_SMARTCARD_CLEAR_FLAG(hsc, SMARTCARD_FLAG_TC);
+ }
+
+ /* Call the Error call Back in case of Errors */
+ if(hsc->ErrorCode != HAL_SMARTCARD_ERROR_NONE)
+ {
+ /* Set the SMARTCARD state ready to be able to start again the process */
+ hsc->State= HAL_SMARTCARD_STATE_READY;
+ HAL_SMARTCARD_ErrorCallback(hsc);
+ }
+}
+
+/**
+ * @brief Tx Transfer completed callbacks
+ * @param hsc: usart handle
+ * @retval None
+ */
+ __weak void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SMARTCARD_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer completed callbacks
+ * @param hsc: usart handle
+ * @retval None
+ */
+__weak void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SMARTCARD_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief SMARTCARD error callbacks
+ * @param hsc: usart handle
+ * @retval None
+ */
+ __weak void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SMARTCARD_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SMARTCARD_Group3 Peripheral State and Errors functions
+ * @brief SMARTCARD State and Errors functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State and Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the SmartCard.
+ (+) HAL_SMARTCARD_GetState() API can be helpful to check in run-time the state of the SmartCard peripheral.
+ (+) HAL_SMARTCARD_GetError() check in run-time errors that could be occured durung communication.
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief return the SMARTCARD state
+ * @param hsc: usart handle
+ * @retval HAL state
+ */
+HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc)
+{
+ return hsc->State;
+}
+
+/**
+ * @brief Return the SMARTCARD error code
+ * @param hsc : pointer to a SMARTCARD_HandleTypeDef structure that contains
+ * the configuration information for the specified SMARTCARD.
+ * @retval SMARTCARD Error Code
+ */
+uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc)
+{
+ return hsc->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief DMA SMARTCARD transmit process complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma)
+{
+ SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ hsc->TxXferCount = 0;
+
+ /* Disable the DMA transfer for transmit request by setting the DMAT bit
+ in the USART CR3 register */
+ hsc->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAT);
+
+ /* Wait for SMARTCARD TC Flag */
+ if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TC, RESET, SMARTCARD_TIMEOUT_VALUE) != HAL_OK)
+ {
+ /* Timeout Occured */
+ hsc->State = HAL_SMARTCARD_STATE_TIMEOUT;
+ HAL_SMARTCARD_ErrorCallback(hsc);
+ }
+ else
+ {
+ /* No Timeout */
+ hsc->State= HAL_SMARTCARD_STATE_READY;
+ HAL_SMARTCARD_TxCpltCallback(hsc);
+ }
+}
+
+/**
+ * @brief DMA SMARTCARD receive process complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
+{
+ SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ hsc->RxXferCount = 0;
+
+ /* Disable the DMA transfer for the receiver request by setting the DMAR bit
+ in the USART CR3 register */
+ hsc->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAR);
+
+ hsc->State= HAL_SMARTCARD_STATE_READY;
+
+ HAL_SMARTCARD_RxCpltCallback(hsc);
+}
+
+/**
+ * @brief DMA SMARTCARD communication error callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma)
+{
+ SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ hsc->RxXferCount = 0;
+ hsc->TxXferCount = 0;
+ hsc->ErrorCode = HAL_SMARTCARD_ERROR_DMA;
+ hsc->State= HAL_SMARTCARD_STATE_READY;
+
+ HAL_SMARTCARD_ErrorCallback(hsc);
+}
+
+/**
+ * @brief This function handles SMARTCARD Communication Timeout.
+ * @param hsc: SMARTCARD handle
+ * @param Flag: specifies the SMARTCARD flag to check.
+ * @param Status: The new Flag status (SET or RESET).
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Wait until flag is set */
+ if(Status == RESET)
+ {
+ while(__HAL_SMARTCARD_GET_FLAG(hsc, Flag) == RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable TXE and RXNE interrupts for the interrupt process */
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_TXE);
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_RXNE);
+
+ hsc->State= HAL_SMARTCARD_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ else
+ {
+ while(__HAL_SMARTCARD_GET_FLAG(hsc, Flag) != RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable TXE and RXNE interrupts for the interrupt process */
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_TXE);
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_RXNE);
+
+ hsc->State= HAL_SMARTCARD_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Send an amount of data in non blocking mode
+ * @param hsc: usart handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc)
+{
+ uint16_t* tmp;
+
+ if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hsc);
+
+ if(hsc->Init.WordLength == SMARTCARD_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) hsc->pTxBuffPtr;
+ hsc->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF);
+ if(hsc->Init.Parity == SMARTCARD_PARITY_NONE)
+ {
+ hsc->pTxBuffPtr += 2;
+ }
+ else
+ {
+ hsc->pTxBuffPtr += 1;
+ }
+ }
+ else
+ {
+ hsc->Instance->DR = (uint8_t)(*hsc->pTxBuffPtr++ & (uint8_t)0x00FF);
+ }
+
+ if(--hsc->TxXferCount == 0)
+ {
+ /* Disable the SMARTCARD Transmit Complete Interrupt */
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_TC);
+
+ /* Disable the SMARTCARD Parity Error Interrupt */
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_PE);
+
+ /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_ERR);
+
+ hsc->State = HAL_SMARTCARD_STATE_READY;
+
+ /* Call the Process Unlocked before calling the Tx call back API to give the possibiity to
+ start again the Transmission under the Tx call back API */
+ __HAL_UNLOCK(hsc);
+
+ HAL_SMARTCARD_TxCpltCallback(hsc);
+
+ return HAL_OK;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in non blocking mode
+ * @param hsc: usart handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc)
+{
+ uint16_t* tmp;
+
+ if(hsc->State == HAL_SMARTCARD_STATE_BUSY_RX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(hsc);
+
+ if(hsc->Init.WordLength == SMARTCARD_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) hsc->pRxBuffPtr;
+ if(hsc->Init.Parity == SMARTCARD_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(hsc->Instance->DR & (uint16_t)0x01FF);
+ hsc->pRxBuffPtr += 2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(hsc->Instance->DR & (uint16_t)0x00FF);
+ hsc->pRxBuffPtr += 1;
+ }
+ }
+ else
+ {
+ if(hsc->Init.Parity == SMARTCARD_PARITY_NONE)
+ {
+ *hsc->pRxBuffPtr++ = (uint8_t)(hsc->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ *hsc->pRxBuffPtr++ = (uint8_t)(hsc->Instance->DR & (uint8_t)0x007F);
+ }
+ }
+
+ if(--hsc->RxXferCount == 0)
+ {
+ while(HAL_IS_BIT_SET(hsc->Instance->SR, SMARTCARD_FLAG_RXNE))
+ {
+ }
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_RXNE);
+
+ /* Disable the SMARTCARD Parity Error Interrupt */
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_PE);
+
+ /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */
+ __SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_ERR);
+
+ hsc->State = HAL_SMARTCARD_STATE_READY;
+
+ /* Call the Process Unlocked before calling the Rx call back API to give the possibiity to
+ start again the receiption under the Rx call back API */
+ __HAL_UNLOCK(hsc);
+
+ HAL_SMARTCARD_RxCpltCallback(hsc);
+
+ return HAL_OK;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hsc);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Configure the SMARTCARD peripheral
+ * @param hsc: usart handle
+ * @retval None
+ */
+static void SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsc)
+{
+ uint32_t tmpreg = 0x00;
+
+ /* Check the parameters */
+ assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance));
+ assert_param(IS_SMARTCARD_POLARITY(hsc->Init.CLKPolarity));
+ assert_param(IS_SMARTCARD_PHASE(hsc->Init.CLKPhase));
+ assert_param(IS_SMARTCARD_LASTBIT(hsc->Init.CLKLastBit));
+ assert_param(IS_SMARTCARD_BAUDRATE(hsc->Init.BaudRate));
+ assert_param(IS_SMARTCARD_WORD_LENGTH(hsc->Init.WordLength));
+ assert_param(IS_SMARTCARD_STOPBITS(hsc->Init.StopBits));
+ assert_param(IS_SMARTCARD_PARITY(hsc->Init.Parity));
+ assert_param(IS_SMARTCARD_MODE(hsc->Init.Mode));
+ assert_param(IS_SMARTCARD_NACK_STATE(hsc->Init.NACKState));
+
+ /* The LBCL, CPOL and CPHA bits have to be selected when both the transmitter and the
+ receiver are disabled (TE=RE=0) to ensure that the clock pulses function correctly. */
+ hsc->Instance->CR1 &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE));
+
+ /*---------------------------- USART CR2 Configuration ---------------------*/
+ tmpreg = hsc->Instance->CR2;
+ /* Clear CLKEN, CPOL, CPHA and LBCL bits */
+ tmpreg &= (uint32_t)~((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_CLKEN | USART_CR2_LBCL));
+ /* Configure the SMARTCARD Clock, CPOL, CPHA and LastBit -----------------------*/
+ /* Set CPOL bit according to hsc->Init.CLKPolarity value */
+ /* Set CPHA bit according to hsc->Init.CLKPhase value */
+ /* Set LBCL bit according to hsc->Init.CLKLastBit value */
+ /* Set Stop Bits: Set STOP[13:12] bits according to hsc->Init.StopBits value */
+ tmpreg |= (uint32_t)(USART_CR2_CLKEN | hsc->Init.CLKPolarity |
+ hsc->Init.CLKPhase| hsc->Init.CLKLastBit | hsc->Init.StopBits);
+ /* Write to USART CR2 */
+ hsc->Instance->CR2 = (uint32_t)tmpreg;
+
+ tmpreg = hsc->Instance->CR2;
+
+ /* Clear STOP[13:12] bits */
+ tmpreg &= (uint32_t)~((uint32_t)USART_CR2_STOP);
+
+ /* Set Stop Bits: Set STOP[13:12] bits according to hsc->Init.StopBits value */
+ tmpreg |= (uint32_t)(hsc->Init.StopBits);
+
+ /* Write to USART CR2 */
+ hsc->Instance->CR2 = (uint32_t)tmpreg;
+
+ /*-------------------------- USART CR1 Configuration -----------------------*/
+ tmpreg = hsc->Instance->CR1;
+
+ /* Clear M, PCE, PS, TE and RE bits */
+ tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | \
+ USART_CR1_RE));
+
+ /* Configure the SMARTCARD Word Length, Parity and mode:
+ Set the M bits according to hsc->Init.WordLength value
+ Set PCE and PS bits according to hsc->Init.Parity value
+ Set TE and RE bits according to hsc->Init.Mode value */
+ tmpreg |= (uint32_t)hsc->Init.WordLength | hsc->Init.Parity | hsc->Init.Mode;
+
+ /* Write to USART CR1 */
+ hsc->Instance->CR1 = (uint32_t)tmpreg;
+
+ /*-------------------------- USART CR3 Configuration -----------------------*/
+ /* Clear CTSE and RTSE bits */
+ hsc->Instance->CR3 &= (uint32_t)~((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE));
+
+ /*-------------------------- USART BRR Configuration -----------------------*/
+ if((hsc->Instance == USART1) || (hsc->Instance == USART6))
+ {
+ hsc->Instance->BRR = __SMARTCARD_BRR(HAL_RCC_GetPCLK2Freq(), hsc->Init.BaudRate);
+ }
+ else
+ {
+ hsc->Instance->BRR = __SMARTCARD_BRR(HAL_RCC_GetPCLK1Freq(), hsc->Init.BaudRate);
+ }
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_SMARTCARD_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_spi.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_spi.c
new file mode 100644
index 0000000..40370dc
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_spi.c
@@ -0,0 +1,2034 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_spi.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief SPI HAL module driver.
+ *
+ * This file provides firmware functions to manage the following
+ * functionalities of the Serial Peripheral Interface (SPI) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The SPI HAL driver can be used as follows:
+
+ (#) Declare a SPI_HandleTypeDef handle structure, for example:
+ SPI_HandleTypeDef hspi;
+
+ (#)Initialize the SPI low level resources by implement the HAL_SPI_MspInit ()API:
+ (##) Enable the SPIx interface clock
+ (##) SPI pins configuration
+ (+++) Enable the clock for the SPI GPIOs
+ (+++) Configure these SPI pins as alternate function push-pull
+ (##) NVIC configuration if you need to use interrupt process
+ (+++) Configure the SPIx interrupt priority
+ (+++) Enable the NVIC SPI IRQ handle
+ (##) DMA Configuration if you need to use DMA process
+ (+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive stream
+ (+++) Enable the DMAx interface clock using
+ (+++) Configure the DMA handle parameters
+ (+++) Configure the DMA Tx or Rx Stream
+ (+++) Associate the initilalized hdma_tx handle to the hspi DMA Tx or Rx handle
+ (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Stream
+
+ (#) Program the Mode, Direction , Data size, Baudrate Prescaler, NSS
+ management, Clock polarity and phase, FirstBit and CRC configuration in the hspi Init structure.
+
+ (#) Initialize the SPI registers by calling the HAL_SPI_Init() API:
+ (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc)
+ by calling the customed HAL_SPI_MspInit(&hspi) API.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup SPI
+ * @brief SPI HAL module driver
+ * @{
+ */
+
+#ifdef HAL_SPI_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define SPI_TIMEOUT_VALUE 10
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void SPI_TxCloseIRQHandler(SPI_HandleTypeDef *hspi);
+static void SPI_TxISR(SPI_HandleTypeDef *hspi);
+static void SPI_RxCloseIRQHandler(SPI_HandleTypeDef *hspi);
+static void SPI_2LinesRxISR(SPI_HandleTypeDef *hspi);
+static void SPI_RxISR(SPI_HandleTypeDef *hspi);
+static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma);
+static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
+static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma);
+static void SPI_DMAError(DMA_HandleTypeDef *hdma);
+static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup SPI_Private_Functions
+ * @{
+ */
+
+/** @defgroup SPI_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization and de-initialization functions #####
+ ===============================================================================
+ [..] This subsection provides a set of functions allowing to initialize and
+ de-initialiaze the SPIx peripheral:
+
+ (+) User must Implement HAL_SPI_MspInit() function in which he configures
+ all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ).
+
+ (+) Call the function HAL_SPI_Init() to configure the selected device with
+ the selected configuration:
+ (++) Mode
+ (++) Direction
+ (++) Data Size
+ (++) Clock Polarity and Phase
+ (++) NSS Management
+ (++) BaudRate Prescaler
+ (++) FirstBit
+ (++) TIMode
+ (++) CRC Calculation
+ (++) CRC Polynomial if CRC enabled
+
+ (+) Call the function HAL_SPI_DeInit() to restore the default configuration
+ of the selected SPIx periperal.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the SPI according to the specified parameters
+ * in the SPI_InitTypeDef and create the associated handle.
+ * @param hspi: SPI handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi)
+{
+ /* Check the SPI handle allocation */
+ if(hspi == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_SPI_MODE(hspi->Init.Mode));
+ assert_param(IS_SPI_DIRECTION_MODE(hspi->Init.Direction));
+ assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize));
+ assert_param(IS_SPI_CPOL(hspi->Init.CLKPolarity));
+ assert_param(IS_SPI_CPHA(hspi->Init.CLKPhase));
+ assert_param(IS_SPI_NSS(hspi->Init.NSS));
+ assert_param(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler));
+ assert_param(IS_SPI_FIRST_BIT(hspi->Init.FirstBit));
+ assert_param(IS_SPI_TIMODE(hspi->Init.TIMode));
+ assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation));
+ assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial));
+
+ if(hspi->State == HAL_SPI_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC... */
+ HAL_SPI_MspInit(hspi);
+ }
+
+ hspi->State = HAL_SPI_STATE_BUSY;
+
+ /* Disble the selected SPI peripheral */
+ __HAL_SPI_DISABLE(hspi);
+
+ /*----------------------- SPIx CR1 & CR2 Configuration ---------------------*/
+ /* Configure : SPI Mode, Communication Mode, Data size, Clock polarity and phase, NSS management,
+ Communication speed, First bit and CRC calculation state */
+ hspi->Instance->CR1 = (hspi->Init.Mode | hspi->Init.Direction | hspi->Init.DataSize |
+ hspi->Init.CLKPolarity | hspi->Init.CLKPhase | (hspi->Init.NSS & SPI_CR1_SSM) |
+ hspi->Init.BaudRatePrescaler | hspi->Init.FirstBit | hspi->Init.CRCCalculation);
+
+ /* Configure : NSS management */
+ hspi->Instance->CR2 = (((hspi->Init.NSS >> 16) & SPI_CR2_SSOE) | hspi->Init.TIMode);
+
+ /*---------------------------- SPIx CRCPOLY Configuration ------------------*/
+ /* Configure : CRC Polynomial */
+ hspi->Instance->CRCPR = hspi->Init.CRCPolynomial;
+
+ /* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */
+ hspi->Instance->I2SCFGR &= (uint32_t)(~SPI_I2SCFGR_I2SMOD);
+
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+ hspi->State = HAL_SPI_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the SPI peripheral
+ * @param hspi: SPI handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi)
+{
+ /* Check the SPI handle allocation */
+ if(hspi == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Disable the SPI Peripheral Clock */
+ __HAL_SPI_DISABLE(hspi);
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */
+ HAL_SPI_MspDeInit(hspi);
+
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+ hspi->State = HAL_SPI_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hspi);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief SPI MSP Init
+ * @param hspi: SPI handle
+ * @retval None
+ */
+ __weak void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi)
+ {
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SPI_MspInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief SPI MSP DeInit
+ * @param hspi: SPI handle
+ * @retval None
+ */
+ __weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SPI_MspDeInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SPI_Group2 IO operation functions
+ * @brief Data transfers functions
+ *
+@verbatim
+ ==============================================================================
+ ##### IO operation functions #####
+ ===============================================================================
+ This subsection provides a set of functions allowing to manage the SPI
+ data transfers.
+
+ [..] The SPI supports master and slave mode :
+
+ (#) There are two mode of transfer:
+ (++) Blocking mode: The communication is performed in polling mode.
+ The HAL status of all data processing is returned by the same function
+ after finishing transfer.
+ (++) No-Blocking mode: The communication is performed using Interrupts
+ or DMA, These API's return the HAL status.
+ The end of the data processing will be indicated through the
+ dedicated SPI IRQ when using Interrupt mode or the DMA IRQ when
+ using DMA mode.
+ The HAL_SPI_TxCpltCallback(), HAL_SPI_RxCpltCallback() and HAL_SPI_TxRxCpltCallback() user callbacks
+ will be executed respectivelly at the end of the transmit or Receive process
+ The HAL_SPI_ErrorCallback()user callback will be executed when a communication error is detected
+
+ (#) Blocking mode API's are :
+ (++) HAL_SPI_Transmit()in 1Line (simplex) and 2Lines (full duplex) mode
+ (++) HAL_SPI_Receive() in 1Line (simplex) and 2Lines (full duplex) mode
+ (++) HAL_SPI_TransmitReceive() in full duplex mode
+
+ (#) Non-Blocking mode API's with Interrupt are :
+ (++) HAL_SPI_Transmit_IT()in 1Line (simplex) and 2Lines (full duplex) mode
+ (++) HAL_SPI_Receive_IT() in 1Line (simplex) and 2Lines (full duplex) mode
+ (++) HAL_SPI_TransmitReceive_IT()in full duplex mode
+ (++) HAL_SPI_IRQHandler()
+
+ (#) No-Blocking mode functions with DMA are :
+ (++) HAL_SPI_Transmit_DMA()in 1Line (simplex) and 2Lines (full duplex) mode
+ (++) HAL_SPI_Receive_DMA() in 1Line (simplex) and 2Lines (full duplex) mode
+ (++) HAL_SPI_TransmitReceie_DMA() in full duplex mode
+
+ (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode:
+ (++) HAL_SPI_TxCpltCallback()
+ (++) HAL_SPI_RxCpltCallback()
+ (++) HAL_SPI_ErrorCallback()
+ (++) HAL_SPI_TxRxCpltCallback()
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Transmit an amount of data in blocking mode
+ * @param hspi: SPI handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+
+ if(hspi->State == HAL_SPI_STATE_READY)
+ {
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction));
+
+ /* Process Locked */
+ __HAL_LOCK(hspi);
+
+ /* Configure communication */
+ hspi->State = HAL_SPI_STATE_BUSY_TX;
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+
+ hspi->pTxBuffPtr = pData;
+ hspi->TxXferSize = Size;
+ hspi->TxXferCount = Size;
+
+ /*Init field not used in handle to zero */
+ hspi->TxISR = 0;
+ hspi->RxISR = 0;
+ hspi->RxXferSize = 0;
+ hspi->RxXferCount = 0;
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
+ {
+ /* Configure communication direction : 1Line */
+ __HAL_SPI_1LINE_TX(hspi);
+ }
+
+ /* Check if the SPI is already enabled */
+ if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
+ {
+ /* Enable SPI peripheral */
+ __HAL_SPI_ENABLE(hspi);
+ }
+
+ /* Transmit data in 8 Bit mode */
+ if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
+ {
+
+ hspi->Instance->DR = (*hspi->pTxBuffPtr++);
+ hspi->TxXferCount--;
+
+ while(hspi->TxXferCount > 0)
+ {
+ /* Wait until TXE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ hspi->Instance->DR = (*hspi->pTxBuffPtr++);
+ hspi->TxXferCount--;
+ }
+ /* Enable CRC Transmission */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+ }
+ /* Transmit data in 16 Bit mode */
+ else
+ {
+ hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
+ hspi->pTxBuffPtr+=2;
+ hspi->TxXferCount--;
+
+ while(hspi->TxXferCount > 0)
+ {
+ /* Wait until TXE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
+ hspi->pTxBuffPtr+=2;
+ hspi->TxXferCount--;
+ }
+ /* Enable CRC Transmission */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+ }
+
+ /* Wait until TXE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ return HAL_TIMEOUT;
+ }
+
+ /* Wait until Busy flag is reset before disabling SPI */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, Timeout) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ return HAL_TIMEOUT;
+ }
+
+ /* Clear OVERUN flag in 2 Lines communication mode because received is not read */
+ if(hspi->Init.Direction == SPI_DIRECTION_2LINES)
+ {
+ __HAL_SPI_CLEAR_OVRFLAG(hspi);
+ }
+
+ hspi->State = HAL_SPI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in blocking mode
+ * @param hspi: SPI handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ __IO uint16_t tmpreg;
+ uint32_t tmp = 0;
+
+ if(hspi->State == HAL_SPI_STATE_READY)
+ {
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hspi);
+
+ /* Configure communication */
+ hspi->State = HAL_SPI_STATE_BUSY_RX;
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+
+ hspi->pRxBuffPtr = pData;
+ hspi->RxXferSize = Size;
+ hspi->RxXferCount = Size;
+
+ /*Init field not used in handle to zero */
+ hspi->RxISR = 0;
+ hspi->TxISR = 0;
+ hspi->TxXferSize = 0;
+ hspi->TxXferCount = 0;
+
+ /* Configure communication direction : 1Line */
+ if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
+ {
+ __HAL_SPI_1LINE_RX(hspi);
+ }
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ if((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES))
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */
+ return HAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout);
+ }
+
+ /* Check if the SPI is already enabled */
+ if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
+ {
+ /* Enable SPI peripheral */
+ __HAL_SPI_ENABLE(hspi);
+ }
+
+ /* Receive data in 8 Bit mode */
+ if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
+ {
+ while(hspi->RxXferCount > 1)
+ {
+ /* Wait until RXNE flag is set */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ (*hspi->pRxBuffPtr++) = hspi->Instance->DR;
+ hspi->RxXferCount--;
+ }
+ /* Enable CRC Transmission */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+ }
+ /* Receive data in 16 Bit mode */
+ else
+ {
+ while(hspi->RxXferCount > 1)
+ {
+ /* Wait until RXNE flag is set to read data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
+ hspi->pRxBuffPtr+=2;
+ hspi->RxXferCount--;
+ }
+ /* Enable CRC Transmission */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+ }
+
+ /* Wait until RXNE flag is set */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Receive last data in 8 Bit mode */
+ if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
+ {
+ (*hspi->pRxBuffPtr++) = hspi->Instance->DR;
+ }
+ /* Receive last data in 16 Bit mode */
+ else
+ {
+ *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
+ hspi->pRxBuffPtr+=2;
+ }
+ hspi->RxXferCount--;
+
+ /* Wait until RXNE flag is set: CRC Received */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
+ return HAL_TIMEOUT;
+ }
+
+ /* Read CRC to Flush RXNE flag */
+ tmpreg = hspi->Instance->DR;
+ }
+
+ if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
+ {
+ /* Disable SPI peripheral */
+ __HAL_SPI_DISABLE(hspi);
+ }
+
+ hspi->State = HAL_SPI_STATE_READY;
+
+ tmp = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR);
+ /* Check if CRC error occurred */
+ if((hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) && (tmp != RESET))
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
+
+ /* Reset CRC Calculation */
+ __HAL_SPI_RESET_CRC(hspi);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ return HAL_ERROR;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit and Receive an amount of data in blocking mode
+ * @param hspi: SPI handle
+ * @param pTxData: pointer to transmission data buffer
+ * @param pRxData: pointer to reception data buffer to be
+ * @param Size: amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout)
+{
+ __IO uint16_t tmpreg;
+ uint32_t tmp = 0;
+
+ tmp = hspi->State;
+ if((tmp == HAL_SPI_STATE_READY) || (tmp == HAL_SPI_STATE_BUSY_RX))
+ {
+ if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
+
+ /* Process Locked */
+ __HAL_LOCK(hspi);
+
+ /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */
+ if(hspi->State == HAL_SPI_STATE_READY)
+ {
+ hspi->State = HAL_SPI_STATE_BUSY_TX_RX;
+ }
+
+ /* Configure communication */
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+
+ hspi->pRxBuffPtr = pRxData;
+ hspi->RxXferSize = Size;
+ hspi->RxXferCount = Size;
+
+ hspi->pTxBuffPtr = pTxData;
+ hspi->TxXferSize = Size;
+ hspi->TxXferCount = Size;
+
+ /*Init field not used in handle to zero */
+ hspi->RxISR = 0;
+ hspi->TxISR = 0;
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ /* Check if the SPI is already enabled */
+ if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
+ {
+ /* Enable SPI peripheral */
+ __HAL_SPI_ENABLE(hspi);
+ }
+
+ /* Transmit and Receive data in 16 Bit mode */
+ if(hspi->Init.DataSize == SPI_DATASIZE_16BIT)
+ {
+ hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
+ hspi->pTxBuffPtr+=2;
+ hspi->TxXferCount--;
+
+ if(hspi->TxXferCount == 0)
+ {
+ /* Enable CRC Transmission */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+
+ /* Wait until RXNE flag is set */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
+ hspi->pRxBuffPtr+=2;
+ hspi->RxXferCount--;
+ }
+ else
+ {
+ while(hspi->TxXferCount > 0)
+ {
+ /* Wait until TXE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
+ hspi->pTxBuffPtr+=2;
+ hspi->TxXferCount--;
+
+ /* Enable CRC Transmission */
+ if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED))
+ {
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+
+ /* Wait until RXNE flag is set */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
+ hspi->pRxBuffPtr+=2;
+ hspi->RxXferCount--;
+ }
+
+ /* Wait until RXNE flag is set */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
+ hspi->pRxBuffPtr+=2;
+ hspi->RxXferCount--;
+ }
+ }
+ /* Transmit and Receive data in 8 Bit mode */
+ else
+ {
+
+ hspi->Instance->DR = (*hspi->pTxBuffPtr++);
+ hspi->TxXferCount--;
+
+ if(hspi->TxXferCount == 0)
+ {
+ /* Enable CRC Transmission */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+
+ /* Wait until RXNE flag is set */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ (*hspi->pRxBuffPtr) = hspi->Instance->DR;
+ hspi->RxXferCount--;
+ }
+ else
+ {
+ while(hspi->TxXferCount > 0)
+ {
+ /* Wait until TXE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ hspi->Instance->DR = (*hspi->pTxBuffPtr++);
+ hspi->TxXferCount--;
+
+ /* Enable CRC Transmission */
+ if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED))
+ {
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+
+ /* Wait until RXNE flag is set */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ (*hspi->pRxBuffPtr++) = hspi->Instance->DR;
+ hspi->RxXferCount--;
+ }
+
+ /* Wait until RXNE flag is set */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ (*hspi->pRxBuffPtr++) = hspi->Instance->DR;
+ hspi->RxXferCount--;
+ }
+ }
+
+ /* Read CRC from DR to close CRC calculation process */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ /* Wait until RXNE flag is set */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
+ return HAL_TIMEOUT;
+ }
+ /* Read CRC */
+ tmpreg = hspi->Instance->DR;
+ }
+
+ /* Wait until Busy flag is reset before disabling SPI */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, Timeout) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ return HAL_TIMEOUT;
+ }
+
+ hspi->State = HAL_SPI_STATE_READY;
+
+ tmp = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR);
+ /* Check if CRC error occurred */
+ if((hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) && (tmp != RESET))
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ return HAL_ERROR;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit an amount of data in no-blocking mode with Interrupt
+ * @param hspi: SPI handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
+{
+ if(hspi->State == HAL_SPI_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction));
+
+ /* Process Locked */
+ __HAL_LOCK(hspi);
+
+ /* Configure communication */
+ hspi->State = HAL_SPI_STATE_BUSY_TX;
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+
+ hspi->TxISR = &SPI_TxISR;
+ hspi->pTxBuffPtr = pData;
+ hspi->TxXferSize = Size;
+ hspi->TxXferCount = Size;
+
+ /*Init field not used in handle to zero */
+ hspi->RxISR = 0;
+ hspi->RxXferSize = 0;
+ hspi->RxXferCount = 0;
+
+ /* Configure communication direction : 1Line */
+ if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
+ {
+ __HAL_SPI_1LINE_TX(hspi);
+ }
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ if (hspi->Init.Direction == SPI_DIRECTION_2LINES)
+ {
+ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE));
+ }else
+ {
+ /* Enable TXE and ERR interrupt */
+ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR));
+ }
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ /* Check if the SPI is already enabled */
+ if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
+ {
+ /* Enable SPI peripheral */
+ __HAL_SPI_ENABLE(hspi);
+ }
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in no-blocking mode with Interrupt
+ * @param hspi: SPI handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
+{
+ if(hspi->State == HAL_SPI_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hspi);
+
+ /* Configure communication */
+ hspi->State = HAL_SPI_STATE_BUSY_RX;
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+
+ hspi->RxISR = &SPI_RxISR;
+ hspi->pRxBuffPtr = pData;
+ hspi->RxXferSize = Size;
+ hspi->RxXferCount = Size ;
+
+ /*Init field not used in handle to zero */
+ hspi->TxISR = 0;
+ hspi->TxXferSize = 0;
+ hspi->TxXferCount = 0;
+
+ /* Configure communication direction : 1Line */
+ if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
+ {
+ __HAL_SPI_1LINE_RX(hspi);
+ }
+ else if((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER))
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */
+ return HAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size);
+ }
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ /* Enable TXE and ERR interrupt */
+ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR));
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ /* Note : The SPI must be enabled after unlocking current process
+ to avoid the risk of SPI interrupt handle execution before current
+ process unlock */
+
+ /* Check if the SPI is already enabled */
+ if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
+ {
+ /* Enable SPI peripheral */
+ __HAL_SPI_ENABLE(hspi);
+ }
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit and Receive an amount of data in no-blocking mode with Interrupt
+ * @param hspi: SPI handle
+ * @param pTxData: pointer to transmission data buffer
+ * @param pRxData: pointer to reception data buffer to be
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size)
+{
+ uint32_t tmp = 0;
+
+ tmp = hspi->State;
+ if((tmp == HAL_SPI_STATE_READY) || (tmp == HAL_SPI_STATE_BUSY_RX))
+ {
+ if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
+
+ /* Process locked */
+ __HAL_LOCK(hspi);
+
+ /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */
+ if(hspi->State == HAL_SPI_STATE_READY)
+ {
+ hspi->State = HAL_SPI_STATE_BUSY_TX_RX;
+ }
+
+ /* Configure communication */
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+
+ hspi->TxISR = &SPI_TxISR;
+ hspi->pTxBuffPtr = pTxData;
+ hspi->TxXferSize = Size;
+ hspi->TxXferCount = Size;
+
+ hspi->RxISR = &SPI_2LinesRxISR;
+ hspi->pRxBuffPtr = pRxData;
+ hspi->RxXferSize = Size;
+ hspi->RxXferCount = Size;
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ /* Enable TXE, RXNE and ERR interrupt */
+ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR));
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ /* Check if the SPI is already enabled */
+ if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
+ {
+ /* Enable SPI peripheral */
+ __HAL_SPI_ENABLE(hspi);
+ }
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit an amount of data in no-blocking mode with DMA
+ * @param hspi: SPI handle
+ * @param pData: pointer to data buffer
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
+{
+ if(hspi->State == HAL_SPI_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction));
+
+ /* Process Locked */
+ __HAL_LOCK(hspi);
+
+ /* Configure communication */
+ hspi->State = HAL_SPI_STATE_BUSY_TX;
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+
+ hspi->pTxBuffPtr = pData;
+ hspi->TxXferSize = Size;
+ hspi->TxXferCount = Size;
+
+ /*Init field not used in handle to zero */
+ hspi->TxISR = 0;
+ hspi->RxISR = 0;
+ hspi->RxXferSize = 0;
+ hspi->RxXferCount = 0;
+
+ /* Configure communication direction : 1Line */
+ if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
+ {
+ __HAL_SPI_1LINE_TX(hspi);
+ }
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ /* Set the SPI TxDMA transfer complete callback */
+ hspi->hdmatx->XferCpltCallback = SPI_DMATransmitCplt;
+
+ /* Set the DMA error callback */
+ hspi->hdmatx->XferErrorCallback = SPI_DMAError;
+
+ /* Enable the Tx DMA Stream */
+ HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount);
+
+ /* Enable Tx DMA Request */
+ hspi->Instance->CR2 |= SPI_CR2_TXDMAEN;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ /* Check if the SPI is already enabled */
+ if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
+ {
+ /* Enable SPI peripheral */
+ __HAL_SPI_ENABLE(hspi);
+ }
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receive an amount of data in no-blocking mode with DMA
+ * @param hspi: SPI handle
+ * @param pData: pointer to data buffer
+ * @note When the CRC feature is enabled the pData Length must be Size + 1.
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
+{
+ if(hspi->State == HAL_SPI_STATE_READY)
+ {
+ if((pData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hspi);
+
+ /* Configure communication */
+ hspi->State = HAL_SPI_STATE_BUSY_RX;
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+
+ hspi->pRxBuffPtr = pData;
+ hspi->RxXferSize = Size;
+ hspi->RxXferCount = Size;
+
+ /*Init field not used in handle to zero */
+ hspi->RxISR = 0;
+ hspi->TxISR = 0;
+ hspi->TxXferSize = 0;
+ hspi->TxXferCount = 0;
+
+ /* Configure communication direction : 1Line */
+ if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
+ {
+ __HAL_SPI_1LINE_RX(hspi);
+ }
+ else if((hspi->Init.Direction == SPI_DIRECTION_2LINES)&&(hspi->Init.Mode == SPI_MODE_MASTER))
+ {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */
+ return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size);
+ }
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ /* Set the SPI Rx DMA transfer complete callback */
+ hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt;
+
+ /* Set the DMA error callback */
+ hspi->hdmarx->XferErrorCallback = SPI_DMAError;
+
+ /* Enable the Rx DMA Stream */
+ HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount);
+
+ /* Enable Rx DMA Request */
+ hspi->Instance->CR2 |= SPI_CR2_RXDMAEN;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ /* Check if the SPI is already enabled */
+ if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
+ {
+ /* Enable SPI peripheral */
+ __HAL_SPI_ENABLE(hspi);
+ }
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Transmit and Receive an amount of data in no-blocking mode with DMA
+ * @param hspi: SPI handle
+ * @param pTxData: pointer to transmission data buffer
+ * @param pRxData: pointer to reception data buffer
+ * @note When the CRC feature is enabled the pRxData Length must be Size + 1
+ * @param Size: amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size)
+{
+ uint32_t tmpstate = 0;
+ tmpstate = hspi->State;
+ if((tmpstate == HAL_SPI_STATE_READY) || (tmpstate == HAL_SPI_STATE_BUSY_RX))
+ {
+ if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
+
+ /* Process locked */
+ __HAL_LOCK(hspi);
+
+ /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */
+ if(hspi->State == HAL_SPI_STATE_READY)
+ {
+ hspi->State = HAL_SPI_STATE_BUSY_TX_RX;
+ }
+
+ /* Configure communication */
+ hspi->ErrorCode = HAL_SPI_ERROR_NONE;
+
+ hspi->pTxBuffPtr = (uint8_t*)pTxData;
+ hspi->TxXferSize = Size;
+ hspi->TxXferCount = Size;
+
+ hspi->pRxBuffPtr = (uint8_t*)pRxData;
+ hspi->RxXferSize = Size;
+ hspi->RxXferCount = Size;
+
+ /*Init field not used in handle to zero */
+ hspi->RxISR = 0;
+ hspi->TxISR = 0;
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ /* Check if we are in Rx only or in Rx/Tx Mode and configure the DMA transfer complete callback */
+ if(hspi->State == HAL_SPI_STATE_BUSY_RX)
+ {
+ hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt;
+ }
+ else
+ {
+ hspi->hdmarx->XferCpltCallback = SPI_DMATransmitReceiveCplt;
+ }
+
+ /* Set the DMA error callback */
+ hspi->hdmarx->XferErrorCallback = SPI_DMAError;
+
+ /* Enable the Rx DMA Stream */
+ HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount);
+
+ /* Enable Rx DMA Request */
+ hspi->Instance->CR2 |= SPI_CR2_RXDMAEN;
+
+ /* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing
+ is performed in DMA reception complete callback */
+ hspi->hdmatx->XferCpltCallback = NULL;
+
+ /* Set the DMA error callback */
+ hspi->hdmatx->XferErrorCallback = SPI_DMAError;
+
+ /* Enable the Tx DMA Stream */
+ HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount);
+
+ /* Enable Tx DMA Request */
+ hspi->Instance->CR2 |= SPI_CR2_TXDMAEN;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ /* Check if the SPI is already enabled */
+ if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
+ {
+ /* Enable SPI peripheral */
+ __HAL_SPI_ENABLE(hspi);
+ }
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief This function handles SPI interrupt request.
+ * @param hspi: SPI handle
+ * @retval HAL status
+ */
+void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi)
+{
+ uint32_t tmp1 = 0, tmp2 = 0, tmp3 = 0;
+
+ tmp1 = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE);
+ tmp2 = __HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_RXNE);
+ tmp3 = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR);
+ /* SPI in mode Receiver and Overrun not occurred ---------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET) && (tmp3 == RESET))
+ {
+ hspi->RxISR(hspi);
+ return;
+ }
+
+ tmp1 = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE);
+ tmp2 = __HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_TXE);
+ /* SPI in mode Tramitter ---------------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ hspi->TxISR(hspi);
+ return;
+ }
+
+ if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_ERR) != RESET)
+ {
+ /* SPI CRC error interrupt occured ---------------------------------------*/
+ if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
+ __HAL_SPI_CLEAR_CRCERRFLAG(hspi);
+ }
+ /* SPI Mode Fault error interrupt occured --------------------------------*/
+ if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_MODF) != RESET)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_MODF;
+ __HAL_SPI_CLEAR_MODFFLAG(hspi);
+ }
+
+ /* SPI Overrun error interrupt occured -----------------------------------*/
+ if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR) != RESET)
+ {
+ if(hspi->State != HAL_SPI_STATE_BUSY_TX)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_OVR;
+ __HAL_SPI_CLEAR_OVRFLAG(hspi);
+ }
+ }
+
+ /* SPI Frame error interrupt occured -------------------------------------*/
+ if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_FRE) != RESET)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FRE;
+ __HAL_SPI_CLEAR_FREFLAG(hspi);
+ }
+
+ /* Call the Error call Back in case of Errors */
+ if(hspi->ErrorCode!=HAL_SPI_ERROR_NONE)
+ {
+ hspi->State = HAL_SPI_STATE_READY;
+ HAL_SPI_ErrorCallback(hspi);
+ }
+ }
+}
+
+/**
+ * @brief Tx Transfer completed callbacks
+ * @param hspi: SPI handle
+ * @retval None
+ */
+__weak void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SPI_TxCpltCallback could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer completed callbacks
+ * @param hspi: SPI handle
+ * @retval None
+ */
+__weak void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SPI_RxCpltCallback() could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief Tx and Rx Transfer completed callbacks
+ * @param hspi: SPI handle
+ * @retval None
+ */
+__weak void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SPI_TxRxCpltCallback() could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief SPI error callbacks
+ * @param hspi: SPI handle
+ * @retval None
+ */
+ __weak void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi)
+{
+ /* NOTE : - This function Should not be modified, when the callback is needed,
+ the HAL_SPI_ErrorCallback() could be implenetd in the user file.
+ - The ErrorCode parameter in the hspi handle is updated by the SPI processes
+ and user can use HAL_SPI_GetError() API to check the latest error occured.
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SPI_Group3 Peripheral State and Errors functions
+ * @brief SPI control functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State and Errors functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the SPI.
+ (+) HAL_SPI_GetState() API can be helpful to check in run-time the state of the SPI peripheral
+ (+) HAL_SPI_GetError() check in run-time Errors occurring during communication
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the SPI state
+ * @param hspi : SPI handle
+ * @retval SPI state
+ */
+HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi)
+{
+ return hspi->State;
+}
+
+/**
+ * @brief Return the SPI error code
+ * @param hspi : SPI handle
+ * @retval SPI Error Code
+ */
+HAL_SPI_ErrorTypeDef HAL_SPI_GetError(SPI_HandleTypeDef *hspi)
+{
+ return hspi->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+ /**
+ * @brief Interrupt Handler to close Tx transfer
+ * @param hspi: SPI handle
+ * @retval void
+ */
+static void SPI_TxCloseIRQHandler(SPI_HandleTypeDef *hspi)
+{
+ /* Wait until TXE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+
+ /* Disable TXE interrupt */
+ __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE ));
+
+ /* Disable ERR interrupt if Receive process is finished */
+ if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_RXNE) == RESET)
+ {
+ __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_ERR));
+
+ /* Wait until Busy flag is reset before disabling SPI */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+
+ /* Clear OVERUN flag in 2 Lines communication mode because received is not read */
+ if(hspi->Init.Direction == SPI_DIRECTION_2LINES)
+ {
+ __HAL_SPI_CLEAR_OVRFLAG(hspi);
+ }
+
+ /* Check if Errors has been detected during transfer */
+ if(hspi->ErrorCode == HAL_SPI_ERROR_NONE)
+ {
+ /* Check if we are in Tx or in Rx/Tx Mode */
+ if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX)
+ {
+ /* Set state to READY before run the Callback Complete */
+ hspi->State = HAL_SPI_STATE_READY;
+ HAL_SPI_TxRxCpltCallback(hspi);
+ }
+ else
+ {
+ /* Set state to READY before run the Callback Complete */
+ hspi->State = HAL_SPI_STATE_READY;
+ HAL_SPI_TxCpltCallback(hspi);
+ }
+ }
+ else
+ {
+ /* Set state to READY before run the Callback Complete */
+ hspi->State = HAL_SPI_STATE_READY;
+ /* Call Error call back in case of Error */
+ HAL_SPI_ErrorCallback(hspi);
+ }
+ }
+}
+
+/**
+ * @brief Interrupt Handler to transmit amount of data in no-blocking mode
+ * @param hspi: SPI handle
+ * @retval void
+ */
+static void SPI_TxISR(SPI_HandleTypeDef *hspi)
+{
+ /* Transmit data in 8 Bit mode */
+ if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
+ {
+ hspi->Instance->DR = (*hspi->pTxBuffPtr++);
+ }
+ /* Transmit data in 16 Bit mode */
+ else
+ {
+ hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
+ hspi->pTxBuffPtr+=2;
+ }
+ hspi->TxXferCount--;
+
+ if(hspi->TxXferCount == 0)
+ {
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ /* calculate and transfer CRC on Tx line */
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+ SPI_TxCloseIRQHandler(hspi);
+ }
+}
+
+/**
+ * @brief Interrupt Handler to close Rx transfer
+ * @param hspi: SPI handle
+ * @retval void
+ */
+static void SPI_RxCloseIRQHandler(SPI_HandleTypeDef *hspi)
+{
+ __IO uint16_t tmpreg;
+
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ /* Wait until RXNE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+
+ /* Read CRC to reset RXNE flag */
+ tmpreg = hspi->Instance->DR;
+
+ /* Wait until RXNE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+
+ /* Check if CRC error occurred */
+ if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
+
+ /* Reset CRC Calculation */
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+ }
+
+ /* Disable RXNE and ERR interrupt */
+ __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE));
+
+ /* if Transmit process is finished */
+ if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_TXE) == RESET)
+ {
+ /* Disable ERR interrupt */
+ __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_ERR));
+
+ if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
+ {
+ /* Disable SPI peripheral */
+ __HAL_SPI_DISABLE(hspi);
+ }
+
+ /* Check if Errors has been detected during transfer */
+ if(hspi->ErrorCode == HAL_SPI_ERROR_NONE)
+ {
+ /* Check if we are in Rx or in Rx/Tx Mode */
+ if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX)
+ {
+ /* Set state to READY before run the Callback Complete */
+ hspi->State = HAL_SPI_STATE_READY;
+ HAL_SPI_TxRxCpltCallback(hspi);
+ }else
+ {
+ /* Set state to READY before run the Callback Complete */
+ hspi->State = HAL_SPI_STATE_READY;
+ HAL_SPI_RxCpltCallback(hspi);
+ }
+ }
+ else
+ {
+ /* Set state to READY before run the Callback Complete */
+ hspi->State = HAL_SPI_STATE_READY;
+ /* Call Error call back in case of Error */
+ HAL_SPI_ErrorCallback(hspi);
+ }
+ }
+}
+
+/**
+ * @brief Interrupt Handler to receive amount of data in 2Lines mode
+ * @param hspi: SPI handle
+ * @retval void
+ */
+static void SPI_2LinesRxISR(SPI_HandleTypeDef *hspi)
+{
+ /* Receive data in 8 Bit mode */
+ if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
+ {
+ (*hspi->pRxBuffPtr++) = hspi->Instance->DR;
+ }
+ /* Receive data in 16 Bit mode */
+ else
+ {
+ *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
+ hspi->pRxBuffPtr+=2;
+ }
+ hspi->RxXferCount--;
+
+ if(hspi->RxXferCount==0)
+ {
+ SPI_RxCloseIRQHandler(hspi);
+ }
+}
+
+/**
+ * @brief Interrupt Handler to receive amount of data in no-blocking mode
+ * @param hspi: SPI handle
+ * @retval void
+ */
+static void SPI_RxISR(SPI_HandleTypeDef *hspi)
+{
+ /* Receive data in 8 Bit mode */
+ if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
+ {
+ (*hspi->pRxBuffPtr++) = hspi->Instance->DR;
+ }
+ /* Receive data in 16 Bit mode */
+ else
+ {
+ *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
+ hspi->pRxBuffPtr+=2;
+ }
+ hspi->RxXferCount--;
+
+ /* Enable CRC Transmission */
+ if((hspi->RxXferCount == 1) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED))
+ {
+ /* Set CRC Next to calculate CRC on Rx side */
+ hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
+ }
+
+ if(hspi->RxXferCount == 0)
+ {
+ SPI_RxCloseIRQHandler(hspi);
+ }
+}
+
+/**
+ * @brief DMA SPI transmit process complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma)
+{
+ SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ /* Wait until TXE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+
+ /* Disable Tx DMA Request */
+ hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
+
+ /* Wait until Busy flag is reset before disabling SPI */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+
+ hspi->TxXferCount = 0;
+
+ hspi->State = HAL_SPI_STATE_READY;
+
+ /* Clear OVERUN flag in 2 Lines communication mode because received is not read */
+ if(hspi->Init.Direction == SPI_DIRECTION_2LINES)
+ {
+ __HAL_SPI_CLEAR_OVRFLAG(hspi);
+ }
+
+ /* Check if Errors has been detected during transfer */
+ if(hspi->ErrorCode != HAL_SPI_ERROR_NONE)
+ {
+ HAL_SPI_ErrorCallback(hspi);
+ }
+ else
+ {
+ HAL_SPI_TxCpltCallback(hspi);
+ }
+}
+
+/**
+ * @brief DMA SPI receive process complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
+{
+ __IO uint16_t tmpreg;
+
+ SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
+ {
+ /* Disable SPI peripheral */
+ __HAL_SPI_DISABLE(hspi);
+ }
+
+ /* Disable Rx DMA Request */
+ hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ /* Wait until RXNE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+
+ /* Read CRC */
+ tmpreg = hspi->Instance->DR;
+
+ /* Wait until RXNE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+ }
+
+ hspi->RxXferCount = 0;
+ hspi->State = HAL_SPI_STATE_READY;
+
+ /* Check if CRC error occurred */
+ if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
+ __HAL_SPI_CLEAR_CRCERRFLAG(hspi);
+ }
+
+ /* Check if Errors has been detected during transfer */
+ if(hspi->ErrorCode != HAL_SPI_ERROR_NONE)
+ {
+ HAL_SPI_ErrorCallback(hspi);
+ }
+ else
+ {
+ HAL_SPI_RxCpltCallback(hspi);
+ }
+}
+
+/**
+ * @brief DMA SPI transmit receive process complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma)
+{
+ __IO uint16_t tmpreg;
+
+ SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ /* Check if CRC is done on going (RXNE flag set) */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) == HAL_OK)
+ {
+ /* Wait until RXNE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+ }
+ /* Read CRC */
+ tmpreg = hspi->Instance->DR;
+ }
+
+ /* Wait until TXE flag is set to send data */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+ /* Disable Tx DMA Request */
+ hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
+
+ /* Wait until Busy flag is reset before disabling SPI */
+ if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
+ }
+
+ /* Disable Rx DMA Request */
+ hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
+
+ hspi->TxXferCount = 0;
+ hspi->RxXferCount = 0;
+
+ hspi->State = HAL_SPI_STATE_READY;
+
+ /* Check if CRC error occurred */
+ if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
+ {
+ hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
+ __HAL_SPI_CLEAR_CRCERRFLAG(hspi);
+ }
+
+ /* Check if Errors has been detected during transfer */
+ if(hspi->ErrorCode != HAL_SPI_ERROR_NONE)
+ {
+ HAL_SPI_ErrorCallback(hspi);
+ }
+ else
+ {
+ HAL_SPI_TxRxCpltCallback(hspi);
+ }
+}
+
+/**
+ * @brief DMA SPI communication error callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void SPI_DMAError(DMA_HandleTypeDef *hdma)
+{
+ SPI_HandleTypeDef* hspi = (SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ hspi->TxXferCount = 0;
+ hspi->RxXferCount = 0;
+ hspi->State= HAL_SPI_STATE_READY;
+ hspi->ErrorCode |= HAL_SPI_ERROR_DMA;
+ HAL_SPI_ErrorCallback(hspi);
+}
+
+/**
+ * @brief This function handles SPI Communication Timeout.
+ * @param hspi: SPI handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Wait until flag is set */
+ if(Status == RESET)
+ {
+ while(__HAL_SPI_GET_FLAG(hspi, Flag) == RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable the SPI and reset the CRC: the CRC value should be cleared
+ on both master and slave sides in order to resynchronize the master
+ and slave for their respective CRC calculation */
+
+ /* Disable TXE, RXNE and ERR interrupts for the interrupt process */
+ __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR));
+
+ /* Disable SPI peripheral */
+ __HAL_SPI_DISABLE(hspi);
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ hspi->State= HAL_SPI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ else
+ {
+ while(__HAL_SPI_GET_FLAG(hspi, Flag) != RESET)
+ {
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable the SPI and reset the CRC: the CRC value should be cleared
+ on both master and slave sides in order to resynchronize the master
+ and slave for their respective CRC calculation */
+
+ /* Disable TXE, RXNE and ERR interrupts for the interrupt process */
+ __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR));
+
+ /* Disable SPI peripheral */
+ __HAL_SPI_DISABLE(hspi);
+
+ /* Reset CRC Calculation */
+ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)
+ {
+ __HAL_SPI_RESET_CRC(hspi);
+ }
+
+ hspi->State= HAL_SPI_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hspi);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ return HAL_OK;
+}
+
+
+/**
+ * @}
+ */
+
+#endif /* HAL_SPI_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sram.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sram.c
new file mode 100644
index 0000000..9aef895
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sram.c
@@ -0,0 +1,664 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_sram.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief SRAM HAL module driver.
+ * This file provides a generic firmware to drive SRAM memories
+ * mounted as external device.
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ This driver is a generic layered driver which contains a set of APIs used to
+ control SRAM memories. It uses the FMC layer functions to interface
+ with SRAM devices.
+ The following sequence should be followed to configure the FMC/FSMC to interface
+ with SRAM/PSRAM memories:
+
+ (#) Declare a SRAM_HandleTypeDef handle structure, for example:
+ SRAM_HandleTypeDef hsram; and:
+
+ (++) Fill the SRAM_HandleTypeDef handle "Init" field with the allowed
+ values of the structure member.
+
+ (++) Fill the SRAM_HandleTypeDef handle "Instance" field with a predefined
+ base register instance for NOR or SRAM device
+
+ (++) Fill the SRAM_HandleTypeDef handle "Extended" field with a predefined
+ base register instance for NOR or SRAM extended mode
+
+ (#) Declare two FMC_NORSRAM_TimingTypeDef structures, for both normal and extended
+ mode timings; for example:
+ FMC_NORSRAM_TimingTypeDef Timing and FMC_NORSRAM_TimingTypeDef ExTiming;
+ and fill its fields with the allowed values of the structure member.
+
+ (#) Initialize the SRAM Controller by calling the function HAL_SRAM_Init(). This function
+ performs the following sequence:
+
+ (##) MSP hardware layer configuration using the function HAL_SRAM_MspInit()
+ (##) Control register configuration using the FMC NORSRAM interface function
+ FMC_NORSRAM_Init()
+ (##) Timing register configuration using the FMC NORSRAM interface function
+ FMC_NORSRAM_Timing_Init()
+ (##) Extended mode Timing register configuration using the FMC NORSRAM interface function
+ FMC_NORSRAM_Extended_Timing_Init()
+ (##) Enable the SRAM device using the macro __FMC_NORSRAM_ENABLE()
+
+ (#) At this stage you can perform read/write accesses from/to the memory connected
+ to the NOR/SRAM Bank. You can perform either polling or DMA transfer using the
+ following APIs:
+ (++) HAL_SRAM_Read()/HAL_SRAM_Write() for polling read/write access
+ (++) HAL_SRAM_Read_DMA()/HAL_SRAM_Write_DMA() for DMA read/write transfer
+
+ (#) You can also control the SRAM device by calling the control APIs HAL_SRAM_WriteOperation_Enable()/
+ HAL_SRAM_WriteOperation_Disable() to respectively enable/disable the SRAM write operation
+
+ (#) You can continuously monitor the SRAM device HAL state by calling the function
+ HAL_SRAM_GetState()
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup SRAM
+ * @brief SRAM driver modules
+ * @{
+ */
+#ifdef HAL_SRAM_MODULE_ENABLED
+
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup SRAM_Private_Functions
+ * @{
+ */
+
+/** @defgroup SRAM_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### SRAM Initialization and de_initialization functions #####
+ ==============================================================================
+ [..] This section provides functions allowing to initialize/de-initialize
+ the SRAM memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Performs the SRAM device initialization sequence
+ * @param hsram: pointer to SRAM handle
+ * @param Timing: Pointer to SRAM control timing structure
+ * @param ExtTiming: Pointer to SRAM extended mode timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_Init(SRAM_HandleTypeDef *hsram, FMC_NORSRAM_TimingTypeDef *Timing, FMC_NORSRAM_TimingTypeDef *ExtTiming)
+{
+ /* Check the SRAM handle parameter */
+ if(hsram == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ if(hsram->State == HAL_SRAM_STATE_RESET)
+ {
+ /* Initialize the low level hardware (MSP) */
+ HAL_SRAM_MspInit(hsram);
+ }
+
+ /* Initialize SRAM control Interface */
+ FMC_NORSRAM_Init(hsram->Instance, &(hsram->Init));
+
+ /* Initialize SRAM timing Interface */
+ FMC_NORSRAM_Timing_Init(hsram->Instance, Timing, hsram->Init.NSBank);
+
+ /* Initialize SRAM extended mode timing Interface */
+ FMC_NORSRAM_Extended_Timing_Init(hsram->Extended, ExtTiming, hsram->Init.NSBank, hsram->Init.ExtendedMode);
+
+ /* Enable the NORSRAM device */
+ __FMC_NORSRAM_ENABLE(hsram->Instance, hsram->Init.NSBank);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Performs the SRAM device De-initialization sequence.
+ * @param hsram: pointer to SRAM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_DeInit(SRAM_HandleTypeDef *hsram)
+{
+ /* De-Initialize the low level hardware (MSP) */
+ HAL_SRAM_MspDeInit(hsram);
+
+ /* Configure the SRAM registers with their reset values */
+ FMC_NORSRAM_DeInit(hsram->Instance, hsram->Extended, hsram->Init.NSBank);
+
+ hsram->State = HAL_SRAM_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief SRAM MSP Init.
+ * @param hsram: pointer to SRAM handle
+ * @retval None
+ */
+__weak void HAL_SRAM_MspInit(SRAM_HandleTypeDef *hsram)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SRAM_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief SRAM MSP DeInit.
+ * @param hsram: pointer to SRAM handle
+ * @retval None
+ */
+__weak void HAL_SRAM_MspDeInit(SRAM_HandleTypeDef *hsram)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SRAM_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DMA transfer complete callback.
+ * @param hsram: pointer to SRAM handle
+ * @retval none
+ */
+__weak void HAL_SRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SRAM_DMA_XferCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DMA transfer complete error callback.
+ * @param hsram: pointer to SRAM handle
+ * @retval none
+ */
+__weak void HAL_SRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_SRAM_DMA_XferErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SRAM_Group2 Input and Output functions
+ * @brief Input Output and memory control functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### SRAM Input and Output functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to use and control the SRAM memory
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Reads 8-bit buffer from SRAM memory.
+ * @param hsram: pointer to SRAM handle
+ * @param pAddress: Pointer to read start address
+ * @param pDstBuffer: Pointer to destination buffer
+ * @param BufferSize: Size of the buffer to read from memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_Read_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pDstBuffer, uint32_t BufferSize)
+{
+ __IO uint8_t * pSramAddress = (uint8_t *)pAddress;
+
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_BUSY;
+
+ /* Read data from memory */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *pDstBuffer = *(__IO uint8_t *)pSramAddress;
+ pDstBuffer++;
+ pSramAddress++;
+ }
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Writes 8-bit buffer to SRAM memory.
+ * @param hsram: pointer to SRAM handle
+ * @param pAddress: Pointer to write start address
+ * @param pSrcBuffer: Pointer to source buffer to write
+ * @param BufferSize: Size of the buffer to write to memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_Write_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pSrcBuffer, uint32_t BufferSize)
+{
+ __IO uint8_t * pSramAddress = (uint8_t *)pAddress;
+
+ /* Check the SRAM controller state */
+ if(hsram->State == HAL_SRAM_STATE_PROTECTED)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_BUSY;
+
+ /* Write data to memory */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *(__IO uint8_t *)pSramAddress = *pSrcBuffer;
+ pSrcBuffer++;
+ pSramAddress++;
+ }
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Reads 16-bit buffer from SRAM memory.
+ * @param hsram: pointer to SRAM handle
+ * @param pAddress: Pointer to read start address
+ * @param pDstBuffer: Pointer to destination buffer
+ * @param BufferSize: Size of the buffer to read from memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_Read_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pDstBuffer, uint32_t BufferSize)
+{
+ __IO uint16_t * pSramAddress = (uint16_t *)pAddress;
+
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_BUSY;
+
+ /* Read data from memory */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *pDstBuffer = *(__IO uint16_t *)pSramAddress;
+ pDstBuffer++;
+ pSramAddress++;
+ }
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Writes 16-bit buffer to SRAM memory.
+ * @param hsram: pointer to SRAM handle
+ * @param pAddress: Pointer to write start address
+ * @param pSrcBuffer: Pointer to source buffer to write
+ * @param BufferSize: Size of the buffer to write to memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_Write_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pSrcBuffer, uint32_t BufferSize)
+{
+ __IO uint16_t * pSramAddress = (uint16_t *)pAddress;
+
+ /* Check the SRAM controller state */
+ if(hsram->State == HAL_SRAM_STATE_PROTECTED)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_BUSY;
+
+ /* Write data to memory */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *(__IO uint16_t *)pSramAddress = *pSrcBuffer;
+ pSrcBuffer++;
+ pSramAddress++;
+ }
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Reads 32-bit buffer from SRAM memory.
+ * @param hsram: pointer to SRAM handle
+ * @param pAddress: Pointer to read start address
+ * @param pDstBuffer: Pointer to destination buffer
+ * @param BufferSize: Size of the buffer to read from memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_Read_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize)
+{
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_BUSY;
+
+ /* Read data from memory */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *pDstBuffer = *(__IO uint32_t *)pAddress;
+ pDstBuffer++;
+ pAddress++;
+ }
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Writes 32-bit buffer to SRAM memory.
+ * @param hsram: pointer to SRAM handle
+ * @param pAddress: Pointer to write start address
+ * @param pSrcBuffer: Pointer to source buffer to write
+ * @param BufferSize: Size of the buffer to write to memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_Write_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize)
+{
+ /* Check the SRAM controller state */
+ if(hsram->State == HAL_SRAM_STATE_PROTECTED)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_BUSY;
+
+ /* Write data to memory */
+ for(; BufferSize != 0; BufferSize--)
+ {
+ *(__IO uint32_t *)pAddress = *pSrcBuffer;
+ pSrcBuffer++;
+ pAddress++;
+ }
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Reads a Words data from the SRAM memory using DMA transfer.
+ * @param hsram: pointer to SRAM handle
+ * @param pAddress: Pointer to read start address
+ * @param pDstBuffer: Pointer to destination buffer
+ * @param BufferSize: Size of the buffer to read from memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_Read_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize)
+{
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_BUSY;
+
+ /* Configure DMA user callbacks */
+ hsram->hdma->XferCpltCallback = HAL_SRAM_DMA_XferCpltCallback;
+ hsram->hdma->XferErrorCallback = HAL_SRAM_DMA_XferErrorCallback;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hsram->hdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, (uint32_t)BufferSize);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Writes a Words data buffer to SRAM memory using DMA transfer.
+ * @param hsram: pointer to SRAM handle
+ * @param pAddress: Pointer to write start address
+ * @param pSrcBuffer: Pointer to source buffer to write
+ * @param BufferSize: Size of the buffer to write to memory
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_Write_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize)
+{
+ /* Check the SRAM controller state */
+ if(hsram->State == HAL_SRAM_STATE_PROTECTED)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_BUSY;
+
+ /* Configure DMA user callbacks */
+ hsram->hdma->XferCpltCallback = HAL_SRAM_DMA_XferCpltCallback;
+ hsram->hdma->XferErrorCallback = HAL_SRAM_DMA_XferErrorCallback;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(hsram->hdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, (uint32_t)BufferSize);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SRAM_Group3 Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### SRAM Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control dynamically
+ the SRAM interface.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables dynamically SRAM write operation.
+ * @param hsram: pointer to SRAM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_WriteOperation_Enable(SRAM_HandleTypeDef *hsram)
+{
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Enable write operation */
+ FMC_NORSRAM_WriteOperation_Enable(hsram->Instance, hsram->Init.NSBank);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_READY;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables dynamically SRAM write operation.
+ * @param hsram: pointer to SRAM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_SRAM_WriteOperation_Disable(SRAM_HandleTypeDef *hsram)
+{
+ /* Process Locked */
+ __HAL_LOCK(hsram);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_BUSY;
+
+ /* Disable write operation */
+ FMC_NORSRAM_WriteOperation_Disable(hsram->Instance, hsram->Init.NSBank);
+
+ /* Update the SRAM controller state */
+ hsram->State = HAL_SRAM_STATE_PROTECTED;
+
+ /* Process unlocked */
+ __HAL_UNLOCK(hsram);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup SRAM_Group4 State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ==============================================================================
+ ##### SRAM State functions #####
+ ==============================================================================
+ [..]
+ This subsection permits to get in run-time the status of the SRAM controller
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the SRAM controller state
+ * @param hsram: pointer to SRAM handle
+ * @retval SRAM controller state
+ */
+HAL_SRAM_StateTypeDef HAL_SRAM_GetState(SRAM_HandleTypeDef *hsram)
+{
+ return hsram->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+#endif /* HAL_SRAM_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim.c
new file mode 100644
index 0000000..4691f46
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim.c
@@ -0,0 +1,5036 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_tim.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief TIM HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Timer (TIM) peripheral:
+ * + Time Base Initialization
+ * + Time Base Start
+ * + Time Base Start Interruption
+ * + Time Base Start DMA
+ * + Time Output Compare/PWM Initialization
+ * + Time Output Compare/PWM Channel Configuration
+ * + Time Output Compare/PWM Start
+ * + Time Output Compare/PWM Start Interruption
+ * + Time Output Compare/PWM Start DMA
+ * + Time Input Capture Initialization
+ * + Time Input Capture Channel Configuration
+ * + Time Input Capture Start
+ * + Time Input Capture Start Interruption
+ * + Time Input Capture Start DMA
+ * + Time One Pulse Initialization
+ * + Time One Pulse Channel Configuration
+ * + Time One Pulse Start
+ * + Time Encoder Interface Initialization
+ * + Time Encoder Interface Start
+ * + Time Encoder Interface Start Interruption
+ * + Time Encoder Interface Start DMA
+ * + Commutation Event configuration with Interruption and DMA
+ * + Time OCRef clear configuration
+ * + Time External Clock configuration
+ @verbatim
+ ==============================================================================
+ ##### TIMER Generic features #####
+ ==============================================================================
+ [..] The Timer features include:
+ (#) 16-bit up, down, up/down auto-reload counter.
+ (#) 16-bit programmable prescaler allowing dividing (also on the fly) the
+ counter clock frequency either by any factor between 1 and 65536.
+ (#) Up to 4 independent channels for:
+ (++) Input Capture
+ (++) Output Compare
+ (++) PWM generation (Edge and Center-aligned Mode)
+ (++) One-pulse mode output
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#) Initialize the TIM low level resources by implementing the following functions
+ depending from feature used :
+ (++) Time Base : HAL_TIM_Base_MspInit()
+ (++) Input Capture : HAL_TIM_IC_MspInit()
+ (++) Output Compare : HAL_TIM_OC_MspInit()
+ (++) PWM generation : HAL_TIM_PWM_MspInit()
+ (++) One-pulse mode output : HAL_TIM_OnePulse_MspInit()
+ (++) Encoder mode output : HAL_TIM_Encoder_MspInit()
+
+ (#) Initialize the TIM low level resources :
+ (##) Enable the TIM interface clock using __TIMx_CLK_ENABLE();
+ (##) TIM pins configuration
+ (+++) Enable the clock for the TIM GPIOs using the following function:
+ __GPIOx_CLK_ENABLE();
+ (+++) Configure these TIM pins in Alternate function mode using HAL_GPIO_Init();
+
+ (#) The external Clock can be configured, if needed (the default clock is the
+ internal clock from the APBx), using the following function:
+ HAL_TIM_ConfigClockSource, the clock configuration should be done before
+ any start function.
+
+ (#) Configure the TIM in the desired functioning mode using one of the
+ initialization function of this driver:
+ (++) HAL_TIM_Base_Init: to use the Timer to generate a simple time base
+ (++) HAL_TIM_OC_Init and HAL_TIM_OC_ConfigChannel: to use the Timer to generate an
+ Output Compare signal.
+ (++) HAL_TIM_PWM_Init and HAL_TIM_PWM_ConfigChannel: to use the Timer to generate a
+ PWM signal.
+ (++) HAL_TIM_IC_Init and HAL_TIM_IC_ConfigChannel: to use the Timer to measure an
+ external signal.
+ (++) HAL_TIM_OnePulse_Init and HAL_TIM_OnePulse_ConfigChannel: to use the Timer
+ in One Pulse Mode.
+ (++) HAL_TIM_Encoder_Init: to use the Timer Encoder Interface.
+
+ (#) Activate the TIM peripheral using one of the start functions depending from the feature used:
+ (++) Time Base : HAL_TIM_Base_Start(), HAL_TIM_Base_Start_DMA(), HAL_TIM_Base_Start_IT()
+ (++) Input Capture : HAL_TIM_IC_Start(), HAL_TIM_IC_Start_DMA(), HAL_TIM_IC_Start_IT()
+ (++) Output Compare : HAL_TIM_OC_Start(), HAL_TIM_OC_Start_DMA(), HAL_TIM_OC_Start_IT()
+ (++) PWM generation : HAL_TIM_PWM_Start(), HAL_TIM_PWM_Start_DMA(), HAL_TIM_PWM_Start_IT()
+ (++) One-pulse mode output : HAL_TIM_OnePulse_Start(), HAL_TIM_OnePulse_Start_IT()
+ (++) Encoder mode output : HAL_TIM_Encoder_Start(), HAL_TIM_Encoder_Start_DMA(), HAL_TIM_Encoder_Start_IT().
+
+ (#) The DMA Burst is managed with the two following functions:
+ HAL_TIM_DMABurst_WriteStart()
+ HAL_TIM_DMABurst_ReadStart()
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup TIM
+ * @brief TIM HAL module driver
+ * @{
+ */
+
+#ifdef HAL_TIM_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
+static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
+static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
+
+static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter);
+static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
+ uint32_t TIM_ICFilter);
+static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter);
+static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
+ uint32_t TIM_ICFilter);
+static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
+ uint32_t TIM_ICFilter);
+
+static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler,
+ uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter);
+
+static void TIM_ITRx_SetConfig(TIM_TypeDef* TIMx, uint16_t TIM_ITRx);
+static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma);
+static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup TIM_Private_Functions
+ * @{
+ */
+
+/** @defgroup TIM_Group1 Time Base functions
+ * @brief Time Base functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Time Base functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the TIM base.
+ (+) De-initialize the TIM base.
+ (+) Start the Time Base.
+ (+) Stop the Time Base.
+ (+) Start the Time Base and enable interrupt.
+ (+) Stop the Time Base and disable interrupt.
+ (+) Start the Time Base and enable DMA transfer.
+ (+) Stop the Time Base and disable DMA transfer.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Initializes the TIM Time base Unit according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @param htim: TIM Base handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim)
+{
+ /* Check the TIM handle allocation */
+ if(htim == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode));
+ assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
+
+ if(htim->State == HAL_TIM_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC */
+ HAL_TIM_Base_MspInit(htim);
+ }
+
+ /* Set the TIM state */
+ htim->State= HAL_TIM_STATE_BUSY;
+
+ /* Set the Time Base configuration */
+ TIM_Base_SetConfig(htim->Instance, &htim->Init);
+
+ /* Initialize the TIM state*/
+ htim->State= HAL_TIM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the TIM Base peripheral
+ * @param htim: TIM Base handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Disable the TIM Peripheral Clock */
+ __HAL_TIM_DISABLE(htim);
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC */
+ HAL_TIM_Base_MspDeInit(htim);
+
+ /* Change TIM state */
+ htim->State = HAL_TIM_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM Base MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_Base_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes TIM Base MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_Base_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Starts the TIM Base generation.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ /* Set the TIM state */
+ htim->State= HAL_TIM_STATE_BUSY;
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Change the TIM state*/
+ htim->State= HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Base generation.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ /* Set the TIM state */
+ htim->State= HAL_TIM_STATE_BUSY;
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the TIM state*/
+ htim->State= HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Base generation in interrupt mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ /* Enable the TIM Update interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Base generation in interrupt mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+ /* Disable the TIM Update interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_UPDATE);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Base generation in DMA mode.
+ * @param htim : TIM handle
+ * @param pData: The source Buffer address.
+ * @param Length: The length of data to be transferred from memory to peripheral.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_DMA_INSTANCE(htim->Instance));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if((pData == 0 ) && (Length > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)pData, (uint32_t)&htim->Instance->ARR, Length);
+
+ /* Enable the TIM Update DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_UPDATE);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Base generation in DMA mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_DMA_INSTANCE(htim->Instance));
+
+ /* Disable the TIM Update DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_UPDATE);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the htim state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIM_Group2 Time Output Compare functions
+ * @brief Time Output Compare functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Time Output Compare functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the TIM Output Compare.
+ (+) De-initialize the TIM Output Compare.
+ (+) Start the Time Output Compare.
+ (+) Stop the Time Output Compare.
+ (+) Start the Time Output Compare and enable interrupt.
+ (+) Stop the Time Output Compare and disable interrupt.
+ (+) Start the Time Output Compare and enable DMA transfer.
+ (+) Stop the Time Output Compare and disable DMA transfer.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Initializes the TIM Output Compare according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @param htim: TIM Output Compare handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef* htim)
+{
+ /* Check the TIM handle allocation */
+ if(htim == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode));
+ assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
+
+ if(htim->State == HAL_TIM_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
+ HAL_TIM_OC_MspInit(htim);
+ }
+
+ /* Set the TIM state */
+ htim->State= HAL_TIM_STATE_BUSY;
+
+ /* Init the base time for the Output Compare */
+ TIM_Base_SetConfig(htim->Instance, &htim->Init);
+
+ /* Initialize the TIM state*/
+ htim->State= HAL_TIM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the TIM peripheral
+ * @param htim: TIM Output Compare handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Disable the TIM Peripheral Clock */
+ __HAL_TIM_DISABLE(htim);
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */
+ HAL_TIM_OC_MspDeInit(htim);
+
+ /* Change TIM state */
+ htim->State = HAL_TIM_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM Output Compare MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_OC_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes TIM Output Compare MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_OC_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Starts the TIM Output Compare signal generation.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ /* Enable the Output compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Enable the main output */
+ __HAL_TIM_MOE_ENABLE(htim);
+ }
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Output Compare signal generation.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ /* Disable the Output compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Output Compare signal generation in interrupt mode.
+ * @param htim : TIM OC handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Enable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Enable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Enable the Output compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Enable the main output */
+ __HAL_TIM_MOE_ENABLE(htim);
+ }
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Output Compare signal generation in interrupt mode.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the Output compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Output Compare signal generation in DMA mode.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @param pData: The source Buffer address.
+ * @param Length: The length of data to be transferred from memory to TIM peripheral
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if(((uint32_t)pData == 0 ) && (Length > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
+
+ /* Enable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
+
+ /* Enable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length);
+
+ /* Enable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length);
+
+ /* Enable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Enable the Output compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Enable the main output */
+ __HAL_TIM_MOE_ENABLE(htim);
+ }
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Output Compare signal generation in DMA mode.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the Output compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the htim state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIM_Group3 Time PWM functions
+ * @brief Time PWM functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Time PWM functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the TIM OPWM.
+ (+) De-initialize the TIM PWM.
+ (+) Start the Time PWM.
+ (+) Stop the Time PWM.
+ (+) Start the Time PWM and enable interrupt.
+ (+) Stop the Time PWM and disable interrupt.
+ (+) Start the Time PWM and enable DMA transfer.
+ (+) Stop the Time PWM and disable DMA transfer.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Initializes the TIM PWM Time Base according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @param htim: TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim)
+{
+ /* Check the TIM handle allocation */
+ if(htim == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode));
+ assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
+
+ if(htim->State == HAL_TIM_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
+ HAL_TIM_PWM_MspInit(htim);
+ }
+
+ /* Set the TIM state */
+ htim->State= HAL_TIM_STATE_BUSY;
+
+ /* Init the base time for the PWM */
+ TIM_Base_SetConfig(htim->Instance, &htim->Init);
+
+ /* Initialize the TIM state*/
+ htim->State= HAL_TIM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the TIM peripheral
+ * @param htim: TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Disable the TIM Peripheral Clock */
+ __HAL_TIM_DISABLE(htim);
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */
+ HAL_TIM_PWM_MspDeInit(htim);
+
+ /* Change TIM state */
+ htim->State = HAL_TIM_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM PWM MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_PWM_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes TIM PWM MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_PWM_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Starts the PWM signal generation.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ /* Enable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Enable the main output */
+ __HAL_TIM_MOE_ENABLE(htim);
+ }
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the PWM signal generation.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ /* Disable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the htim state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the PWM signal generation in interrupt mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Enable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Enable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Enable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Enable the main output */
+ __HAL_TIM_MOE_ENABLE(htim);
+ }
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the PWM signal generation in interrupt mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT (TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM PWM signal generation in DMA mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @param pData: The source Buffer address.
+ * @param Length: The length of data to be transferred from memory to TIM peripheral
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if(((uint32_t)pData == 0 ) && (Length > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
+
+ /* Enable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
+
+ /* Enable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length);
+
+ /* Enable the TIM Output Capture/Compare 3 request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length);
+
+ /* Enable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Enable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Enable the main output */
+ __HAL_TIM_MOE_ENABLE(htim);
+ }
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM PWM signal generation in DMA mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the htim state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIM_Group4 Time Input Capture functions
+ * @brief Time Input Capture functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Time Input Capture functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the TIM Input Capture.
+ (+) De-initialize the TIM Input Capture.
+ (+) Start the Time Input Capture.
+ (+) Stop the Time Input Capture.
+ (+) Start the Time Input Capture and enable interrupt.
+ (+) Stop the Time Input Capture and disable interrupt.
+ (+) Start the Time Input Capture and enable DMA transfer.
+ (+) Stop the Time Input Capture and disable DMA transfer.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Initializes the TIM Input Capture Time base according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @param htim: TIM Input Capture handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim)
+{
+ /* Check the TIM handle allocation */
+ if(htim == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode));
+ assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
+
+ if(htim->State == HAL_TIM_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
+ HAL_TIM_IC_MspInit(htim);
+ }
+
+ /* Set the TIM state */
+ htim->State= HAL_TIM_STATE_BUSY;
+
+ /* Init the base time for the input capture */
+ TIM_Base_SetConfig(htim->Instance, &htim->Init);
+
+ /* Initialize the TIM state*/
+ htim->State= HAL_TIM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the TIM peripheral
+ * @param htim: TIM Input Capture handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Disable the TIM Peripheral Clock */
+ __HAL_TIM_DISABLE(htim);
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */
+ HAL_TIM_IC_MspDeInit(htim);
+
+ /* Change TIM state */
+ htim->State = HAL_TIM_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM INput Capture MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_IC_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes TIM Input Capture MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_IC_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Starts the TIM Input Capture measurement.
+ * @param hdma : TIM Input Capture handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Start (TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ /* Enable the Input Capture channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Input Capture measurement.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ /* Disable the Input Capture channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Input Capture measurement in interrupt mode.
+ * @param hdma : TIM Input Capture handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Start_IT (TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Enable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Enable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+ /* Enable the Input Capture channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Input Capture measurement in interrupt mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the Input Capture channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Input Capture measurement on in DMA mode.
+ * @param htim : TIM Input Capture handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @param pData: The destination Buffer address.
+ * @param Length: The length of data to be transferred from TIM peripheral to memory.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+ assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if((pData == 0 ) && (Length > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length);
+
+ /* Enable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData, Length);
+
+ /* Enable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->CCR3, (uint32_t)pData, Length);
+
+ /* Enable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->CCR4, (uint32_t)pData, Length);
+
+ /* Enable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Enable the Input Capture channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Input Capture measurement on in DMA mode.
+ * @param htim : TIM Input Capture handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
+ assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the Input Capture channel */
+ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the htim state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+/**
+ * @}
+ */
+
+/** @defgroup TIM_Group5 Time One Pulse functions
+ * @brief Time One Pulse functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Time One Pulse functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the TIM One Pulse.
+ (+) De-initialize the TIM One Pulse.
+ (+) Start the Time One Pulse.
+ (+) Stop the Time One Pulse.
+ (+) Start the Time One Pulse and enable interrupt.
+ (+) Stop the Time One Pulse and disable interrupt.
+ (+) Start the Time One Pulse and enable DMA transfer.
+ (+) Stop the Time One Pulse and disable DMA transfer.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Initializes the TIM One Pulse Time Base according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @param htim: TIM OnePulse handle
+ * @param OnePulseMode: Select the One pulse mode.
+ * This parameter can be one of the following values:
+ * @arg TIM_OPMODE_SINGLE: Only one pulse will be generated.
+ * @arg TIM_OPMODE_REPETITIVE: Repetitive pulses wil be generated.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode)
+{
+ /* Check the TIM handle allocation */
+ if(htim == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode));
+ assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
+ assert_param(IS_TIM_OPM_MODE(OnePulseMode));
+
+ if(htim->State == HAL_TIM_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
+ HAL_TIM_OnePulse_MspInit(htim);
+ }
+
+ /* Set the TIM state */
+ htim->State= HAL_TIM_STATE_BUSY;
+
+ /* Configure the Time base in the One Pulse Mode */
+ TIM_Base_SetConfig(htim->Instance, &htim->Init);
+
+ /* Reset the OPM Bit */
+ htim->Instance->CR1 &= ~TIM_CR1_OPM;
+
+ /* Configure the OPM Mode */
+ htim->Instance->CR1 |= OnePulseMode;
+
+ /* Initialize the TIM state*/
+ htim->State= HAL_TIM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the TIM One Pulse
+ * @param htim: TIM One Pulse handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Disable the TIM Peripheral Clock */
+ __HAL_TIM_DISABLE(htim);
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC */
+ HAL_TIM_OnePulse_MspDeInit(htim);
+
+ /* Change TIM state */
+ htim->State = HAL_TIM_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM One Pulse MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_OnePulse_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes TIM One Pulse MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_OnePulse_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Starts the TIM One Pulse signal generation.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
+{
+ /* Enable the Capture compare and the Input Capture channels
+ (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
+ if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
+ if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
+ in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together
+
+ No need to enable the counter, it's enabled automatically by hardware
+ (the counter starts in response to a stimulus and generate a pulse */
+
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Enable the main output */
+ __HAL_TIM_MOE_ENABLE(htim);
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM One Pulse signal generation.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channels to be disable
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
+{
+ /* Disable the Capture compare and the Input Capture channels
+ (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
+ if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
+ if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
+ in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */
+
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM One Pulse signal generation in interrupt mode.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
+{
+ /* Enable the Capture compare and the Input Capture channels
+ (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
+ if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
+ if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
+ in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together
+
+ No need to enable the counter, it's enabled automatically by hardware
+ (the counter starts in response to a stimulus and generate a pulse */
+
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Enable the main output */
+ __HAL_TIM_MOE_ENABLE(htim);
+ }
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM One Pulse signal generation in interrupt mode.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
+{
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+
+ /* Disable the Capture compare and the Input Capture channels
+ (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
+ if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
+ if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
+ in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
+
+ if(IS_TIM_ADVANCED_INSTANCE(htim->Instance) != RESET)
+ {
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIM_Group6 Time Encoder functions
+ * @brief Time Encoder functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Time Encoder functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the TIM Encoder.
+ (+) De-initialize the TIM Encoder.
+ (+) Start the Time Encoder.
+ (+) Stop the Time Encoder.
+ (+) Start the Time Encoder and enable interrupt.
+ (+) Stop the Time Encoder and disable interrupt.
+ (+) Start the Time Encoder and enable DMA transfer.
+ (+) Stop the Time Encoder and disable DMA transfer.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Initializes the TIM Encoder Interface and create the associated handle.
+ * @param htim: TIM Encoder Interface handle
+ * @param sConfig: TIM Encoder Interface configuration structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig)
+{
+ uint32_t tmpsmcr = 0;
+ uint32_t tmpccmr1 = 0;
+ uint32_t tmpccer = 0;
+
+ /* Check the TIM handle allocation */
+ if(htim == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_ENCODER_MODE(sConfig->EncoderMode));
+ assert_param(IS_TIM_IC_SELECTION(sConfig->IC1Selection));
+ assert_param(IS_TIM_IC_SELECTION(sConfig->IC2Selection));
+ assert_param(IS_TIM_IC_POLARITY(sConfig->IC1Polarity));
+ assert_param(IS_TIM_IC_POLARITY(sConfig->IC2Polarity));
+ assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler));
+ assert_param(IS_TIM_IC_PRESCALER(sConfig->IC2Prescaler));
+ assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter));
+ assert_param(IS_TIM_IC_FILTER(sConfig->IC2Filter));
+
+ if(htim->State == HAL_TIM_STATE_RESET)
+ {
+ /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
+ HAL_TIM_Encoder_MspInit(htim);
+ }
+
+ /* Set the TIM state */
+ htim->State= HAL_TIM_STATE_BUSY;
+
+ /* Reset the SMS bits */
+ htim->Instance->SMCR &= ~TIM_SMCR_SMS;
+
+ /* Configure the Time base in the Encoder Mode */
+ TIM_Base_SetConfig(htim->Instance, &htim->Init);
+
+ /* Get the TIMx SMCR register value */
+ tmpsmcr = htim->Instance->SMCR;
+
+ /* Get the TIMx CCMR1 register value */
+ tmpccmr1 = htim->Instance->CCMR1;
+
+ /* Get the TIMx CCER register value */
+ tmpccer = htim->Instance->CCER;
+
+ /* Set the encoder Mode */
+ tmpsmcr |= sConfig->EncoderMode;
+
+ /* Select the Capture Compare 1 and the Capture Compare 2 as input */
+ tmpccmr1 &= ~(TIM_CCMR1_CC1S | TIM_CCMR1_CC2S);
+ tmpccmr1 |= (sConfig->IC1Selection | (sConfig->IC2Selection << 8));
+
+ /* Set the the Capture Compare 1 and the Capture Compare 2 prescalers and filters */
+ tmpccmr1 &= ~(TIM_CCMR1_IC1PSC | TIM_CCMR1_IC2PSC);
+ tmpccmr1 &= ~(TIM_CCMR1_IC1F | TIM_CCMR1_IC2F);
+ tmpccmr1 |= sConfig->IC1Prescaler | (sConfig->IC2Prescaler << 8);
+ tmpccmr1 |= (sConfig->IC1Filter << 4) | (sConfig->IC2Filter << 12);
+
+ /* Set the TI1 and the TI2 Polarities */
+ tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC2P);
+ tmpccer &= ~(TIM_CCER_CC1NP | TIM_CCER_CC2NP);
+ tmpccer |= sConfig->IC1Polarity | (sConfig->IC2Polarity << 4);
+
+ /* Write to TIMx SMCR */
+ htim->Instance->SMCR = tmpsmcr;
+
+ /* Write to TIMx CCMR1 */
+ htim->Instance->CCMR1 = tmpccmr1;
+
+ /* Write to TIMx CCER */
+ htim->Instance->CCER = tmpccer;
+
+ /* Initialize the TIM state*/
+ htim->State= HAL_TIM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the TIM Encoder interface
+ * @param htim: TIM Encoder handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Disable the TIM Peripheral Clock */
+ __HAL_TIM_DISABLE(htim);
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC */
+ HAL_TIM_Encoder_MspDeInit(htim);
+
+ /* Change TIM state */
+ htim->State = HAL_TIM_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM Encoder Interface MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_Encoder_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes TIM Encoder Interface MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_Encoder_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Starts the TIM Encoder Interface.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+
+ /* Enable the encoder interface channels */
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ break;
+ }
+ case TIM_CHANNEL_2:
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+ break;
+ }
+ default :
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+ break;
+ }
+ }
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Encoder Interface.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+
+ /* Disable the Input Capture channels 1 and 2
+ (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+ break;
+ }
+ case TIM_CHANNEL_2:
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
+ break;
+ }
+ default :
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
+ break;
+ }
+ }
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Encoder Interface in interrupt mode.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+
+ /* Enable the encoder interface channels */
+ /* Enable the capture compare Interrupts 1 and/or 2 */
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ break;
+ }
+ case TIM_CHANNEL_2:
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ break;
+ }
+ default :
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ break;
+ }
+ }
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Encoder Interface in interrupt mode.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+
+ /* Disable the Input Capture channels 1 and 2
+ (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
+ if(Channel == TIM_CHANNEL_1)
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+
+ /* Disable the capture compare Interrupts 1 */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ }
+ else if(Channel == TIM_CHANNEL_2)
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
+
+ /* Disable the capture compare Interrupts 2 */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ }
+ else
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
+
+ /* Disable the capture compare Interrupts 1 and 2 */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the htim state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Encoder Interface in DMA mode.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @param pData1: The destination Buffer address for IC1.
+ * @param pData2: The destination Buffer address for IC2.
+ * @param Length: The length of data to be transferred from TIM peripheral to memory.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if((((pData1 == 0) || (pData2 == 0) )) && (Length > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t )pData1, Length);
+
+ /* Enable the TIM Input Capture DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Enable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError;
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length);
+
+ /* Enable the TIM Input Capture DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Enable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+ }
+ break;
+
+ case TIM_CHANNEL_ALL:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length);
+
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Enable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+
+ /* Enable the TIM Input Capture DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ /* Enable the TIM Input Capture DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ default:
+ break;
+ }
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Encoder Interface in DMA mode.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
+
+ /* Disable the Input Capture channels 1 and 2
+ (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
+ if(Channel == TIM_CHANNEL_1)
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+
+ /* Disable the capture compare DMA Request 1 */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ else if(Channel == TIM_CHANNEL_2)
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
+
+ /* Disable the capture compare DMA Request 2 */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ else
+ {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
+
+ /* Disable the capture compare DMA Request 1 and 2 */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ }
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the htim state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+/** @defgroup TIM_Group7 TIM IRQ handler management
+ * @brief IRQ handler management
+ *
+@verbatim
+ ==============================================================================
+ ##### IRQ handler management #####
+ ==============================================================================
+ [..]
+ This section provides Timer IRQ handler function.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief This function handles TIM interrupts requests.
+ * @param htim: TIM handle
+ * @retval None
+ */
+void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
+{
+ /* Capture compare 1 event */
+ if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET)
+ {
+ if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC1) !=RESET)
+ {
+ {
+ __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1);
+ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
+
+ /* Input capture event */
+ if((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00)
+ {
+ HAL_TIM_IC_CaptureCallback(htim);
+ }
+ /* Output compare event */
+ else
+ {
+ HAL_TIM_OC_DelayElapsedCallback(htim);
+ HAL_TIM_PWM_PulseFinishedCallback(htim);
+ }
+ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
+ }
+ }
+ }
+ /* Capture compare 2 event */
+ if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET)
+ {
+ if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC2) !=RESET)
+ {
+ __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2);
+ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
+ /* Input capture event */
+ if((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00)
+ {
+ HAL_TIM_IC_CaptureCallback(htim);
+ }
+ /* Output compare event */
+ else
+ {
+ HAL_TIM_OC_DelayElapsedCallback(htim);
+ HAL_TIM_PWM_PulseFinishedCallback(htim);
+ }
+ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
+ }
+ }
+ /* Capture compare 3 event */
+ if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET)
+ {
+ if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC3) !=RESET)
+ {
+ __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3);
+ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
+ /* Input capture event */
+ if((htim->Instance->CCMR1 & TIM_CCMR2_CC3S) != 0x00)
+ {
+ HAL_TIM_IC_CaptureCallback(htim);
+ }
+ /* Output compare event */
+ else
+ {
+ HAL_TIM_OC_DelayElapsedCallback(htim);
+ HAL_TIM_PWM_PulseFinishedCallback(htim);
+ }
+ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
+ }
+ }
+ /* Capture compare 4 event */
+ if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET)
+ {
+ if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC4) !=RESET)
+ {
+ __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4);
+ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
+ /* Input capture event */
+ if((htim->Instance->CCMR1 & TIM_CCMR2_CC4S) != 0x00)
+ {
+ HAL_TIM_IC_CaptureCallback(htim);
+ }
+ /* Output compare event */
+ else
+ {
+ HAL_TIM_OC_DelayElapsedCallback(htim);
+ HAL_TIM_PWM_PulseFinishedCallback(htim);
+ }
+ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
+ }
+ }
+ /* TIM Update event */
+ if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET)
+ {
+ if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_UPDATE) !=RESET)
+ {
+ __HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE);
+ HAL_TIM_PeriodElapsedCallback(htim);
+ }
+ }
+ /* TIM Break input event */
+ if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET)
+ {
+ if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_BREAK) !=RESET)
+ {
+ __HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK);
+ HAL_TIMEx_BreakCallback(htim);
+ }
+ }
+ /* TIM Trigger detection event */
+ if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET)
+ {
+ if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_TRIGGER) !=RESET)
+ {
+ __HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER);
+ HAL_TIM_TriggerCallback(htim);
+ }
+ }
+ /* TIM commutation event */
+ if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET)
+ {
+ if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_COM) !=RESET)
+ {
+ __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM);
+ HAL_TIMEx_CommutationCallback(htim);
+ }
+ }
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIM_Group8 Peripheral Control functions
+ * @brief Peripheral Control functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral Control functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Configure The Input Output channels for OC, PWM, IC or One Pulse mode.
+ (+) Configure External Clock source.
+ (+) Configure Complementary channels, break features and dead time.
+ (+) Configure Master and the Slave synchronization.
+ (+) Configure the DMA Burst Mode.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the TIM Output Compare Channels according to the specified
+ * parameters in the TIM_OC_InitTypeDef.
+ * @param htim: TIM Output Compare handle
+ * @param sConfig: TIM Output Compare configuration structure
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CHANNELS(Channel));
+ assert_param(IS_TIM_OC_MODE(sConfig->OCMode));
+ assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity));
+ assert_param(IS_TIM_OCN_POLARITY(sConfig->OCNPolarity));
+ assert_param(IS_TIM_FAST_STATE(sConfig->OCFastMode));
+ assert_param(IS_TIM_OCNIDLE_STATE(sConfig->OCNIdleState));
+ assert_param(IS_TIM_OCIDLE_STATE(sConfig->OCIdleState));
+
+ /* Check input state */
+ __HAL_LOCK(htim);
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ /* Configure the TIM Channel 1 in Output Compare */
+ TIM_OC1_SetConfig(htim->Instance, sConfig);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ /* Configure the TIM Channel 2 in Output Compare */
+ TIM_OC2_SetConfig(htim->Instance, sConfig);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
+ /* Configure the TIM Channel 3 in Output Compare */
+ TIM_OC3_SetConfig(htim->Instance, sConfig);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+ /* Configure the TIM Channel 4 in Output Compare */
+ TIM_OC4_SetConfig(htim->Instance, sConfig);
+ }
+ break;
+
+ default:
+ break;
+ }
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM Input Capture Channels according to the specified
+ * parameters in the TIM_IC_InitTypeDef.
+ * @param htim: TIM IC handle
+ * @param sConfig: TIM Input Capture configuration structure
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_IC_POLARITY(sConfig->ICPolarity));
+ assert_param(IS_TIM_IC_SELECTION(sConfig->ICSelection));
+ assert_param(IS_TIM_IC_PRESCALER(sConfig->ICPrescaler));
+ assert_param(IS_TIM_IC_FILTER(sConfig->ICFilter));
+
+ __HAL_LOCK(htim);
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ if (Channel == TIM_CHANNEL_1)
+ {
+ /* TI1 Configuration */
+ TIM_TI1_SetConfig(htim->Instance,
+ sConfig->ICPolarity,
+ sConfig->ICSelection,
+ sConfig->ICFilter);
+
+ /* Reset the IC1PSC Bits */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC;
+
+ /* Set the IC1PSC value */
+ htim->Instance->CCMR1 |= sConfig->ICPrescaler;
+ }
+ else if (Channel == TIM_CHANNEL_2)
+ {
+ /* TI2 Configuration */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+
+ TIM_TI2_SetConfig(htim->Instance,
+ sConfig->ICPolarity,
+ sConfig->ICSelection,
+ sConfig->ICFilter);
+
+ /* Reset the IC2PSC Bits */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC;
+
+ /* Set the IC2PSC value */
+ htim->Instance->CCMR1 |= (sConfig->ICPrescaler << 8);
+ }
+ else if (Channel == TIM_CHANNEL_3)
+ {
+ /* TI3 Configuration */
+ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
+
+ TIM_TI3_SetConfig(htim->Instance,
+ sConfig->ICPolarity,
+ sConfig->ICSelection,
+ sConfig->ICFilter);
+
+ /* Reset the IC3PSC Bits */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_IC3PSC;
+
+ /* Set the IC3PSC value */
+ htim->Instance->CCMR2 |= sConfig->ICPrescaler;
+ }
+ else
+ {
+ /* TI4 Configuration */
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+
+ TIM_TI4_SetConfig(htim->Instance,
+ sConfig->ICPolarity,
+ sConfig->ICSelection,
+ sConfig->ICFilter);
+
+ /* Reset the IC4PSC Bits */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_IC4PSC;
+
+ /* Set the IC4PSC value */
+ htim->Instance->CCMR2 |= (sConfig->ICPrescaler << 8);
+ }
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM PWM channels according to the specified
+ * parameters in the TIM_OC_InitTypeDef.
+ * @param htim: TIM handle
+ * @param sConfig: TIM PWM configuration structure
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel)
+{
+ __HAL_LOCK(htim);
+
+ /* Check the parameters */
+ assert_param(IS_TIM_CHANNELS(Channel));
+ assert_param(IS_TIM_PWM_MODE(sConfig->OCMode));
+ assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity));
+ assert_param(IS_TIM_OCN_POLARITY(sConfig->OCNPolarity));
+ assert_param(IS_TIM_OCNIDLE_STATE(sConfig->OCNIdleState));
+ assert_param(IS_TIM_OCIDLE_STATE(sConfig->OCIdleState));
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ /* Configure the Channel 1 in PWM mode */
+ TIM_OC1_SetConfig(htim->Instance, sConfig);
+
+ /* Set the Preload enable bit for channel1 */
+ htim->Instance->CCMR1 |= TIM_CCMR1_OC1PE;
+
+ /* Configure the Output Fast mode */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC1FE;
+ htim->Instance->CCMR1 |= sConfig->OCFastMode;
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ /* Configure the Channel 2 in PWM mode */
+ TIM_OC2_SetConfig(htim->Instance, sConfig);
+
+ /* Set the Preload enable bit for channel2 */
+ htim->Instance->CCMR1 |= TIM_CCMR1_OC2PE;
+
+ /* Configure the Output Fast mode */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC2FE;
+ htim->Instance->CCMR1 |= sConfig->OCFastMode << 8;
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
+ /* Configure the Channel 3 in PWM mode */
+ TIM_OC3_SetConfig(htim->Instance, sConfig);
+
+ /* Set the Preload enable bit for channel3 */
+ htim->Instance->CCMR2 |= TIM_CCMR2_OC3PE;
+
+ /* Configure the Output Fast mode */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC3FE;
+ htim->Instance->CCMR2 |= sConfig->OCFastMode;
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+ /* Configure the Channel 4 in PWM mode */
+ TIM_OC4_SetConfig(htim->Instance, sConfig);
+
+ /* Set the Preload enable bit for channel4 */
+ htim->Instance->CCMR2 |= TIM_CCMR2_OC4PE;
+
+ /* Configure the Output Fast mode */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC4FE;
+ htim->Instance->CCMR2 |= sConfig->OCFastMode << 8;
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM One Pulse Channels according to the specified
+ * parameters in the TIM_OnePulse_InitTypeDef.
+ * @param htim: TIM One Pulse handle
+ * @param sConfig: TIM One Pulse configuration structure
+ * @param OutputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @param InputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel)
+{
+ TIM_OC_InitTypeDef temp1;
+
+ /* Check the parameters */
+ assert_param(IS_TIM_OPM_CHANNELS(OutputChannel));
+ assert_param(IS_TIM_OPM_CHANNELS(InputChannel));
+
+ if(OutputChannel != InputChannel)
+ {
+ __HAL_LOCK(htim);
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Extract the Ouput compare configuration from sConfig structure */
+ temp1.OCMode = sConfig->OCMode;
+ temp1.Pulse = sConfig->Pulse;
+ temp1.OCPolarity = sConfig->OCPolarity;
+ temp1.OCNPolarity = sConfig->OCNPolarity;
+ temp1.OCIdleState = sConfig->OCIdleState;
+ temp1.OCNIdleState = sConfig->OCNIdleState;
+
+ switch (OutputChannel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+
+ TIM_OC1_SetConfig(htim->Instance, &temp1);
+ }
+ break;
+ case TIM_CHANNEL_2:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+
+ TIM_OC2_SetConfig(htim->Instance, &temp1);
+ }
+ break;
+ default:
+ break;
+ }
+ switch (InputChannel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+
+ TIM_TI1_SetConfig(htim->Instance, sConfig->ICPolarity,
+ sConfig->ICSelection, sConfig->ICFilter);
+
+ /* Reset the IC1PSC Bits */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC;
+
+ /* Select the Trigger source */
+ htim->Instance->SMCR &= ~TIM_SMCR_TS;
+ htim->Instance->SMCR |= TIM_TS_TI1FP1;
+
+ /* Select the Slave Mode */
+ htim->Instance->SMCR &= ~TIM_SMCR_SMS;
+ htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER;
+ }
+ break;
+ case TIM_CHANNEL_2:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+
+ TIM_TI2_SetConfig(htim->Instance, sConfig->ICPolarity,
+ sConfig->ICSelection, sConfig->ICFilter);
+
+ /* Reset the IC2PSC Bits */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC;
+
+ /* Select the Trigger source */
+ htim->Instance->SMCR &= ~TIM_SMCR_TS;
+ htim->Instance->SMCR |= TIM_TS_TI2FP2;
+
+ /* Select the Slave Mode */
+ htim->Instance->SMCR &= ~TIM_SMCR_SMS;
+ htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER;
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_ERROR;
+ }
+}
+
+/**
+ * @brief Configure the DMA Burst to transfer Data from the memory to the TIM peripheral
+ * @param htim: TIM handle
+ * @param BurstBaseAddress: TIM Base address from when the DMA will starts the Data write
+ * This parameters can be on of the following values:
+ * @arg TIM_DMABase_CR1
+ * @arg TIM_DMABase_CR2
+ * @arg TIM_DMABase_SMCR
+ * @arg TIM_DMABase_DIER
+ * @arg TIM_DMABase_SR
+ * @arg TIM_DMABase_EGR
+ * @arg TIM_DMABase_CCMR1
+ * @arg TIM_DMABase_CCMR2
+ * @arg TIM_DMABase_CCER
+ * @arg TIM_DMABase_CNT
+ * @arg TIM_DMABase_PSC
+ * @arg TIM_DMABase_ARR
+ * @arg TIM_DMABase_RCR
+ * @arg TIM_DMABase_CCR1
+ * @arg TIM_DMABase_CCR2
+ * @arg TIM_DMABase_CCR3
+ * @arg TIM_DMABase_CCR4
+ * @arg TIM_DMABase_BDTR
+ * @arg TIM_DMABase_DCR
+ * @param BurstRequestSrc: TIM DMA Request sources
+ * This parameters can be on of the following values:
+ * @arg TIM_DMA_UPDATE: TIM update Interrupt source
+ * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source
+ * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source
+ * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source
+ * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source
+ * @arg TIM_DMA_COM: TIM Commutation DMA source
+ * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source
+ * @param BurstBuffer: The Buffer address.
+ * @param BurstLength: DMA Burst length. This parameter can be one value
+ * between: TIM_DMABurstLength_1Transfer and TIM_DMABurstLength_18Transfers.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc,
+ uint32_t* BurstBuffer, uint32_t BurstLength)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_DMA_BASE(BurstBaseAddress));
+ assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
+ assert_param(IS_TIM_DMA_LENGTH(BurstLength));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if((BurstBuffer == 0 ) && (BurstLength > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+ switch(BurstRequestSrc)
+ {
+ case TIM_DMA_UPDATE:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_CC1:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_CC2:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_CC3:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_CC4:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_COM:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = HAL_TIMEx_DMACommutationCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_TRIGGER:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ default:
+ break;
+ }
+ /* configure the DMA Burst Mode */
+ htim->Instance->DCR = BurstBaseAddress | BurstLength;
+
+ /* Enable the TIM DMA Request */
+ __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc);
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM DMA Burst mode
+ * @param htim: TIM handle
+ * @param BurstRequestSrc: TIM DMA Request sources to disable
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
+
+ /* Disable the TIM Update DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Configure the DMA Burst to transfer Data from the TIM peripheral to the memory
+ * @param htim: TIM handle
+ * @param BurstBaseAddress: TIM Base address from when the DMA will starts the Data read
+ * This parameters can be on of the following values:
+ * @arg TIM_DMABase_CR1
+ * @arg TIM_DMABase_CR2
+ * @arg TIM_DMABase_SMCR
+ * @arg TIM_DMABase_DIER
+ * @arg TIM_DMABase_SR
+ * @arg TIM_DMABase_EGR
+ * @arg TIM_DMABase_CCMR1
+ * @arg TIM_DMABase_CCMR2
+ * @arg TIM_DMABase_CCER
+ * @arg TIM_DMABase_CNT
+ * @arg TIM_DMABase_PSC
+ * @arg TIM_DMABase_ARR
+ * @arg TIM_DMABase_RCR
+ * @arg TIM_DMABase_CCR1
+ * @arg TIM_DMABase_CCR2
+ * @arg TIM_DMABase_CCR3
+ * @arg TIM_DMABase_CCR4
+ * @arg TIM_DMABase_BDTR
+ * @arg TIM_DMABase_DCR
+ * @param BurstRequestSrc: TIM DMA Request sources
+ * This parameters can be on of the following values:
+ * @arg TIM_DMA_UPDATE: TIM update Interrupt source
+ * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source
+ * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source
+ * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source
+ * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source
+ * @arg TIM_DMA_COM: TIM Commutation DMA source
+ * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source
+ * @param BurstBuffer: The Buffer address.
+ * @param BurstLength: DMA Burst length. This parameter can be one value
+ * between: TIM_DMABurstLength_1Transfer and TIM_DMABurstLength_18Transfers.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc,
+ uint32_t *BurstBuffer, uint32_t BurstLength)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_DMA_BASE(BurstBaseAddress));
+ assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
+ assert_param(IS_TIM_DMA_LENGTH(BurstLength));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if((BurstBuffer == 0 ) && (BurstLength > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+ switch(BurstRequestSrc)
+ {
+ case TIM_DMA_UPDATE:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_CC1:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_CC2:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_CC3:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_CC4:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_COM:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = HAL_TIMEx_DMACommutationCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ case TIM_DMA_TRIGGER:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1);
+ }
+ break;
+ default:
+ break;
+ }
+
+ /* configure the DMA Burst Mode */
+ htim->Instance->DCR = BurstBaseAddress | BurstLength;
+
+ /* Enable the TIM DMA Request */
+ __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc);
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stop the DMA burst reading
+ * @param htim: TIM handle
+ * @param BurstRequestSrc: TIM DMA Request sources to disable.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
+
+ /* Disable the TIM Update DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Generate a software event
+ * @param htim: TIM handle
+ * @param EventSource: specifies the event source.
+ * This parameter can be one of the following values:
+ * @arg TIM_EventSource_Update: Timer update Event source
+ * @arg TIM_EventSource_CC1: Timer Capture Compare 1 Event source
+ * @arg TIM_EventSource_CC2: Timer Capture Compare 2 Event source
+ * @arg TIM_EventSource_CC3: Timer Capture Compare 3 Event source
+ * @arg TIM_EventSource_CC4: Timer Capture Compare 4 Event source
+ * @arg TIM_EventSource_COM: Timer COM event source
+ * @arg TIM_EventSource_Trigger: Timer Trigger Event source
+ * @arg TIM_EventSource_Break: Timer Break event source
+ * @note TIM6 and TIM7 can only generate an update event.
+ * @note TIM_EventSource_COM and TIM_EventSource_Break are used only with TIM1 and TIM8.
+ * @retval HAL status
+ */
+
+HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_EVENT_SOURCE(EventSource));
+
+ /* Process Locked */
+ __HAL_LOCK(htim);
+
+ /* Change the TIM state */
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Set the event sources */
+ htim->Instance->EGR = EventSource;
+
+ /* Change the TIM state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the OCRef clear feature
+ * @param htim: TIM handle
+ * @param sClearInputConfig: pointer to a TIM_ClearInputConfigTypeDef structure that
+ * contains the OCREF clear feature and parameters for the TIM peripheral.
+ * @param Channel: specifies the TIM Channel
+ * This parameter can be one of the following values:
+ * @arg TIM_Channel_1: TIM Channel 1
+ * @arg TIM_Channel_2: TIM Channel 2
+ * @arg TIM_Channel_3: TIM Channel 3
+ * @arg TIM_Channel_4: TIM Channel 4
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_CHANNELS(Channel));
+ assert_param(IS_TIM_CLEARINPUT_SOURCE(sClearInputConfig->ClearInputSource));
+ assert_param(IS_TIM_CLEARINPUT_POLARITY(sClearInputConfig->ClearInputPolarity));
+ assert_param(IS_TIM_CLEARINPUT_PRESCALER(sClearInputConfig->ClearInputPrescaler));
+ assert_param(IS_TIM_CLEARINPUT_FILTER(sClearInputConfig->ClearInputFilter));
+
+ /* Process Locked */
+ __HAL_LOCK(htim);
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ if(sClearInputConfig->ClearInputSource == TIM_CLEARINPUTSOURCE_ETR)
+ {
+ TIM_ETR_SetConfig(htim->Instance,
+ sClearInputConfig->ClearInputPrescaler,
+ sClearInputConfig->ClearInputPolarity,
+ sClearInputConfig->ClearInputFilter);
+ }
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ if(sClearInputConfig->ClearInputState != RESET)
+ {
+ /* Enable the Ocref clear feature for Channel 1 */
+ htim->Instance->CCMR1 |= TIM_CCMR1_OC1CE;
+ }
+ else
+ {
+ /* Disable the Ocref clear feature for Channel 1 */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC1CE;
+ }
+ }
+ break;
+ case TIM_CHANNEL_2:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ if(sClearInputConfig->ClearInputState != RESET)
+ {
+ /* Enable the Ocref clear feature for Channel 2 */
+ htim->Instance->CCMR1 |= TIM_CCMR1_OC2CE;
+ }
+ else
+ {
+ /* Disable the Ocref clear feature for Channel 2 */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC2CE;
+ }
+ }
+ break;
+ case TIM_CHANNEL_3:
+ {
+ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
+ if(sClearInputConfig->ClearInputState != RESET)
+ {
+ /* Enable the Ocref clear feature for Channel 3 */
+ htim->Instance->CCMR2 |= TIM_CCMR2_OC3CE;
+ }
+ else
+ {
+ /* Disable the Ocref clear feature for Channel 3 */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC3CE;
+ }
+ }
+ break;
+ case TIM_CHANNEL_4:
+ {
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+ if(sClearInputConfig->ClearInputState != RESET)
+ {
+ /* Enable the Ocref clear feature for Channel 4 */
+ htim->Instance->CCMR2 |= TIM_CCMR2_OC4CE;
+ }
+ else
+ {
+ /* Disable the Ocref clear feature for Channel 4 */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC4CE;
+ }
+ }
+ break;
+ default:
+ break;
+ }
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the clock source to be used
+ * @param htim: TIM handle
+ * @param sClockSourceConfig: pointer to a TIM_ClockConfigTypeDef structure that
+ * contains the clock source information for the TIM peripheral.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig)
+{
+ uint32_t tmpsmcr = 0;
+
+ /* Process Locked */
+ __HAL_LOCK(htim);
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_TIM_CLOCKSOURCE(sClockSourceConfig->ClockSource));
+ assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
+ assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler));
+ assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
+
+ /* Reset the SMS, TS, ECE, ETPS and ETRF bits */
+ tmpsmcr = htim->Instance->SMCR;
+ tmpsmcr &= ~(TIM_SMCR_SMS | TIM_SMCR_TS);
+ tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP);
+ htim->Instance->SMCR = tmpsmcr;
+
+ switch (sClockSourceConfig->ClockSource)
+ {
+ case TIM_CLOCKSOURCE_INTERNAL:
+ {
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+ /* Disable slave mode to clock the prescaler directly with the internal clock */
+ htim->Instance->SMCR &= ~TIM_SMCR_SMS;
+ }
+ break;
+
+ case TIM_CLOCKSOURCE_ETRMODE1:
+ {
+ assert_param(IS_TIM_ETR_INSTANCE(htim->Instance));
+ /* Configure the ETR Clock source */
+ TIM_ETR_SetConfig(htim->Instance,
+ sClockSourceConfig->ClockPrescaler,
+ sClockSourceConfig->ClockPolarity,
+ sClockSourceConfig->ClockFilter);
+ /* Get the TIMx SMCR register value */
+ tmpsmcr = htim->Instance->SMCR;
+ /* Reset the SMS and TS Bits */
+ tmpsmcr &= ~(TIM_SMCR_SMS | TIM_SMCR_TS);
+ /* Select the External clock mode1 and the ETRF trigger */
+ tmpsmcr |= (TIM_SLAVEMODE_EXTERNAL1 | TIM_CLOCKSOURCE_ETRMODE1);
+ /* Write to TIMx SMCR */
+ htim->Instance->SMCR = tmpsmcr;
+ }
+ break;
+
+ case TIM_CLOCKSOURCE_ETRMODE2:
+ {
+ assert_param(IS_TIM_ETR_INSTANCE(htim->Instance));
+ /* Configure the ETR Clock source */
+ TIM_ETR_SetConfig(htim->Instance,
+ sClockSourceConfig->ClockPrescaler,
+ sClockSourceConfig->ClockPolarity,
+ sClockSourceConfig->ClockFilter);
+ /* Enable the External clock mode2 */
+ htim->Instance->SMCR |= TIM_SMCR_ECE;
+ }
+ break;
+
+ case TIM_CLOCKSOURCE_TI1:
+ {
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ TIM_TI1_ConfigInputStage(htim->Instance,
+ sClockSourceConfig->ClockPolarity,
+ sClockSourceConfig->ClockFilter);
+ TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1);
+ }
+ break;
+ case TIM_CLOCKSOURCE_TI2:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ TIM_TI2_ConfigInputStage(htim->Instance,
+ sClockSourceConfig->ClockPolarity,
+ sClockSourceConfig->ClockFilter);
+ TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI2);
+ }
+ break;
+ case TIM_CLOCKSOURCE_TI1ED:
+ {
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ TIM_TI1_ConfigInputStage(htim->Instance,
+ sClockSourceConfig->ClockPolarity,
+ sClockSourceConfig->ClockFilter);
+ TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1ED);
+ }
+ break;
+ case TIM_CLOCKSOURCE_ITR0:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR0);
+ }
+ break;
+ case TIM_CLOCKSOURCE_ITR1:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR1);
+ }
+ break;
+ case TIM_CLOCKSOURCE_ITR2:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR2);
+ }
+ break;
+ case TIM_CLOCKSOURCE_ITR3:
+ {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR3);
+ }
+ break;
+
+ default:
+ break;
+ }
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Selects the signal connected to the TI1 input: direct from CH1_input
+ * or a XOR combination between CH1_input, CH2_input & CH3_input
+ * @param htim: TIM handle.
+ * @param TI1_Selection: Indicate whether or not channel 1 is connected to the
+ * output of a XOR gate.
+ * This parameter can be one of the following values:
+ * @arg TIM_TI1SELECTION_CH1: The TIMx_CH1 pin is connected to TI1 input
+ * @arg TIM_TI1SELECTION_XORCOMBINATION: The TIMx_CH1, CH2 and CH3
+ * pins are connected to the TI1 input (XOR combination)
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection)
+{
+ uint32_t tmpcr2 = 0;
+
+ /* Check the parameters */
+ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TI1SELECTION(TI1_Selection));
+
+ /* Get the TIMx CR2 register value */
+ tmpcr2 = htim->Instance->CR2;
+
+ /* Reset the TI1 selection */
+ tmpcr2 &= ~TIM_CR2_TI1S;
+
+ /* Set the the TI1 selection */
+ tmpcr2 |= TI1_Selection;
+
+ /* Write to TIMxCR2 */
+ htim->Instance->CR2 = tmpcr2;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the TIM in Slave mode
+ * @param htim: TIM handle.
+ * @param sSlaveConfig: pointer to a TIM_SlaveConfigTypeDef structure that
+ * contains the selected trigger (internal trigger input, filtered
+ * timer input or external trigger input) and the ) and the Slave
+ * mode (Disable, Reset, Gated, Trigger, External clock mode 1).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig)
+{
+ uint32_t tmpsmcr = 0;
+ uint32_t tmpccmr1 = 0;
+ uint32_t tmpccer = 0;
+
+ /* Check the parameters */
+ assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode));
+ assert_param(IS_TIM_TRIGGER_SELECTION(sSlaveConfig->InputTrigger));
+
+ __HAL_LOCK(htim);
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Get the TIMx SMCR register value */
+ tmpsmcr = htim->Instance->SMCR;
+
+ /* Reset the Trigger Selection Bits */
+ tmpsmcr &= ~TIM_SMCR_TS;
+ /* Set the Input Trigger source */
+ tmpsmcr |= sSlaveConfig->InputTrigger;
+
+ /* Reset the slave mode Bits */
+ tmpsmcr &= ~TIM_SMCR_SMS;
+ /* Set the slave mode */
+ tmpsmcr |= sSlaveConfig->SlaveMode;
+
+ /* Write to TIMx SMCR */
+ htim->Instance->SMCR = tmpsmcr;
+
+ /* Configure the trigger prescaler, filter, and polarity */
+ switch (sSlaveConfig->InputTrigger)
+ {
+ case TIM_TS_ETRF:
+ {
+ /* Check the parameters */
+ assert_param(IS_TIM_ETR_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TRIGGERPRESCALER(sSlaveConfig->TriggerPrescaler));
+ assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity));
+ assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
+ /* Configure the ETR Trigger source */
+ TIM_ETR_SetConfig(htim->Instance,
+ sSlaveConfig->TriggerPrescaler,
+ sSlaveConfig->TriggerPolarity,
+ sSlaveConfig->TriggerFilter);
+ }
+ break;
+
+ case TIM_TS_TI1F_ED:
+ {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
+
+ /* Disable the Channel 1: Reset the CC1E Bit */
+ tmpccer = htim->Instance->CCER;
+ htim->Instance->CCER &= ~TIM_CCER_CC1E;
+ tmpccmr1 = htim->Instance->CCMR1;
+
+ /* Set the filter */
+ tmpccmr1 &= ~TIM_CCMR1_IC1F;
+ tmpccmr1 |= ((sSlaveConfig->TriggerFilter) << 4);
+
+ /* Write to TIMx CCMR1 and CCER registers */
+ htim->Instance->CCMR1 = tmpccmr1;
+ htim->Instance->CCER = tmpccer;
+
+ }
+ break;
+
+ case TIM_TS_TI1FP1:
+ {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity));
+ assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
+
+ /* Configure TI1 Filter and Polarity */
+ TIM_TI1_ConfigInputStage(htim->Instance,
+ sSlaveConfig->TriggerPolarity,
+ sSlaveConfig->TriggerFilter);
+ }
+ break;
+
+ case TIM_TS_TI2FP2:
+ {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity));
+ assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
+
+ /* Configure TI2 Filter and Polarity */
+ TIM_TI2_ConfigInputStage(htim->Instance,
+ sSlaveConfig->TriggerPolarity,
+ sSlaveConfig->TriggerFilter);
+ }
+ break;
+
+ case TIM_TS_ITR0:
+ {
+ /* Check the parameter */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ }
+ break;
+
+ case TIM_TS_ITR1:
+ {
+ /* Check the parameter */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ }
+ break;
+
+ case TIM_TS_ITR2:
+ {
+ /* Check the parameter */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ }
+ break;
+
+ case TIM_TS_ITR3:
+ {
+ /* Check the parameter */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Read the captured value from Capture Compare unit
+ * @param htim: TIM handle.
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval Captured value
+ */
+uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ uint32_t tmpreg = 0;
+
+ __HAL_LOCK(htim);
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+
+ /* Return the capture 1 value */
+ tmpreg = htim->Instance->CCR1;
+
+ break;
+ }
+ case TIM_CHANNEL_2:
+ {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+
+ /* Return the capture 2 value */
+ tmpreg = htim->Instance->CCR2;
+
+ break;
+ }
+
+ case TIM_CHANNEL_3:
+ {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
+
+ /* Return the capture 3 value */
+ tmpreg = htim->Instance->CCR3;
+
+ break;
+ }
+
+ case TIM_CHANNEL_4:
+ {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+
+ /* Return the capture 4 value */
+ tmpreg = htim->Instance->CCR4;
+
+ break;
+ }
+
+ default:
+ break;
+ }
+
+ __HAL_UNLOCK(htim);
+ return tmpreg;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIM_Group9 TIM Callbacks functions
+ * @brief TIM Callbacks functions
+ *
+@verbatim
+ ==============================================================================
+ ##### TIM Callbacks functions #####
+ ==============================================================================
+ [..]
+ This section provides TIM callback functions:
+ (+) Timer Period elapsed callback
+ (+) Timer Output Compare callback
+ (+) Timer Input capture callback
+ (+) Timer Trigger callback
+ (+) Timer Error callback
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Period elapsed callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the __HAL_TIM_PeriodElapsedCallback could be implemented in the user file
+ */
+
+}
+/**
+ * @brief Output Compare callback in non blocking mode
+ * @param htim : TIM OC handle
+ * @retval None
+ */
+__weak void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the __HAL_TIM_OC_DelayElapsedCallback could be implemented in the user file
+ */
+}
+/**
+ * @brief Input Capture callback in non blocking mode
+ * @param htim : TIM IC handle
+ * @retval None
+ */
+__weak void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the __HAL_TIM_IC_CaptureCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief PWM Pulse finished callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the __HAL_TIM_PWM_PulseFinishedCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Hall Trigger detection callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_TriggerCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Timer error callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIM_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIM_Group10 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State functions #####
+ ==============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the TIM Base state
+ * @param htim: TIM Base handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim)
+{
+ return htim->State;
+}
+
+/**
+ * @brief Return the TIM OC state
+ * @param htim: TIM Ouput Compare handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim)
+{
+ return htim->State;
+}
+
+/**
+ * @brief Return the TIM PWM state
+ * @param htim: TIM handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim)
+{
+ return htim->State;
+}
+
+/**
+ * @brief Return the TIM Input Capture state
+ * @param htim: TIM IC handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim)
+{
+ return htim->State;
+}
+
+/**
+ * @brief Return the TIM One Pulse Mode state
+ * @param htim: TIM OPM handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim)
+{
+ return htim->State;
+}
+
+/**
+ * @brief Return the TIM Encoder Mode state
+ * @param htim: TIM Encoder handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim)
+{
+ return htim->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief TIM DMA error callback
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+void HAL_TIM_DMAError(DMA_HandleTypeDef *hdma)
+{
+ TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ htim->State= HAL_TIM_STATE_READY;
+
+ HAL_TIM_ErrorCallback(htim);
+}
+
+/**
+ * @brief TIM DMA Delay Pulse complete callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+void HAL_TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma)
+{
+ TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ htim->State= HAL_TIM_STATE_READY;
+
+ HAL_TIM_PWM_PulseFinishedCallback(htim);
+}
+/**
+ * @brief TIM DMA Capture complete callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+void HAL_TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma)
+{
+ TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ htim->State= HAL_TIM_STATE_READY;
+
+ HAL_TIM_IC_CaptureCallback(htim);
+
+}
+
+/**
+ * @brief TIM DMA Period Elapse complete callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma)
+{
+ TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ htim->State= HAL_TIM_STATE_READY;
+
+ HAL_TIM_PeriodElapsedCallback(htim);
+}
+
+/**
+ * @brief TIM DMA Trigger callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma)
+{
+ TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ htim->State= HAL_TIM_STATE_READY;
+
+ HAL_TIM_TriggerCallback(htim);
+}
+
+/**
+ * @brief Time Base configuration
+ * @param TIMx: TIM periheral
+ * @retval None
+ */
+void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure)
+{
+ uint32_t tmpcr1 = 0;
+ tmpcr1 = TIMx->CR1;
+
+ /* Set TIM Time Base Unit parameters ---------------------------------------*/
+ if(IS_TIM_CC3_INSTANCE(TIMx) != RESET)
+ {
+ /* Select the Counter Mode */
+ tmpcr1 &= ~(TIM_CR1_DIR | TIM_CR1_CMS);
+ tmpcr1 |= Structure->CounterMode;
+ }
+
+ if(IS_TIM_CC1_INSTANCE(TIMx) != RESET)
+ {
+ /* Set the clock division */
+ tmpcr1 &= ~TIM_CR1_CKD;
+ tmpcr1 |= (uint32_t)Structure->ClockDivision;
+ }
+
+ TIMx->CR1 = tmpcr1;
+
+ /* Set the Autoreload value */
+ TIMx->ARR = (uint32_t)Structure->Period ;
+
+ /* Set the Prescaler value */
+ TIMx->PSC = (uint32_t)Structure->Prescaler;
+
+ if(IS_TIM_ADVANCED_INSTANCE(TIMx) != RESET)
+ {
+ /* Set the Repetition Counter value */
+ TIMx->RCR = Structure->RepetitionCounter;
+ }
+
+ /* Generate an update event to reload the Prescaler
+ and the repetition counter(only for TIM1 and TIM8) value immediatly */
+ TIMx->EGR = TIM_EGR_UG;
+}
+
+/**
+ * @brief Time Ouput Compare 1 configuration
+ * @param TIMx to select the TIM peripheral
+ * @param OC_Config: The ouput configuration structure
+ * @retval None
+ */
+static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
+{
+ uint32_t tmpccmrx = 0;
+ uint32_t tmpccer = 0;
+ uint32_t tmpcr2 = 0;
+
+ /* Disable the Channel 1: Reset the CC1E Bit */
+ TIMx->CCER &= ~TIM_CCER_CC1E;
+
+ /* Get the TIMx CCER register value */
+ tmpccer = TIMx->CCER;
+ /* Get the TIMx CR2 register value */
+ tmpcr2 = TIMx->CR2;
+
+ /* Get the TIMx CCMR1 register value */
+ tmpccmrx = TIMx->CCMR1;
+
+ /* Reset the Output Compare Mode Bits */
+ tmpccmrx &= ~TIM_CCMR1_OC1M;
+ tmpccmrx &= ~TIM_CCMR1_CC1S;
+ /* Select the Output Compare Mode */
+ tmpccmrx |= OC_Config->OCMode;
+
+ /* Reset the Output Polarity level */
+ tmpccer &= ~TIM_CCER_CC1P;
+ /* Set the Output Compare Polarity */
+ tmpccer |= OC_Config->OCPolarity;
+
+
+ if(IS_TIM_ADVANCED_INSTANCE(TIMx) != RESET)
+ {
+ /* Reset the Output N Polarity level */
+ tmpccer &= ~TIM_CCER_CC1NP;
+ /* Set the Output N Polarity */
+ tmpccer |= OC_Config->OCNPolarity;
+ /* Reset the Output N State */
+ tmpccer &= ~TIM_CCER_CC1NE;
+
+ /* Reset the Output Compare and Output Compare N IDLE State */
+ tmpcr2 &= ~TIM_CR2_OIS1;
+ tmpcr2 &= ~TIM_CR2_OIS1N;
+ /* Set the Output Idle state */
+ tmpcr2 |= OC_Config->OCIdleState;
+ /* Set the Output N Idle state */
+ tmpcr2 |= OC_Config->OCNIdleState;
+ }
+ /* Write to TIMx CR2 */
+ TIMx->CR2 = tmpcr2;
+
+ /* Write to TIMx CCMR1 */
+ TIMx->CCMR1 = tmpccmrx;
+
+ /* Set the Capture Compare Register value */
+ TIMx->CCR1 = OC_Config->Pulse;
+
+ /* Write to TIMx CCER */
+ TIMx->CCER = tmpccer;
+}
+
+/**
+ * @brief Time Ouput Compare 2 configuration
+ * @param TIMx to select the TIM peripheral
+ * @param OC_Config: The ouput configuration structure
+ * @retval None
+ */
+void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
+{
+ uint32_t tmpccmrx = 0;
+ uint32_t tmpccer = 0;
+ uint32_t tmpcr2 = 0;
+
+ /* Disable the Channel 2: Reset the CC2E Bit */
+ TIMx->CCER &= ~TIM_CCER_CC2E;
+
+ /* Get the TIMx CCER register value */
+ tmpccer = TIMx->CCER;
+ /* Get the TIMx CR2 register value */
+ tmpcr2 = TIMx->CR2;
+
+ /* Get the TIMx CCMR1 register value */
+ tmpccmrx = TIMx->CCMR1;
+
+ /* Reset the Output Compare mode and Capture/Compare selection Bits */
+ tmpccmrx &= ~TIM_CCMR1_OC2M;
+ tmpccmrx &= ~TIM_CCMR1_CC2S;
+
+ /* Select the Output Compare Mode */
+ tmpccmrx |= (OC_Config->OCMode << 8);
+
+ /* Reset the Output Polarity level */
+ tmpccer &= ~TIM_CCER_CC2P;
+ /* Set the Output Compare Polarity */
+ tmpccer |= (OC_Config->OCPolarity << 4);
+
+ if(IS_TIM_ADVANCED_INSTANCE(TIMx) != RESET)
+ {
+ assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity));
+ assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState));
+ assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState));
+
+ /* Reset the Output N Polarity level */
+ tmpccer &= ~TIM_CCER_CC2NP;
+ /* Set the Output N Polarity */
+ tmpccer |= (OC_Config->OCNPolarity << 4);
+ /* Reset the Output N State */
+ tmpccer &= ~TIM_CCER_CC2NE;
+
+ /* Reset the Output Compare and Output Compare N IDLE State */
+ tmpcr2 &= ~TIM_CR2_OIS2;
+ tmpcr2 &= ~TIM_CR2_OIS2N;
+ /* Set the Output Idle state */
+ tmpcr2 |= (OC_Config->OCIdleState << 2);
+ /* Set the Output N Idle state */
+ tmpcr2 |= (OC_Config->OCNIdleState << 2);
+ }
+ /* Write to TIMx CR2 */
+ TIMx->CR2 = tmpcr2;
+
+ /* Write to TIMx CCMR1 */
+ TIMx->CCMR1 = tmpccmrx;
+
+ /* Set the Capture Compare Register value */
+ TIMx->CCR2 = OC_Config->Pulse;
+
+ /* Write to TIMx CCER */
+ TIMx->CCER = tmpccer;
+}
+
+/**
+ * @brief Time Ouput Compare 3 configuration
+ * @param TIMx to select the TIM peripheral
+ * @param OC_Config: The ouput configuration structure
+ * @retval None
+ */
+static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
+{
+ uint32_t tmpccmrx = 0;
+ uint32_t tmpccer = 0;
+ uint32_t tmpcr2 = 0;
+
+ /* Disable the Channel 3: Reset the CC2E Bit */
+ TIMx->CCER &= ~TIM_CCER_CC3E;
+
+ /* Get the TIMx CCER register value */
+ tmpccer = TIMx->CCER;
+ /* Get the TIMx CR2 register value */
+ tmpcr2 = TIMx->CR2;
+
+ /* Get the TIMx CCMR2 register value */
+ tmpccmrx = TIMx->CCMR2;
+
+ /* Reset the Output Compare mode and Capture/Compare selection Bits */
+ tmpccmrx &= ~TIM_CCMR2_OC3M;
+ tmpccmrx &= ~TIM_CCMR2_CC3S;
+ /* Select the Output Compare Mode */
+ tmpccmrx |= OC_Config->OCMode;
+
+ /* Reset the Output Polarity level */
+ tmpccer &= ~TIM_CCER_CC3P;
+ /* Set the Output Compare Polarity */
+ tmpccer |= (OC_Config->OCPolarity << 8);
+
+ if(IS_TIM_ADVANCED_INSTANCE(TIMx) != RESET)
+ {
+ assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity));
+ assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState));
+ assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState));
+
+ /* Reset the Output N Polarity level */
+ tmpccer &= ~TIM_CCER_CC3NP;
+ /* Set the Output N Polarity */
+ tmpccer |= (OC_Config->OCNPolarity << 8);
+ /* Reset the Output N State */
+ tmpccer &= ~TIM_CCER_CC3NE;
+
+ /* Reset the Output Compare and Output Compare N IDLE State */
+ tmpcr2 &= ~TIM_CR2_OIS3;
+ tmpcr2 &= ~TIM_CR2_OIS3N;
+ /* Set the Output Idle state */
+ tmpcr2 |= (OC_Config->OCIdleState << 4);
+ /* Set the Output N Idle state */
+ tmpcr2 |= (OC_Config->OCNIdleState << 4);
+ }
+ /* Write to TIMx CR2 */
+ TIMx->CR2 = tmpcr2;
+
+ /* Write to TIMx CCMR2 */
+ TIMx->CCMR2 = tmpccmrx;
+
+ /* Set the Capture Compare Register value */
+ TIMx->CCR3 = OC_Config->Pulse;
+
+ /* Write to TIMx CCER */
+ TIMx->CCER = tmpccer;
+}
+
+/**
+ * @brief Time Ouput Compare 4 configuration
+ * @param TIMx to select the TIM peripheral
+ * @param OC_Config: The ouput configuration structure
+ * @retval None
+ */
+static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
+{
+ uint32_t tmpccmrx = 0;
+ uint32_t tmpccer = 0;
+ uint32_t tmpcr2 = 0;
+
+ /* Disable the Channel 4: Reset the CC4E Bit */
+ TIMx->CCER &= ~TIM_CCER_CC4E;
+
+ /* Get the TIMx CCER register value */
+ tmpccer = TIMx->CCER;
+ /* Get the TIMx CR2 register value */
+ tmpcr2 = TIMx->CR2;
+
+ /* Get the TIMx CCMR2 register value */
+ tmpccmrx = TIMx->CCMR2;
+
+ /* Reset the Output Compare mode and Capture/Compare selection Bits */
+ tmpccmrx &= ~TIM_CCMR2_OC4M;
+ tmpccmrx &= ~TIM_CCMR2_CC4S;
+
+ /* Select the Output Compare Mode */
+ tmpccmrx |= (OC_Config->OCMode << 8);
+
+ /* Reset the Output Polarity level */
+ tmpccer &= ~TIM_CCER_CC4P;
+ /* Set the Output Compare Polarity */
+ tmpccer |= (OC_Config->OCPolarity << 12);
+
+ /*if((TIMx == TIM1) || (TIMx == TIM8))*/
+ if(IS_TIM_ADVANCED_INSTANCE(TIMx) != RESET)
+ {
+ assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState));
+ /* Reset the Output Compare IDLE State */
+ tmpcr2 &= ~TIM_CR2_OIS4;
+ /* Set the Output Idle state */
+ tmpcr2 |= (OC_Config->OCIdleState << 6);
+ }
+ /* Write to TIMx CR2 */
+ TIMx->CR2 = tmpcr2;
+
+ /* Write to TIMx CCMR2 */
+ TIMx->CCMR2 = tmpccmrx;
+
+ /* Set the Capture Compare Register value */
+ TIMx->CCR4 = OC_Config->Pulse;
+
+ /* Write to TIMx CCER */
+ TIMx->CCER = tmpccer;
+}
+
+/**
+ * @brief Configure the TI1 as Input.
+ * @param TIMx to select the TIM peripheral.
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPolarity_Rising
+ * @arg TIM_ICPolarity_Falling
+ * @arg TIM_ICPolarity_BothEdge
+ * @param TIM_ICSelection: specifies the input to be used.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICSelection_DirectTI: TIM Input 1 is selected to be connected to IC1.
+ * @arg TIM_ICSelection_IndirectTI: TIM Input 1 is selected to be connected to IC2.
+ * @arg TIM_ICSelection_TRC: TIM Input 1 is selected to be connected to TRC.
+ * @param TIM_ICFilter: Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ */
+void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
+ uint32_t TIM_ICFilter)
+{
+ uint32_t tmpccmr1 = 0;
+ uint32_t tmpccer = 0;
+
+ /* Disable the Channel 1: Reset the CC1E Bit */
+ TIMx->CCER &= ~TIM_CCER_CC1E;
+ tmpccmr1 = TIMx->CCMR1;
+ tmpccer = TIMx->CCER;
+
+ /* Select the Input */
+ if(IS_TIM_CC2_INSTANCE(TIMx) != RESET)
+ {
+ tmpccmr1 &= ~TIM_CCMR1_CC1S;
+ tmpccmr1 |= TIM_ICSelection;
+ }
+ else
+ {
+ tmpccmr1 &= ~TIM_CCMR1_CC1S;
+ tmpccmr1 |= TIM_CCMR1_CC1S_0;
+ }
+
+ /* Set the filter */
+ tmpccmr1 &= ~TIM_CCMR1_IC1F;
+ tmpccmr1 |= (TIM_ICFilter << 4);
+
+ /* Select the Polarity and set the CC1E Bit */
+ tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP);
+ tmpccer |= TIM_ICPolarity;
+
+ /* Write to TIMx CCMR1 and CCER registers */
+ TIMx->CCMR1 = tmpccmr1;
+ TIMx->CCER = tmpccer;
+}
+
+/**
+ * @brief Configure the Polarity and Filter for TI1.
+ * @param TIMx to select the TIM peripheral.
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPolarity_Rising
+ * @arg TIM_ICPolarity_Falling
+ * @arg TIM_ICPolarity_BothEdge
+ * @param TIM_ICFilter: Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ */
+static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter)
+{
+ uint32_t tmpccmr1 = 0;
+ uint32_t tmpccer = 0;
+
+ /* Disable the Channel 1: Reset the CC1E Bit */
+ tmpccer = TIMx->CCER;
+ TIMx->CCER &= ~TIM_CCER_CC1E;
+ tmpccmr1 = TIMx->CCMR1;
+
+ /* Set the filter */
+ tmpccmr1 &= ~TIM_CCMR1_IC1F;
+ tmpccmr1 |= (TIM_ICFilter << 4);
+
+ /* Select the Polarity and set the CC1E Bit */
+ tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP);
+ tmpccer |= TIM_ICPolarity;
+
+ /* Write to TIMx CCMR1 and CCER registers */
+ TIMx->CCMR1 = tmpccmr1;
+ TIMx->CCER = tmpccer;
+}
+
+/**
+ * @brief Configure the TI2 as Input.
+ * @param TIMx to select the TIM peripheral
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPolarity_Rising
+ * @arg TIM_ICPolarity_Falling
+ * @arg TIM_ICPolarity_BothEdge
+ * @param TIM_ICSelection: specifies the input to be used.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICSelection_DirectTI: TIM Input 2 is selected to be connected to IC2.
+ * @arg TIM_ICSelection_IndirectTI: TIM Input 2 is selected to be connected to IC1.
+ * @arg TIM_ICSelection_TRC: TIM Input 2 is selected to be connected to TRC.
+ * @param TIM_ICFilter: Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ */
+static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
+ uint32_t TIM_ICFilter)
+{
+ uint32_t tmpccmr1 = 0;
+ uint32_t tmpccer = 0;
+
+ /* Disable the Channel 2: Reset the CC2E Bit */
+ TIMx->CCER &= ~TIM_CCER_CC2E;
+ tmpccmr1 = TIMx->CCMR1;
+ tmpccer = TIMx->CCER;
+
+ /* Select the Input */
+ tmpccmr1 &= ~TIM_CCMR1_CC2S;
+ tmpccmr1 |= (TIM_ICSelection << 8);
+
+ /* Set the filter */
+ tmpccmr1 &= ~TIM_CCMR1_IC2F;
+ tmpccmr1 |= (TIM_ICFilter << 12);
+
+ /* Select the Polarity and set the CC2E Bit */
+ tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP);
+ tmpccer |= (TIM_ICPolarity << 4);
+
+ /* Write to TIMx CCMR1 and CCER registers */
+ TIMx->CCMR1 = tmpccmr1 ;
+ TIMx->CCER = tmpccer;
+}
+
+/**
+ * @brief Configure the Polarity and Filter for TI2.
+ * @param TIMx to select the TIM peripheral.
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPolarity_Rising
+ * @arg TIM_ICPolarity_Falling
+ * @arg TIM_ICPolarity_BothEdge
+ * @param TIM_ICFilter: Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ */
+static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter)
+{
+ uint32_t tmpccmr1 = 0;
+ uint32_t tmpccer = 0;
+
+ /* Disable the Channel 2: Reset the CC2E Bit */
+ TIMx->CCER &= ~TIM_CCER_CC2E;
+ tmpccmr1 = TIMx->CCMR1;
+ tmpccer = TIMx->CCER;
+
+ /* Set the filter */
+ tmpccmr1 &= ~TIM_CCMR1_IC2F;
+ tmpccmr1 |= (TIM_ICFilter << 12);
+
+ /* Select the Polarity and set the CC2E Bit */
+ tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP);
+ tmpccer |= (TIM_ICPolarity << 4);
+
+ /* Write to TIMx CCMR1 and CCER registers */
+ TIMx->CCMR1 = tmpccmr1 ;
+ TIMx->CCER = tmpccer;
+}
+
+/**
+ * @brief Configure the TI3 as Input.
+ * @param TIMx to select the TIM peripheral
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPolarity_Rising
+ * @arg TIM_ICPolarity_Falling
+ * @arg TIM_ICPolarity_BothEdge
+ * @param TIM_ICSelection: specifies the input to be used.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICSelection_DirectTI: TIM Input 3 is selected to be connected to IC3.
+ * @arg TIM_ICSelection_IndirectTI: TIM Input 3 is selected to be connected to IC4.
+ * @arg TIM_ICSelection_TRC: TIM Input 3 is selected to be connected to TRC.
+ * @param TIM_ICFilter: Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ */
+static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
+ uint32_t TIM_ICFilter)
+{
+ uint32_t tmpccmr2 = 0;
+ uint32_t tmpccer = 0;
+
+ /* Disable the Channel 3: Reset the CC3E Bit */
+ TIMx->CCER &= ~TIM_CCER_CC3E;
+ tmpccmr2 = TIMx->CCMR2;
+ tmpccer = TIMx->CCER;
+
+ /* Select the Input */
+ tmpccmr2 &= ~TIM_CCMR2_CC3S;
+ tmpccmr2 |= TIM_ICSelection;
+
+ /* Set the filter */
+ tmpccmr2 &= ~TIM_CCMR2_IC3F;
+ tmpccmr2 |= (TIM_ICFilter << 4);
+
+ /* Select the Polarity and set the CC3E Bit */
+ tmpccer &= ~(TIM_CCER_CC3P | TIM_CCER_CC3NP);
+ tmpccer |= (TIM_ICPolarity << 8);
+
+ /* Write to TIMx CCMR2 and CCER registers */
+ TIMx->CCMR2 = tmpccmr2;
+ TIMx->CCER = tmpccer;
+}
+
+/**
+ * @brief Configure the TI4 as Input.
+ * @param TIMx to select the TIM peripheral
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPolarity_Rising
+ * @arg TIM_ICPolarity_Falling
+ * @arg TIM_ICPolarity_BothEdge
+ * @param TIM_ICSelection: specifies the input to be used.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICSelection_DirectTI: TIM Input 4 is selected to be connected to IC4.
+ * @arg TIM_ICSelection_IndirectTI: TIM Input 4 is selected to be connected to IC3.
+ * @arg TIM_ICSelection_TRC: TIM Input 4 is selected to be connected to TRC.
+ * @param TIM_ICFilter: Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ */
+static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
+ uint32_t TIM_ICFilter)
+{
+ uint32_t tmpccmr2 = 0;
+ uint32_t tmpccer = 0;
+
+ /* Disable the Channel 4: Reset the CC4E Bit */
+ TIMx->CCER &= ~TIM_CCER_CC4E;
+ tmpccmr2 = TIMx->CCMR2;
+ tmpccer = TIMx->CCER;
+
+ /* Select the Input */
+ tmpccmr2 &= ~TIM_CCMR2_CC4S;
+ tmpccmr2 |= (TIM_ICSelection << 8);
+
+ /* Set the filter */
+ tmpccmr2 &= ~TIM_CCMR2_IC4F;
+ tmpccmr2 |= (TIM_ICFilter << 12);
+
+ /* Select the Polarity and set the CC4E Bit */
+ tmpccer &= ~(TIM_CCER_CC4P | TIM_CCER_CC4NP);
+ tmpccer |= (TIM_ICPolarity << 12);
+
+ /* Write to TIMx CCMR2 and CCER registers */
+ TIMx->CCMR2 = tmpccmr2;
+ TIMx->CCER = tmpccer ;
+}
+
+/**
+ * @brief Selects the Input Trigger source
+ * @param TIMx to select the TIM peripheral
+ * @param InputTriggerSource: The Input Trigger source.
+ * This parameter can be one of the following values:
+ * @arg TIM_TS_ITR0: Internal Trigger 0
+ * @arg TIM_TS_ITR1: Internal Trigger 1
+ * @arg TIM_TS_ITR2: Internal Trigger 2
+ * @arg TIM_TS_ITR3: Internal Trigger 3
+ * @arg TIM_TS_TI1F_ED: TI1 Edge Detector
+ * @arg TIM_TS_TI1FP1: Filtered Timer Input 1
+ * @arg TIM_TS_TI2FP2: Filtered Timer Input 2
+ * @arg TIM_TS_ETRF: External Trigger input
+ * @retval None
+ */
+static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint16_t TIM_ITRx)
+{
+ uint32_t tmpsmcr = 0;
+
+ /* Get the TIMx SMCR register value */
+ tmpsmcr = TIMx->SMCR;
+ /* Reset the TS Bits */
+ tmpsmcr &= ~TIM_SMCR_TS;
+ /* Set the Input Trigger source and the slave mode*/
+ tmpsmcr |= TIM_ITRx | TIM_SLAVEMODE_EXTERNAL1;
+ /* Write to TIMx SMCR */
+ TIMx->SMCR = tmpsmcr;
+}
+/**
+ * @brief Configures the TIMx External Trigger (ETR).
+ * @param TIMx to select the TIM peripheral
+ * @param TIM_ExtTRGPrescaler: The external Trigger Prescaler.
+ * This parameter can be one of the following values:
+ * @arg TIM_ExtTRGPSC_DIV1: ETRP Prescaler OFF.
+ * @arg TIM_ExtTRGPSC_DIV2: ETRP frequency divided by 2.
+ * @arg TIM_ExtTRGPSC_DIV4: ETRP frequency divided by 4.
+ * @arg TIM_ExtTRGPSC_DIV8: ETRP frequency divided by 8.
+ * @param TIM_ExtTRGPolarity: The external Trigger Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ExtTRGPolarity_Inverted: active low or falling edge active.
+ * @arg TIM_ExtTRGPolarity_NonInverted: active high or rising edge active.
+ * @param ExtTRGFilter: External Trigger Filter.
+ * This parameter must be a value between 0x00 and 0x0F
+ * @retval None
+ */
+static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler,
+ uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter)
+{
+ uint32_t tmpsmcr = 0;
+
+ tmpsmcr = TIMx->SMCR;
+
+ /* Reset the ETR Bits */
+ tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP);
+
+ /* Set the Prescaler, the Filter value and the Polarity */
+ tmpsmcr |= (uint32_t)(TIM_ExtTRGPrescaler | (TIM_ExtTRGPolarity | (ExtTRGFilter << 8)));
+
+ /* Write to TIMx SMCR */
+ TIMx->SMCR = tmpsmcr;
+}
+
+/**
+ * @brief Enables or disables the TIM Capture Compare Channel x.
+ * @param TIMx to select the TIM peripheral
+ * @param Channel: specifies the TIM Channel
+ * This parameter can be one of the following values:
+ * @arg TIM_Channel_1: TIM Channel 1
+ * @arg TIM_Channel_2: TIM Channel 2
+ * @arg TIM_Channel_3: TIM Channel 3
+ * @arg TIM_Channel_4: TIM Channel 4
+ * @param ChannelState: specifies the TIM Channel CCxE bit new state.
+ * This parameter can be: TIM_CCx_ENABLE or TIM_CCx_Disable.
+ * @retval None
+ */
+void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState)
+{
+ uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_TIM_CC1_INSTANCE(TIMx));
+ assert_param(IS_TIM_CHANNELS(Channel));
+
+ tmp = TIM_CCER_CC1E << Channel;
+
+ /* Reset the CCxE Bit */
+ TIMx->CCER &= ~tmp;
+
+ /* Set or reset the CCxE Bit */
+ TIMx->CCER |= (uint32_t)(ChannelState << Channel);
+}
+
+
+/**
+ * @}
+ */
+
+#endif /* HAL_TIM_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim_ex.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim_ex.c
new file mode 100644
index 0000000..a4d7d2b
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim_ex.c
@@ -0,0 +1,1810 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_tim_ex.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief TIM HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Timer extension peripheral:
+ * + Time Hall Sensor Interface Initialization
+ * + Time Hall Sensor Interface Start
+ * + Time Complementary signal bread and dead time configuration
+ * + Time Master and Slave synchronization configuration
+ @verbatim
+ ==============================================================================
+ ##### TIMER Extended features #####
+ ==============================================================================
+ [..]
+ The Timer Extension features include:
+ (#) Complementary outputs with programmable dead-time for :
+ (++) Input Capture
+ (++) Output Compare
+ (++) PWM generation (Edge and Center-aligned Mode)
+ (++) One-pulse mode output
+ (#) Synchronization circuit to control the timer with external signals and to
+ interconnect several timers together.
+ (#) Break input to put the timer output signals in reset state or in a known state.
+ (#) Supports incremental (quadrature) encoder and hall-sensor circuitry for
+ positioning purposes
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#) Initialize the TIM low level resources by implementing the following functions
+ depending from feature used :
+ (++) Complementary Output Compare : HAL_TIM_OC_MspInit()
+ (++) Complementary PWM generation : HAL_TIM_PWM_MspInit()
+ (++) Complementary One-pulse mode output : HAL_TIM_OnePulse_MspInit()
+ (++) Hall Sensor output : HAL_TIM_HallSensor_MspInit()
+
+ (#) Initialize the TIM low level resources :
+ (##) Enable the TIM interface clock using __TIMx_CLK_ENABLE();
+ (##) TIM pins configuration
+ (+++) Enable the clock for the TIM GPIOs using the following function:
+ __GPIOx_CLK_ENABLE();
+ (+++) Configure these TIM pins in Alternate function mode using HAL_GPIO_Init();
+
+ (#) The external Clock can be configured, if needed (the default clock is the
+ internal clock from the APBx), using the following function:
+ HAL_TIM_ConfigClockSource, the clock configuration should be done before
+ any start function.
+
+ (#) Configure the TIM in the desired functioning mode using one of the
+ initialization function of this driver:
+ (++) HAL_TIMEx_HallSensor_Init and HAL_TIMEx_ConfigCommutationEvent: to use the
+ Timer Hall Sensor Interface and the commutation event with the corresponding
+ Interrupt and DMA request if needed (Note that One Timer is used to interface
+ with the Hall sensor Interface and another Timer should be used to use
+ the commutation event).
+
+ (#) Activate the TIM peripheral using one of the start functions:
+ (++) Complementary Output Compare : HAL_TIMEx_OCN_Start(), HAL_TIMEx_OCN_Start_DMA(), HAL_TIMEx_OC_Start_IT()
+ (++) Complementary PWM generation : HAL_TIMEx_PWMN_Start(), HAL_TIMEx_PWMN_Start_DMA(), HAL_TIMEx_PWMN_Start_IT()
+ (++) Complementary One-pulse mode output : HAL_TIMEx_OnePulseN_Start(), HAL_TIMEx_OnePulseN_Start_IT()
+ (++) Hall Sensor output : HAL_TIMEx_HallSensor_Start(), HAL_TIMEx_HallSensor_Start_DMA(), HAL_TIMEx_HallSensor_Start_IT().
+
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup TIMEx
+ * @brief TIM HAL module driver
+ * @{
+ */
+
+#ifdef HAL_TIM_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelNState);
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup TIMEx_Private_Functions
+ * @{
+ */
+
+/** @defgroup TIMEx_Group1 Timer Hall Sensor functions
+ * @brief Timer Hall Sensor functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Timer Hall Sensor functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure TIM HAL Sensor.
+ (+) De-initialize TIM HAL Sensor.
+ (+) Start the Hall Sensor Interface.
+ (+) Stop the Hall Sensor Interface.
+ (+) Start the Hall Sensor Interface and enable interrupts.
+ (+) Stop the Hall Sensor Interface and disable interrupts.
+ (+) Start the Hall Sensor Interface and enable DMA transfers.
+ (+) Stop the Hall Sensor Interface and disable DMA transfers.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Initializes the TIM Hall Sensor Interface and create the associated handle.
+ * @param htim: TIM Encoder Interface handle
+ * @param sConfig: TIM Hall Sensor configuration structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSensor_InitTypeDef* sConfig)
+{
+ TIM_OC_InitTypeDef OC_Config;
+
+ /* Check the TIM handle allocation */
+ if(htim == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode));
+ assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
+ assert_param(IS_TIM_IC_POLARITY(sConfig->IC1Polarity));
+ assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler));
+ assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter));
+
+ /* Set the TIM state */
+ htim->State= HAL_TIM_STATE_BUSY;
+
+ /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
+ HAL_TIMEx_HallSensor_MspInit(htim);
+
+ /* Configure the Time base in the Encoder Mode */
+ TIM_Base_SetConfig(htim->Instance, &htim->Init);
+
+ /* Configure the Channel 1 as Input Channel to interface with the three Outputs of the Hall sensor */
+ TIM_TI1_SetConfig(htim->Instance, sConfig->IC1Polarity, TIM_ICSELECTION_TRC, sConfig->IC1Filter);
+
+ /* Reset the IC1PSC Bits */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC;
+ /* Set the IC1PSC value */
+ htim->Instance->CCMR1 |= sConfig->IC1Prescaler;
+
+ /* Enable the Hall sensor interface (XOR function of the three inputs) */
+ htim->Instance->CR2 |= TIM_CR2_TI1S;
+
+ /* Select the TIM_TS_TI1F_ED signal as Input trigger for the TIM */
+ htim->Instance->SMCR &= ~TIM_SMCR_TS;
+ htim->Instance->SMCR |= TIM_TS_TI1F_ED;
+
+ /* Use the TIM_TS_TI1F_ED signal to reset the TIM counter each edge detection */
+ htim->Instance->SMCR &= ~TIM_SMCR_SMS;
+ htim->Instance->SMCR |= TIM_SLAVEMODE_RESET;
+
+ /* Program channel 2 in PWM 2 mode with the desired Commutation_Delay*/
+ OC_Config.OCFastMode = TIM_OCFAST_DISABLE;
+ OC_Config.OCIdleState = TIM_OCIDLESTATE_RESET;
+ OC_Config.OCMode = TIM_OCMODE_PWM2;
+ OC_Config.OCNIdleState = TIM_OCNIDLESTATE_RESET;
+ OC_Config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
+ OC_Config.OCPolarity = TIM_OCPOLARITY_HIGH;
+ OC_Config.Pulse = sConfig->Commutation_Delay;
+
+ TIM_OC2_SetConfig(htim->Instance, &OC_Config);
+
+ /* Select OC2REF as trigger output on TRGO: write the MMS bits in the TIMx_CR2
+ register to 101 */
+ htim->Instance->CR2 &= ~TIM_CR2_MMS;
+ htim->Instance->CR2 |= TIM_TRGO_OC2REF;
+
+ /* Initialize the TIM state*/
+ htim->State= HAL_TIM_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the TIM Hall Sensor interface
+ * @param htim: TIM Hall Sensor handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Disable the TIM Peripheral Clock */
+ __HAL_TIM_DISABLE(htim);
+
+ /* DeInit the low level hardware: GPIO, CLOCK, NVIC */
+ HAL_TIMEx_HallSensor_MspDeInit(htim);
+
+ /* Change TIM state */
+ htim->State = HAL_TIM_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the TIM Hall Sensor MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIMEx_HallSensor_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes TIM Hall Sensor MSP.
+ * @param htim: TIM handle
+ * @retval None
+ */
+__weak void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIMEx_HallSensor_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Starts the TIM Hall Sensor Interface.
+ * @param htim : TIM Hall Sensor handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
+
+ /* Enable the Input Capture channels 1
+ (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Hall sensor Interface.
+ * @param htim : TIM Hall Sensor handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
+
+ /* Disable the Input Capture channels 1, 2 and 3
+ (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Hall Sensor Interface in interrupt mode.
+ * @param htim : TIM Hall Sensor handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
+
+ /* Enable the capture compare Interrupts 1 event */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+
+ /* Enable the Input Capture channels 1
+ (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Hall Sensor Interface in interrupt mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
+
+ /* Disable the Input Capture channels 1
+ (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+
+ /* Disable the capture compare Interrupts event */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Hall Sensor Interface in DMA mode.
+ * @param htim : TIM Hall Sensor handle
+ * @param pData: The destination Buffer address.
+ * @param Length: The length of data to be transferred from TIM peripheral to memory.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if(((uint32_t)pData == 0 ) && (Length > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+ /* Enable the Input Capture channels 1
+ (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+
+ /* Set the DMA Input Capture 1 Callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream for Capture 1*/
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length);
+
+ /* Enable the capture compare 1 Interrupt */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Hall Sensor Interface in DMA mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
+
+ /* Disable the Input Capture channels 1
+ (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+
+
+ /* Disable the capture compare Interrupts 1 event */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIMEx_Group2 Timer Complementary Output Compare functions
+ * @brief Timer Complementary Output Compare functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Timer Complementary Output Compare functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Start the Complementary Output Compare/PWM.
+ (+) Stop the Complementary Output Compare/PWM.
+ (+) Start the Complementary Output Compare/PWM and enable interrupts.
+ (+) Stop the Complementary Output Compare/PWM and disable interrupts.
+ (+) Start the Complementary Output Compare/PWM and enable DMA transfers.
+ (+) Stop the Complementary Output Compare/PWM and disable DMA transfers.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Starts the TIM Output Compare signal generation on the complementary
+ * output.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ /* Enable the Capture compare channel N */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE);
+
+ /* Enable the Main Ouput */
+ __HAL_TIM_MOE_ENABLE(htim);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Output Compare signal generation on the complementary
+ * output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ /* Disable the Capture compare channel N */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE);
+
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Output Compare signal generation in interrupt mode
+ * on the complementary output.
+ * @param htim : TIM OC handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Enable the TIM Output Compare interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Enable the TIM Output Compare interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Enable the TIM Output Compare interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Enable the TIM Output Compare interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Enable the Capture compare channel N */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE);
+
+ /* Enable the Main Ouput */
+ __HAL_TIM_MOE_ENABLE(htim);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Output Compare signal generation in interrupt mode
+ * on the complementary output.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Output Compare interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Output Compare interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Output Compare interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Output Compare interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the Capture compare channel N */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE);
+
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM Output Compare signal generation in DMA mode
+ * on the complementary output.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @param pData: The source Buffer address.
+ * @param Length: The length of data to be transferred from memory to TIM peripheral
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if(((uint32_t)pData == 0 ) && (Length > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
+
+ /* Enable the TIM Output Compare DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
+
+ /* Enable the TIM Output Compare DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+{
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length);
+
+ /* Enable the TIM Output Compare DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length);
+
+ /* Enable the TIM Output Compare DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Enable the Capture compare channel N */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE);
+
+ /* Enable the Main Ouput */
+ __HAL_TIM_MOE_ENABLE(htim);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM Output Compare signal generation in DMA mode
+ * on the complementary output.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Output Compare DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Output Compare DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Output Compare DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Output Compare interrupt */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the Capture compare channel N */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE);
+
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the htim state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIMEx_Group3 Timer Complementary PWM functions
+ * @brief Timer Complementary PWM functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Timer Complementary PWM functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Start the Complementary PWM.
+ (+) Stop the Complementary PWM.
+ (+) Start the Complementary PWM and enable interrupts.
+ (+) Stop the Complementary PWM and disable interrupts.
+ (+) Start the Complementary PWM and enable DMA transfers.
+ (+) Stop the Complementary PWM and disable DMA transfers.
+ (+) Start the Complementary Input Capture measurement.
+ (+) Stop the Complementary Input Capture.
+ (+) Start the Complementary Input Capture and enable interrupts.
+ (+) Stop the Complementary Input Capture and disable interrupts.
+ (+) Start the Complementary Input Capture and enable DMA transfers.
+ (+) Stop the Complementary Input Capture and disable DMA transfers.
+ (+) Start the Complementary One Pulse generation.
+ (+) Stop the Complementary One Pulse.
+ (+) Start the Complementary One Pulse and enable interrupts.
+ (+) Stop the Complementary One Pulse and disable interrupts.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Starts the PWM signal generation on the complementary output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ /* Enable the complementary PWM output */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE);
+
+ /* Enable the Main Ouput */
+ __HAL_TIM_MOE_ENABLE(htim);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the PWM signal generation on the complementary output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ /* Disable the complementary PWM output */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE);
+
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the PWM signal generation in interrupt mode on the
+ * complementary output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Enable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Enable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Enable the TIM Break interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_BREAK);
+
+ /* Enable the complementary PWM output */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE);
+
+ /* Enable the Main Ouput */
+ __HAL_TIM_MOE_ENABLE(htim);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the PWM signal generation in interrupt mode on the
+ * complementary output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT (TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the TIM Break interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK);
+
+ /* Disable the complementary PWM output */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE);
+
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM PWM signal generation in DMA mode on the
+ * complementary output
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @param pData: The source Buffer address.
+ * @param Length: The length of data to be transferred from memory to TIM peripheral
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ if((htim->State == HAL_TIM_STATE_BUSY))
+ {
+ return HAL_BUSY;
+ }
+ else if((htim->State == HAL_TIM_STATE_READY))
+ {
+ if(((uint32_t)pData == 0 ) && (Length > 0))
+ {
+ return HAL_ERROR;
+ }
+ else
+ {
+ htim->State = HAL_TIM_STATE_BUSY;
+ }
+ }
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
+
+ /* Enable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
+
+ /* Enable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length);
+
+ /* Enable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ;
+
+ /* Enable the DMA Stream */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length);
+
+ /* Enable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Enable the complementary PWM output */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE);
+
+ /* Enable the Main Ouput */
+ __HAL_TIM_MOE_ENABLE(htim);
+
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM PWM signal generation in DMA mode on the complementary
+ * output
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
+
+ switch (Channel)
+ {
+ case TIM_CHANNEL_1:
+ {
+ /* Disable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ }
+ break;
+
+ case TIM_CHANNEL_2:
+ {
+ /* Disable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ }
+ break;
+
+ case TIM_CHANNEL_3:
+ {
+ /* Disable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ }
+ break;
+
+ case TIM_CHANNEL_4:
+ {
+ /* Disable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Disable the complementary PWM output */
+ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE);
+
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Change the htim state */
+ htim->State = HAL_TIM_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIMEx_Group4 Timer Complementary One Pulse functions
+ * @brief Timer Complementary One Pulse functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Timer Complementary One Pulse functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Start the Complementary One Pulse generation.
+ (+) Stop the Complementary One Pulse.
+ (+) Start the Complementary One Pulse and enable interrupts.
+ (+) Stop the Complementary One Pulse and disable interrupts.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Starts the TIM One Pulse signal generation on the complemetary
+ * output.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
+ {
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
+
+ /* Enable the complementary One Pulse output */
+ TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE);
+
+ /* Enable the Main Ouput */
+ __HAL_TIM_MOE_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the TIM One Pulse signal generation on the complementary
+ * output.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
+{
+
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
+
+ /* Disable the complementary One Pulse output */
+ TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE);
+
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the TIM One Pulse signal generation in interrupt mode on the
+ * complementary channel.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
+
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+
+ /* Enable the complementary One Pulse output */
+ TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE);
+
+ /* Enable the Main Ouput */
+ __HAL_TIM_MOE_ENABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+ }
+
+/**
+ * @brief Stops the TIM One Pulse signal generation in interrupt mode on the
+ * complementary channel.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
+
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+
+ /* Disable the complementary One Pulse output */
+ TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE);
+
+ /* Disable the Main Ouput */
+ __HAL_TIM_MOE_DISABLE(htim);
+
+ /* Disable the Peripheral */
+ __HAL_TIM_DISABLE(htim);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+/** @defgroup TIMEx_Group5 Peripheral Control functions
+ * @brief Peripheral Control functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral Control functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Configure The Input Output channels for OC, PWM, IC or One Pulse mode.
+ (+) Configure External Clock source.
+ (+) Configure Complementary channels, break features and dead time.
+ (+) Configure Master and the Slave synchronization.
+ (+) Configure the commutation event in case of use of the Hall sensor interface.
+ (+) Configure the DMA Burst Mode.
+
+@endverbatim
+ * @{
+ */
+/**
+ * @brief Configure the TIM commutation event sequence.
+ * @note: this function is mandatory to use the commutation event in order to
+ * update the configuration at each commutation detection on the TRGI input of the Timer,
+ * the typical use of this feature is with the use of another Timer(interface Timer)
+ * configured in Hall sensor interface, this interface Timer will generate the
+ * commutation at its TRGO output (connected to Timer used in this function) each time
+ * the TI1 of the Interface Timer detect a commutation at its input TI1.
+ * @param htim: TIM handle
+ * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
+ * This parameter can be one of the following values:
+ * @arg TIM_TS_ITR0: Internal trigger 0 selected
+ * @arg TIM_TS_ITR1: Internal trigger 1 selected
+ * @arg TIM_TS_ITR2: Internal trigger 2 selected
+ * @arg TIM_TS_ITR3: Internal trigger 3 selected
+ * @arg TIM_TS_NONE: No trigger is needed
+ * @param CommutationSource : the Commutation Event source
+ * This parameter can be one of the following values:
+ * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
+ * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_ADVANCED_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger));
+
+ __HAL_LOCK(htim);
+
+ if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
+ (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3))
+ {
+ /* Select the Input trigger */
+ htim->Instance->SMCR &= ~TIM_SMCR_TS;
+ htim->Instance->SMCR |= InputTrigger;
+ }
+
+ /* Select the Capture Compare preload feature */
+ htim->Instance->CR2 |= TIM_CR2_CCPC;
+ /* Select the Commutation event source */
+ htim->Instance->CR2 &= ~TIM_CR2_CCUS;
+ htim->Instance->CR2 |= CommutationSource;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configure the TIM commutation event sequence with interrupt.
+ * @note: this function is mandatory to use the commutation event in order to
+ * update the configuration at each commutation detection on the TRGI input of the Timer,
+ * the typical use of this feature is with the use of another Timer(interface Timer)
+ * configured in Hall sensor interface, this interface Timer will generate the
+ * commutation at its TRGO output (connected to Timer used in this function) each time
+ * the TI1 of the Interface Timer detect a commutation at its input TI1.
+ * @param htim: TIM handle
+ * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
+ * This parameter can be one of the following values:
+ * @arg TIM_TS_ITR0: Internal trigger 0 selected
+ * @arg TIM_TS_ITR1: Internal trigger 1 selected
+ * @arg TIM_TS_ITR2: Internal trigger 2 selected
+ * @arg TIM_TS_ITR3: Internal trigger 3 selected
+ * @arg TIM_TS_NONE: No trigger is needed
+ * @param CommutationSource : the Commutation Event source
+ * This parameter can be one of the following values:
+ * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
+ * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_ADVANCED_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger));
+
+ __HAL_LOCK(htim);
+
+ if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
+ (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3))
+ {
+ /* Select the Input trigger */
+ htim->Instance->SMCR &= ~TIM_SMCR_TS;
+ htim->Instance->SMCR |= InputTrigger;
+ }
+
+ /* Select the Capture Compare preload feature */
+ htim->Instance->CR2 |= TIM_CR2_CCPC;
+ /* Select the Commutation event source */
+ htim->Instance->CR2 &= ~TIM_CR2_CCUS;
+ htim->Instance->CR2 |= CommutationSource;
+
+ /* Enable the Commutation Interrupt Request */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_COM);
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configure the TIM commutation event sequence with DMA.
+ * @note: this function is mandatory to use the commutation event in order to
+ * update the configuration at each commutation detection on the TRGI input of the Timer,
+ * the typical use of this feature is with the use of another Timer(interface Timer)
+ * configured in Hall sensor interface, this interface Timer will generate the
+ * commutation at its TRGO output (connected to Timer used in this function) each time
+ * the TI1 of the Interface Timer detect a commutation at its input TI1.
+ * @note: The user should configure the DMA in his own software, in This function only the COMDE bit is set
+ * @param htim: TIM handle
+ * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
+ * This parameter can be one of the following values:
+ * @arg TIM_TS_ITR0: Internal trigger 0 selected
+ * @arg TIM_TS_ITR1: Internal trigger 1 selected
+ * @arg TIM_TS_ITR2: Internal trigger 2 selected
+ * @arg TIM_TS_ITR3: Internal trigger 3 selected
+ * @arg TIM_TS_NONE: No trigger is needed
+ * @param CommutationSource : the Commutation Event source
+ * This parameter can be one of the following values:
+ * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
+ * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_ADVANCED_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger));
+
+ __HAL_LOCK(htim);
+
+ if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
+ (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3))
+ {
+ /* Select the Input trigger */
+ htim->Instance->SMCR &= ~TIM_SMCR_TS;
+ htim->Instance->SMCR |= InputTrigger;
+ }
+
+ /* Select the Capture Compare preload feature */
+ htim->Instance->CR2 |= TIM_CR2_CCPC;
+ /* Select the Commutation event source */
+ htim->Instance->CR2 &= ~TIM_CR2_CCUS;
+ htim->Instance->CR2 |= CommutationSource;
+
+ /* Enable the Commutation DMA Request */
+ /* Set the DMA Commutation Callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = HAL_TIMEx_DMACommutationCplt;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = HAL_TIM_DMAError;
+
+ /* Enable the Commutation DMA Request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_COM);
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the TIM in master mode.
+ * @param htim: TIM handle.
+ * @param sMasterConfig: pointer to a TIM_MasterConfigTypeDef structure that
+ * contains the selected trigger output (TRGO) and the Master/Slave
+ * mode.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef * sMasterConfig)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_MASTER_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TRGO_SOURCE(sMasterConfig->MasterOutputTrigger));
+ assert_param(IS_TIM_MSM_STATE(sMasterConfig->MasterSlaveMode));
+
+ __HAL_LOCK(htim);
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Reset the MMS Bits */
+ htim->Instance->CR2 &= ~TIM_CR2_MMS;
+ /* Select the TRGO source */
+ htim->Instance->CR2 |= sMasterConfig->MasterOutputTrigger;
+
+ /* Reset the MSM Bit */
+ htim->Instance->SMCR &= ~TIM_SMCR_MSM;
+ /* Set or Reset the MSM Bit */
+ htim->Instance->SMCR |= sMasterConfig->MasterSlaveMode;
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the Break feature, dead time, Lock level, OSSI/OSSR State
+ * and the AOE(automatic output enable).
+ * @param htim: TIM handle
+ * @param sBreakDeadTimeConfig: pointer to a TIM_ConfigBreakDeadConfig_TypeDef structure that
+ * contains the BDTR Register configuration information for the TIM peripheral.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim,
+ TIM_BreakDeadTimeConfigTypeDef * sBreakDeadTimeConfig)
+{
+ /* Check the parameters */
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_OSSR_STATE(sBreakDeadTimeConfig->OffStateRunMode));
+ assert_param(IS_TIM_OSSI_STATE(sBreakDeadTimeConfig->OffStateIDLEMode));
+ assert_param(IS_TIM_LOCK_LEVEL(sBreakDeadTimeConfig->LockLevel));
+ assert_param(IS_TIM_BREAK_STATE(sBreakDeadTimeConfig->BreakState));
+ assert_param(IS_TIM_BREAK_POLARITY(sBreakDeadTimeConfig->BreakPolarity));
+ assert_param(IS_TIM_AUTOMATIC_OUTPUT_STATE(sBreakDeadTimeConfig->AutomaticOutput));
+
+ /* Process Locked */
+ __HAL_LOCK(htim);
+
+ htim->State = HAL_TIM_STATE_BUSY;
+
+ /* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State,
+ the OSSI State, the dead time value and the Automatic Output Enable Bit */
+ htim->Instance->BDTR = (uint32_t)sBreakDeadTimeConfig->OffStateRunMode |
+ sBreakDeadTimeConfig->OffStateIDLEMode |
+ sBreakDeadTimeConfig->LockLevel |
+ sBreakDeadTimeConfig->DeadTime |
+ sBreakDeadTimeConfig->BreakState |
+ sBreakDeadTimeConfig->BreakPolarity |
+ sBreakDeadTimeConfig->AutomaticOutput;
+
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Configures the TIM2, TIM5 and TIM11 Remapping input capabilities.
+ * @param htim: TIM handle.
+ * @param TIM_Remap: specifies the TIM input remapping source.
+ * This parameter can be one of the following values:
+ * @arg TIM_TIM2_TIM8_TRGO: TIM2 ITR1 input is connected to TIM8 Trigger output(default)
+ * @arg TIM_TIM2_ETH_PTP: TIM2 ITR1 input is connected to ETH PTP trogger output.
+ * @arg TIM_TIM2_USBFS_SOF: TIM2 ITR1 input is connected to USB FS SOF.
+ * @arg TIM_TIM2_USBHS_SOF: TIM2 ITR1 input is connected to USB HS SOF.
+ * @arg TIM_TIM5_GPIO: TIM5 CH4 input is connected to dedicated Timer pin(default)
+ * @arg TIM_TIM5_LSI: TIM5 CH4 input is connected to LSI clock.
+ * @arg TIM_TIM5_LSE: TIM5 CH4 input is connected to LSE clock.
+ * @arg TIM_TIM5_RTC: TIM5 CH4 input is connected to RTC Output event.
+ * @arg TIM_TIM11_GPIO: TIM11 CH4 input is connected to dedicated Timer pin(default)
+ * @arg TIM_TIM11_HSE: TIM11 CH4 input is connected to HSE_RTC clock
+ * (HSE divided by a programmable prescaler)
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap)
+{
+ __HAL_LOCK(htim);
+
+ /* Check parameters */
+ assert_param(IS_TIM_REMAP_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_REMAP(Remap));
+
+ /* Set the Timer remapping configuration */
+ htim->Instance->OR = Remap;
+
+ htim->State = HAL_TIM_STATE_READY;
+
+ __HAL_UNLOCK(htim);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIMEx_Group6 Extension Callbacks functions
+ * @brief Extension Callbacks functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Extension Callbacks functions #####
+ ==============================================================================
+ [..]
+ This section provides Extension TIM callback functions:
+ (+) Timer Commutation callback
+ (+) Timer Break callback
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Hall commutation changed callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIMEx_CommutationCallback(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIMEx_CommutationCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Hall Break detection callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim)
+{
+ /* NOTE : This function Should not be modified, when the callback is needed,
+ the HAL_TIMEx_BreakCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup TIMEx_Group7 Extension Peripheral State functions
+ * @brief Extension Peripheral State functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Extension Peripheral State functions #####
+ ==============================================================================
+ [..]
+ This subsection permit to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Return the TIM Hall Sensor interface state
+ * @param htim: TIM Hall Sensor handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef *htim)
+{
+ return htim->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief TIM DMA Commutation callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+void HAL_TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma)
+{
+ TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ htim->State= HAL_TIM_STATE_READY;
+
+ HAL_TIMEx_CommutationCallback(htim);
+}
+
+/**
+ * @brief Enables or disables the TIM Capture Compare Channel xN.
+ * @param TIMx to select the TIM peripheral
+ * @param Channel: specifies the TIM Channel
+ * This parameter can be one of the following values:
+ * @arg TIM_Channel_1: TIM Channel 1
+ * @arg TIM_Channel_2: TIM Channel 2
+ * @arg TIM_Channel_3: TIM Channel 3
+ * @param ChannelNState: specifies the TIM Channel CCxNE bit new state.
+ * This parameter can be: TIM_CCxN_ENABLE or TIM_CCxN_Disable.
+ * @retval None
+ */
+static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelNState)
+{
+ uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_TIM_CC4_INSTANCE(TIMx));
+ assert_param(IS_TIM_COMPLEMENTARY_CHANNELS(Channel));
+
+ tmp = TIM_CCER_CC1NE << Channel;
+
+ /* Reset the CCxNE Bit */
+ TIMx->CCER &= ~tmp;
+
+ /* Set or reset the CCxNE Bit */
+ TIMx->CCER |= (uint32_t)(ChannelNState << Channel);
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_TIM_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_uart.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_uart.c
new file mode 100644
index 0000000..9c6f49e
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_uart.c
@@ -0,0 +1,1885 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_uart.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief UART HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Universal Asynchronous Receiver Transmitter (UART) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ * + Peripheral State and Errors functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The UART HAL driver can be used as follows:
+
+ (#) Declare a UART_HandleTypeDef handle structure.
+
+ (#) Initialize the UART low level resources by implement the HAL_UART_MspInit() API:
+ (##) Enable the USARTx interface clock.
+ (##) UART pins configuration:
+ (+++) Enable the clock for the UART GPIOs.
+ (+++) Configure these UART pins as alternate function pull-up.
+ (##) NVIC configuration if you need to use interrupt process (HAL_UART_Transmit_IT()
+ and HAL_UART_Receive_IT() APIs):
+ (+++) Configure the USARTx interrupt priority.
+ (+++) Enable the NVIC USART IRQ handle.
+ (##) DMA Configuration if you need to use DMA process (HAL_UART_Transmit_DMA()
+ and HAL_UART_Receive_DMA() APIs):
+ (+++) Declare a DMA handle structure for the Tx/Rx stream.
+ (+++) Enable the DMAx interface clock.
+ (+++) Configure the declared DMA handle structure with the required
+ Tx/Rx parameters.
+ (+++) Configure the DMA Tx/Rx Stream.
+ (+++) Associate the initialized DMA handle to the UART DMA Tx/Rx handle.
+ (+++) Configure the priority and enable the NVIC for the transfer complete
+ interrupt on the DMA Tx/Rx Stream.
+
+ (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware
+ flow control and Mode(Receiver/Transmitter) in the huart Init structure.
+
+ (#) For the UART asynchronous mode, initialize the UART registers by calling
+ the HAL_UART_Init() API.
+
+ (#) For the UART Half duplex mode, initialize the UART registers by calling
+ the HAL_HalfDuplex_Init() API.
+
+ (#) For the LIN mode, initialize the UART registers by calling the HAL_LIN_Init() API.
+
+ (#) For the Multi-Processor mode, initialize the UART registers by calling
+ the HAL_MultiProcessor_Init() API.
+
+ -@- The specific UART interrupts (Transmission complete interrupt,
+ RXNE interrupt and Error Interrupts) will be managed using the macros
+ __HAL_UART_ENABLE_IT() and __HAL_UART_DISABLE_IT() inside the transmit
+ and receive process.
+
+ -@- These API's(HAL_UART_Init() and HAL_HalfDuplex_Init()) configures also the
+ low level Hardware GPIO, CLOCK, CORTEX...etc) by calling the customed
+ HAL_UART_MspInit() API.
+
+ (#) Three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Send an amount of data in blocking mode using HAL_UART_Transmit()
+ (+) Receive an amount of data in blocking mode using HAL_UART_Receive()
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Send an amount of data in non blocking mode using HAL_UART_Transmit_IT()
+ (+) At transmission end of half transfer HAL_UART_TxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_UART_TxHalfCpltCallback
+ (+) At transmission end of transfer HAL_UART_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_UART_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode using HAL_UART_Receive_IT()
+ (+) At reception end of half transfer HAL_UART_RxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_UART_RxHalfCpltCallback
+ (+) At reception end of transfer HAL_UART_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_UART_RxCpltCallback
+ (+) In case of transfer Error, HAL_UART_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_UART_ErrorCallback
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Send an amount of data in non blocking mode (DMA) using HAL_UART_Transmit_DMA()
+ (+) At transmission end of half transfer HAL_UART_TxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_UART_TxHalfCpltCallback
+ (+) At transmission end of transfer HAL_UART_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_UART_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode (DMA) using HAL_UART_Receive_DMA()
+ (+) At reception end of half transfer HAL_UART_RxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_UART_RxHalfCpltCallback
+ (+) At reception end of transfer HAL_UART_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_UART_RxCpltCallback
+ (+) In case of transfer Error, HAL_UART_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_UART_ErrorCallback
+ (+) Pause the DMA Transfer using HAL_UART_DMAPause()
+ (+) Resume the DMA Transfer using HAL_UART_DMAResume()
+ (+) Stop the DMA Transfer using HAL_UART_DMAStop()
+
+ *** UART HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in UART HAL driver.
+
+ (+) __HAL_UART_ENABLE: Enable the UART peripheral
+ (+) __HAL_UART_DISABLE: Disable the UART peripheral
+ (+) __HAL_UART_GET_FLAG : Checks whether the specified UART flag is set or not
+ (+) __HAL_UART_CLEAR_FLAG : Clears the specified UART pending flag
+ (+) __HAL_UART_ENABLE_IT: Enables the specified UART interrupt
+ (+) __HAL_UART_DISABLE_IT: Disables the specified UART interrupt
+
+ [..]
+ (@) You can refer to the UART HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup UART
+ * @brief HAL UART module driver
+ * @{
+ */
+#ifdef HAL_UART_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define UART_TIMEOUT_VALUE 22000
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static void UART_SetConfig (UART_HandleTypeDef *huart);
+static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart);
+static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart);
+static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma);
+static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma);
+static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
+static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma);
+static void UART_DMAError(DMA_HandleTypeDef *hdma);
+static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
+
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup UART_Private_Functions
+ * @{
+ */
+
+/** @defgroup UART_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+===============================================================================
+ ##### Initialization and Configuration functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to initialize the USARTx or the UARTy
+ in asynchronous mode.
+ (+) For the asynchronous mode only these parameters can be configured:
+ (++) Baud Rate
+ (++) Word Length
+ (++) Stop Bit
+ (++) Parity: If the parity is enabled, then the MSB bit of the data written
+ in the data register is transmitted but is changed by the parity bit.
+ Depending on the frame length defined by the M bit (8-bits or 9-bits),
+ the possible UART frame formats are as listed in the following table:
+ +-------------------------------------------------------------+
+ | M bit | PCE bit | UART frame |
+ |---------------------|---------------------------------------|
+ | 0 | 0 | | SB | 8 bit data | STB | |
+ |---------|-----------|---------------------------------------|
+ | 0 | 1 | | SB | 7 bit data | PB | STB | |
+ |---------|-----------|---------------------------------------|
+ | 1 | 0 | | SB | 9 bit data | STB | |
+ |---------|-----------|---------------------------------------|
+ | 1 | 1 | | SB | 8 bit data | PB | STB | |
+ +-------------------------------------------------------------+
+ (++) Hardware flow control
+ (++) Receiver/transmitter modes
+ (++) Over Sampling Methode
+ [..]
+ The HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init() and HAL_MultiProcessor_Init() APIs
+ follow respectively the UART asynchronous, UART Half duplex, LIN and Multi-Processor
+ configuration procedures (details for the procedures are available in reference manual (RM0329)).
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the UART mode according to the specified parameters in
+ * the UART_InitTypeDef and create the associated handle.
+ * @param huart: UART handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart)
+{
+ /* Check the UART handle allocation */
+ if(huart == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ if(huart->Init.HwFlowCtl != UART_HWCONTROL_NONE)
+ {
+ /* Check the parameters */
+ assert_param(IS_UART_HWFLOW_INSTANCE(huart->Instance));
+ }
+ else
+ {
+ /* Check the parameters */
+ assert_param(IS_UART_INSTANCE(huart->Instance));
+ }
+
+ if(huart->State == HAL_UART_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_UART_MspInit(huart);
+ }
+
+ huart->State = HAL_UART_STATE_BUSY;
+
+ /* Disable the peripheral */
+ __HAL_UART_DISABLE(huart);
+
+ /* Set the UART Communication parameters */
+ UART_SetConfig(huart);
+
+ /* In asynchronous mode, the following bits must be kept cleared:
+ - LINEN and CLKEN bits in the USART_CR2 register,
+ - SCEN, HDSEL and IREN bits in the USART_CR3 register.*/
+ huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN);
+ huart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN);
+
+ /* Enable the peripheral */
+ __HAL_UART_ENABLE(huart);
+
+ /* Initialize the UART state */
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ huart->State= HAL_UART_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the half-duplex mode according to the specified
+ * parameters in the UART_InitTypeDef and create the associated handle.
+ * @param huart: UART handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart)
+{
+ /* Check the UART handle allocation */
+ if(huart == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ if(huart->State == HAL_UART_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_UART_MspInit(huart);
+ }
+
+ /* Disable the peripheral */
+ __HAL_UART_DISABLE(huart);
+
+ /* Set the UART Communication parameters */
+ UART_SetConfig(huart);
+
+ /* In half-duplex mode, the following bits must be kept cleared:
+ - LINEN and CLKEN bits in the USART_CR2 register,
+ - SCEN and IREN bits in the USART_CR3 register.*/
+ huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN);
+ huart->Instance->CR3 &= ~(USART_CR3_IREN | USART_CR3_SCEN);
+
+ /* Enable the Half-Duplex mode by setting the HDSEL bit in the CR3 register */
+ huart->Instance->CR3 |= USART_CR3_HDSEL;
+
+ /* Enable the peripheral */
+ __HAL_UART_ENABLE(huart);
+
+ /* Initialize the UART state*/
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ huart->State= HAL_UART_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the LIN mode according to the specified
+ * parameters in the UART_InitTypeDef and create the associated handle.
+ * @param huart: UART handle
+ * @param BreakDetectLength: Specifies the LIN break detection length.
+ * This parameter can be one of the following values:
+ * @arg UART_LINBREAKDETECTLENGTH_10B: 10-bit break detection
+ * @arg UART_LINBREAKDETECTLENGTH_11B: 11-bit break detection
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength)
+{
+ /* Check the UART handle allocation */
+ if(huart == NULL)
+ {
+ return HAL_ERROR;
+ }
+ /* Check the Break detection length parameter */
+ assert_param(IS_UART_LIN_BREAK_DETECT_LENGTH(BreakDetectLength));
+
+ if(huart->State == HAL_UART_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_UART_MspInit(huart);
+ }
+
+ /* Disable the peripheral */
+ __HAL_UART_DISABLE(huart);
+
+ /* Set the UART Communication parameters */
+ UART_SetConfig(huart);
+
+ /* In LIN mode, the following bits must be kept cleared:
+ - LINEN and CLKEN bits in the USART_CR2 register,
+ - SCEN and IREN bits in the USART_CR3 register.*/
+ huart->Instance->CR2 &= ~(USART_CR2_CLKEN);
+ huart->Instance->CR3 &= ~(USART_CR3_HDSEL | USART_CR3_IREN | USART_CR3_SCEN);
+
+ /* Enable the LIN mode by setting the LINEN bit in the CR2 register */
+ huart->Instance->CR2 |= USART_CR2_LINEN;
+
+ /* Set the USART LIN Break detection length. */
+ huart->Instance->CR2 &= ~(USART_CR2_LBDL);
+ huart->Instance->CR2 |= BreakDetectLength;
+
+ /* Enable the peripheral */
+ __HAL_UART_ENABLE(huart);
+
+ /* Initialize the UART state*/
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ huart->State= HAL_UART_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the Multi-Processor mode according to the specified
+ * parameters in the UART_InitTypeDef and create the associated handle.
+ * @param huart: UART handle
+ * @param Address: USART address
+ * @param WakeUpMethode: specifies the USART wakeup method.
+ * This parameter can be one of the following values:
+ * @arg UART_WAKEUPMETHODE_IDLELINE: Wakeup by an idle line detection
+ * @arg UART_WAKEUPMETHODE_ADDRESSMARK: Wakeup by an address mark
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethode)
+{
+ /* Check the UART handle allocation */
+ if(huart == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the Address & wake up method parameters */
+ assert_param(IS_UART_WAKEUPMETHODE(WakeUpMethode));
+ assert_param(IS_UART_ADDRESS(Address));
+
+ if(huart->State == HAL_UART_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_UART_MspInit(huart);
+ }
+
+ /* Disable the peripheral */
+ __HAL_UART_DISABLE(huart);
+
+ /* Set the UART Communication parameters */
+ UART_SetConfig(huart);
+
+ /* In Multi-Processor mode, the following bits must be kept cleared:
+ - LINEN and CLKEN bits in the USART_CR2 register,
+ - SCEN, HDSEL and IREN bits in the USART_CR3 register */
+ huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN);
+ huart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN);
+
+ /* Clear the USART address */
+ huart->Instance->CR2 &= ~(USART_CR2_ADD);
+ /* Set the USART address node */
+ huart->Instance->CR2 |= Address;
+
+ /* Set the wake up methode by setting the WAKE bit in the CR1 register */
+ huart->Instance->CR1 &= ~(USART_CR1_WAKE);
+ huart->Instance->CR1 |= WakeUpMethode;
+
+ /* Enable the peripheral */
+ __HAL_UART_ENABLE(huart);
+
+ /* Initialize the UART state */
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ huart->State= HAL_UART_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the UART peripheral.
+ * @param huart: UART handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_UART_DeInit(UART_HandleTypeDef *huart)
+{
+ /* Check the UART handle allocation */
+ if(huart == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_UART_INSTANCE(huart->Instance));
+
+ huart->State = HAL_UART_STATE_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_UART_MspDeInit(huart);
+
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ huart->State = HAL_UART_STATE_RESET;
+
+ /* Process Lock */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief UART MSP Init.
+ * @param huart: UART handle
+ * @retval None
+ */
+ __weak void HAL_UART_MspInit(UART_HandleTypeDef *huart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_UART_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief UART MSP DeInit.
+ * @param huart: UART handle
+ * @retval None
+ */
+ __weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_UART_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup UART_Group2 IO operation functions
+ * @brief UART Transmit and Receive functions
+ *
+@verbatim
+ ==============================================================================
+ ##### IO operation functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the UART asynchronous
+ and Half duplex data transfers.
+
+ (#) There are two modes of transfer:
+ (++) Blocking mode: The communication is performed in polling mode.
+ The HAL status of all data processing is returned by the same function
+ after finishing transfer.
+ (++) Non-Blocking mode: The communication is performed using Interrupts
+ or DMA, these APIs return the HAL status.
+ The end of the data processing will be indicated through the
+ dedicated UART IRQ when using Interrupt mode or the DMA IRQ when
+ using DMA mode.
+ The HAL_UART_TxCpltCallback(), HAL_UART_RxCpltCallback() user callbacks
+ will be executed respectivelly at the end of the transmit or receive process.
+ The HAL_UART_ErrorCallback() user callback will be executed when
+ a communication error is detected.
+
+ (#) Blocking mode API's are:
+ (++) HAL_UART_Transmit()
+ (++) HAL_UART_Receive()
+
+ (#) Non-Blocking mode API's with Interrupt are:
+ (++) HAL_UART_Transmit_IT()
+ (++) HAL_UART_Receive_IT()
+ (++) HAL_UART_IRQHandler()
+
+ (#) No-Blocking mode functions with DMA are:
+ (++) HAL_UART_Transmit_DMA()
+ (++) HAL_UART_Receive_DMA()
+
+ (#) A set of Transfer Complete Callbacks are provided in Non-Blocking mode:
+ (++) HAL_UART_TxCpltCallback()
+ (++) HAL_UART_RxCpltCallback()
+ (++) HAL_UART_ErrorCallback()
+
+ [..]
+ (@) In the Half duplex communication, it is forbidden to run the transmit
+ and receive process in parallel, the UART state HAL_UART_STATE_BUSY_TX_RX
+ can't be useful.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Sends an amount of data in blocking mode.
+ * @param huart: UART handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ uint16_t* tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = huart->State;
+ if((tmp1 == HAL_UART_STATE_READY) || (tmp1 == HAL_UART_STATE_BUSY_RX))
+ {
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ /* Check if a non-blocking receive process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_RX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX;
+ }
+
+ huart->TxXferSize = Size;
+ huart->TxXferCount = Size;
+ while(huart->TxXferCount > 0)
+ {
+ huart->TxXferCount--;
+ if(huart->Init.WordLength == UART_WORDLENGTH_9B)
+ {
+ if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pData;
+ huart->Instance->DR = (*tmp & (uint16_t)0x01FF);
+ if(huart->Init.Parity == UART_PARITY_NONE)
+ {
+ pData +=2;
+ }
+ else
+ {
+ pData +=1;
+ }
+ }
+ else
+ {
+ if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ huart->Instance->DR = (*pData++ & (uint8_t)0xFF);
+ }
+ }
+
+ if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Check if a non-blocking receive process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_RX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_READY;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receives an amount of data in blocking mode.
+ * @param huart: UART handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
+{
+ uint16_t* tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = huart->State;
+ if((tmp1 == HAL_UART_STATE_READY) || (tmp1 == HAL_UART_STATE_BUSY_TX))
+ {
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ /* Check if a non-blocking transmit process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_TX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_BUSY_RX;
+ }
+
+ huart->RxXferSize = Size;
+ huart->RxXferCount = Size;
+
+ /* Check the remain data to be received */
+ while(huart->RxXferCount > 0)
+ {
+ huart->RxXferCount--;
+ if(huart->Init.WordLength == UART_WORDLENGTH_9B)
+ {
+ if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pData ;
+ if(huart->Init.Parity == UART_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x01FF);
+ pData +=2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x00FF);
+ pData +=1;
+ }
+
+ }
+ else
+ {
+ if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ if(huart->Init.Parity == UART_PARITY_NONE)
+ {
+ *pData++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ *pData++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x007F);
+ }
+
+ }
+ }
+
+ /* Check if a non-blocking transmit process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_READY;
+ }
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Sends an amount of data in non blocking mode.
+ * @param huart: UART handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
+{
+ uint32_t tmp = 0;
+
+ tmp = huart->State;
+ if((tmp == HAL_UART_STATE_READY) || (tmp == HAL_UART_STATE_BUSY_RX))
+ {
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->pTxBuffPtr = pData;
+ huart->TxXferSize = Size;
+ huart->TxXferCount = Size;
+
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ /* Check if a receive process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_RX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX;
+ }
+
+ /* Enable the UART Parity Error Interrupt */
+ __HAL_UART_ENABLE_IT(huart, UART_IT_PE);
+
+ /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */
+ __HAL_UART_ENABLE_IT(huart, UART_IT_ERR);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ /* Enable the UART Transmit Complete Interrupt */
+ __HAL_UART_ENABLE_IT(huart, UART_IT_TC);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receives an amount of data in non blocking mode
+ * @param huart: UART handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
+{
+ uint32_t tmp = 0;
+
+ tmp = huart->State;
+ if((tmp == HAL_UART_STATE_READY) || (tmp == HAL_UART_STATE_BUSY_TX))
+ {
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->pRxBuffPtr = pData;
+ huart->RxXferSize = Size;
+ huart->RxXferCount = Size;
+
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ /* Check if a transmit process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_TX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_BUSY_RX;
+ }
+
+ /* Enable the UART Parity Error Interrupt */
+ __HAL_UART_ENABLE_IT(huart, UART_IT_PE);
+
+ /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */
+ __HAL_UART_ENABLE_IT(huart, UART_IT_ERR);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ /* Enable the UART Data Register not empty Interrupt */
+ __HAL_UART_ENABLE_IT(huart, UART_IT_RXNE);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Sends an amount of data in non blocking mode.
+ * @param huart: UART handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = huart->State;
+ if((tmp1 == HAL_UART_STATE_READY) || (tmp1 == HAL_UART_STATE_BUSY_RX))
+ {
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->pTxBuffPtr = pData;
+ huart->TxXferSize = Size;
+ huart->TxXferCount = Size;
+
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ /* Check if a receive process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_RX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX;
+ }
+
+ /* Set the UART DMA transfer complete callback */
+ huart->hdmatx->XferCpltCallback = UART_DMATransmitCplt;
+
+ /* Set the UART DMA Half transfer complete callback */
+ huart->hdmatx->XferHalfCpltCallback = UART_DMATxHalfCplt;
+
+ /* Set the DMA error callback */
+ huart->hdmatx->XferErrorCallback = UART_DMAError;
+
+ /* Enable the UART transmit DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(huart->hdmatx, *(uint32_t*)tmp, (uint32_t)&huart->Instance->DR, Size);
+
+ /* Enable the DMA transfer for transmit request by setting the DMAT bit
+ in the UART CR3 register */
+ huart->Instance->CR3 |= USART_CR3_DMAT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Receives an amount of data in non blocking mode.
+ * @param huart: UART handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @note When the UART parity is enabled (PCE = 1) the data received contain the parity bit.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
+{
+ uint32_t *tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = huart->State;
+ if((tmp1 == HAL_UART_STATE_READY) || (tmp1 == HAL_UART_STATE_BUSY_TX))
+ {
+ if((pData == NULL ) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->pRxBuffPtr = pData;
+ huart->RxXferSize = Size;
+
+ huart->ErrorCode = HAL_UART_ERROR_NONE;
+ /* Check if a transmit rocess is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_TX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX_RX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_BUSY_RX;
+ }
+
+ /* Set the UART DMA transfer complete callback */
+ huart->hdmarx->XferCpltCallback = UART_DMAReceiveCplt;
+
+ /* Set the UART DMA Half transfer complete callback */
+ huart->hdmarx->XferHalfCpltCallback = UART_DMARxHalfCplt;
+
+ /* Set the DMA error callback */
+ huart->hdmarx->XferErrorCallback = UART_DMAError;
+
+ /* Enable the DMA Stream */
+ tmp = (uint32_t*)&pData;
+ HAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->DR, *(uint32_t*)tmp, Size);
+
+ /* Enable the DMA transfer for the receiver request by setting the DMAR bit
+ in the UART CR3 register */
+ huart->Instance->CR3 |= USART_CR3_DMAR;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Pauses the DMA Transfer.
+ * @param huart: UART handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart)
+{
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ if(huart->State == HAL_UART_STATE_BUSY_TX)
+ {
+ /* Disable the UART DMA Tx request */
+ huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT);
+ }
+ else if(huart->State == HAL_UART_STATE_BUSY_RX)
+ {
+ /* Disable the UART DMA Rx request */
+ huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR);
+ }
+ else if (huart->State == HAL_UART_STATE_BUSY_TX_RX)
+ {
+ /* Disable the UART DMA Tx & Rx requests */
+ huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT);
+ huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Resumes the DMA Transfer.
+ * @param huart: UART handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart)
+{
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ if(huart->State == HAL_UART_STATE_BUSY_TX)
+ {
+ /* Enable the UART DMA Tx request */
+ huart->Instance->CR3 |= USART_CR3_DMAT;
+ }
+ else if(huart->State == HAL_UART_STATE_BUSY_RX)
+ {
+ /* Enable the UART DMA Rx request */
+ huart->Instance->CR3 |= USART_CR3_DMAR;
+ }
+ else if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
+ {
+ /* Enable the UART DMA Tx & Rx request */
+ huart->Instance->CR3 |= USART_CR3_DMAT;
+ huart->Instance->CR3 |= USART_CR3_DMAR;
+ }
+
+ /* If the UART peripheral is still not enabled, enable it */
+ if ((huart->Instance->CR1 & USART_CR1_UE) == 0)
+ {
+ /* Enable UART peripheral */
+ __HAL_UART_ENABLE(huart);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the DMA Transfer.
+ * @param huart: UART handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart)
+{
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ /* Disable the UART Tx/Rx DMA requests */
+ huart->Instance->CR3 &= ~USART_CR3_DMAT;
+ huart->Instance->CR3 &= ~USART_CR3_DMAR;
+
+ /* Abort the UART DMA tx Stream */
+ if(huart->hdmatx != NULL)
+ {
+ HAL_DMA_Abort(huart->hdmatx);
+ }
+ /* Abort the UART DMA rx Stream */
+ if(huart->hdmarx != NULL)
+ {
+ HAL_DMA_Abort(huart->hdmarx);
+ }
+ /* Disable UART peripheral */
+ __HAL_UART_DISABLE(huart);
+
+ huart->State = HAL_UART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles UART interrupt request.
+ * @param huart: UART handle
+ * @retval None
+ */
+void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_PE);
+ tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_PE);
+ /* UART parity error interrupt occurred ------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_PE);
+
+ huart->ErrorCode |= HAL_UART_ERROR_PE;
+ }
+
+ tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_FE);
+ tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR);
+ /* UART frame error interrupt occurred -------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_FE);
+
+ huart->ErrorCode |= HAL_UART_ERROR_FE;
+ }
+
+ tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_NE);
+ tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR);
+ /* UART noise error interrupt occurred -------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_NE);
+
+ huart->ErrorCode |= HAL_UART_ERROR_NE;
+ }
+
+ tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_ORE);
+ tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR);
+ /* UART Over-Run interrupt occurred ----------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_ORE);
+
+ huart->ErrorCode |= HAL_UART_ERROR_ORE;
+ }
+
+ tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_RXNE);
+ tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_RXNE);
+ /* UART in mode Receiver ---------------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ UART_Receive_IT(huart);
+ __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_RXNE);
+ }
+
+ tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_TC);
+ tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_TC);
+ /* UART in mode Transmitter ------------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ UART_Transmit_IT(huart);
+ __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_TC);
+ }
+
+ if(huart->ErrorCode != HAL_UART_ERROR_NONE)
+ {
+ /* Set the UART state ready to be able to start again the process */
+ huart->State = HAL_UART_STATE_READY;
+
+ HAL_UART_ErrorCallback(huart);
+ }
+}
+
+/**
+ * @brief Tx Transfer completed callbacks.
+ * @param huart: UART handle
+ * @retval None
+ */
+ __weak void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_UART_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Tx Half Transfer completed callbacks.
+ * @param huart: UART handle
+ * @retval None
+ */
+ __weak void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_UART_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer completed callbacks.
+ * @param huart: UART handle
+ * @retval None
+ */
+__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_UART_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Rx Half Transfer completed callbacks.
+ * @param huart: UART handle
+ * @retval None
+ */
+__weak void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_UART_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief UART error callbacks.
+ * @param huart: UART handle
+ * @retval None
+ */
+ __weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_UART_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup UART_Group3 Peripheral Control functions
+ * @brief UART control functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the UART:
+ (+) HAL_LIN_SendBreak() API can be helpful to transmit the break character.
+ (+) HAL_MultiProcessor_EnterMuteMode() API can be helpful to enter the UART in mute mode.
+ (+) HAL_MultiProcessor_ExitMuteMode() API can be helpful to exit the UART mute mode by software.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Transmits break characters.
+ * @param huart: UART handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart)
+{
+ /* Check the parameters */
+ assert_param(IS_UART_INSTANCE(huart->Instance));
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->State = HAL_UART_STATE_BUSY;
+
+ /* Send break characters */
+ huart->Instance->CR1 |= USART_CR1_SBK;
+
+ huart->State = HAL_UART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enters the UART in mute mode.
+ * @param huart: UART handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart)
+{
+ /* Check the parameters */
+ assert_param(IS_UART_INSTANCE(huart->Instance));
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->State = HAL_UART_STATE_BUSY;
+
+ /* Enable the USART mute mode by setting the RWU bit in the CR1 register */
+ huart->Instance->CR1 |= USART_CR1_RWU;
+
+ huart->State = HAL_UART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Exits the UART mute mode: wake up software.
+ * @param huart: UART handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart)
+{
+ /* Check the parameters */
+ assert_param(IS_UART_INSTANCE(huart->Instance));
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->State = HAL_UART_STATE_BUSY;
+
+ /* Disable the USART mute mode by clearing the RWU bit in the CR1 register */
+ huart->Instance->CR1 &= (uint32_t)~((uint32_t)USART_CR1_RWU);
+
+ huart->State = HAL_UART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enables the UART transmitter and disables the UART receiver.
+ * @param huart: UART handle
+ * @retval HAL status
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart)
+{
+ uint32_t tmpreg = 0x00;
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->State = HAL_UART_STATE_BUSY;
+
+ /*-------------------------- USART CR1 Configuration -----------------------*/
+ tmpreg = huart->Instance->CR1;
+
+ /* Clear TE and RE bits */
+ tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE));
+
+ /* Enable the USART's transmit interface by setting the TE bit in the USART CR1 register */
+ tmpreg |= (uint32_t)USART_CR1_TE;
+
+ /* Write to USART CR1 */
+ huart->Instance->CR1 = (uint32_t)tmpreg;
+
+ huart->State = HAL_UART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Enables the UART receiver and disables the UART transmitter.
+ * @param huart: UART handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart)
+{
+ uint32_t tmpreg = 0x00;
+
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ huart->State = HAL_UART_STATE_BUSY;
+
+ /*-------------------------- USART CR1 Configuration -----------------------*/
+ tmpreg = huart->Instance->CR1;
+
+ /* Clear TE and RE bits */
+ tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE));
+
+ /* Enable the USART's receive interface by setting the RE bit in the USART CR1 register */
+ tmpreg |= (uint32_t)USART_CR1_RE;
+
+ /* Write to USART CR1 */
+ huart->Instance->CR1 = (uint32_t)tmpreg;
+
+ huart->State = HAL_UART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup UART_Group4 Peripheral State and Errors functions
+ * @brief UART State and Errors functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State and Errors functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to return the State of
+ UART communication process, return Peripheral Errors occured during communication
+ process
+ (+) HAL_UART_GetState() API can be helpful to check in run-time the state of the UART peripheral.
+ (+) HAL_UART_GetError() check in run-time errors that could be occured durung communication.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the UART state.
+ * @param huart: UART handle
+ * @retval HAL state
+ */
+HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart)
+{
+ return huart->State;
+}
+
+/**
+* @brief Return the UART error code
+* @param huart : pointer to a UART_HandleTypeDef structure that contains
+ * the configuration information for the specified UART.
+* @retval UART Error Code
+*/
+uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart)
+{
+ return huart->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @brief DMA UART transmit process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma)
+{
+ UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ huart->TxXferCount = 0;
+
+ /* Disable the DMA transfer for transmit request by setting the DMAT bit
+ in the UART CR3 register */
+ huart->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAT);
+
+ /* Wait for UART TC Flag */
+ if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, UART_TIMEOUT_VALUE) != HAL_OK)
+ {
+ /* Timeout Occured */
+ huart->State = HAL_UART_STATE_TIMEOUT;
+ HAL_UART_ErrorCallback(huart);
+ }
+ else
+ {
+ /* No Timeout */
+ /* Check if a receive process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_RX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_READY;
+ }
+ HAL_UART_TxCpltCallback(huart);
+ }
+}
+
+/**
+ * @brief DMA UART transmit process half complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma)
+{
+ UART_HandleTypeDef* huart = (UART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ HAL_UART_TxHalfCpltCallback(huart);
+}
+
+/**
+ * @brief DMA UART receive process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
+{
+ UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ huart->RxXferCount = 0;
+
+ /* Disable the DMA transfer for the receiver request by setting the DMAR bit
+ in the UART CR3 register */
+ huart->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAR);
+
+ /* Check if a transmit process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX;
+ }
+ else
+ {
+ huart->State = HAL_UART_STATE_READY;
+ }
+ HAL_UART_RxCpltCallback(huart);
+}
+
+/**
+ * @brief DMA UART receive process half complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
+{
+ UART_HandleTypeDef* huart = (UART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ HAL_UART_RxHalfCpltCallback(huart);
+}
+
+/**
+ * @brief DMA UART communication error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void UART_DMAError(DMA_HandleTypeDef *hdma)
+{
+ UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ huart->RxXferCount = 0;
+ huart->TxXferCount = 0;
+ huart->State= HAL_UART_STATE_READY;
+ huart->ErrorCode |= HAL_UART_ERROR_DMA;
+ HAL_UART_ErrorCallback(huart);
+}
+
+/**
+ * @brief This function handles UART Communication Timeout.
+ * @param huart: UART handle
+ * @param Flag: specifies the UART flag to check.
+ * @param Status: The new Flag status (SET or RESET).
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Wait until flag is set */
+ if(Status == RESET)
+ {
+ while(__HAL_UART_GET_FLAG(huart, Flag) == RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
+ __HAL_UART_DISABLE_IT(huart, UART_IT_TXE);
+ __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
+ __HAL_UART_DISABLE_IT(huart, UART_IT_PE);
+ __HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
+
+ huart->State= HAL_UART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ else
+ {
+ while(__HAL_UART_GET_FLAG(huart, Flag) != RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
+ __HAL_UART_DISABLE_IT(huart, UART_IT_TXE);
+ __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
+ __HAL_UART_DISABLE_IT(huart, UART_IT_PE);
+ __HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
+
+ huart->State= HAL_UART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Sends an amount of data in non blocking mode.
+ * @param huart: UART handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart)
+{
+ uint16_t* tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = huart->State;
+ if((tmp1 == HAL_UART_STATE_BUSY_TX) || (tmp1 == HAL_UART_STATE_BUSY_TX_RX))
+ {
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ if(huart->Init.WordLength == UART_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) huart->pTxBuffPtr;
+ huart->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF);
+ if(huart->Init.Parity == UART_PARITY_NONE)
+ {
+ huart->pTxBuffPtr += 2;
+ }
+ else
+ {
+ huart->pTxBuffPtr += 1;
+ }
+ }
+ else
+ {
+ huart->Instance->DR = (uint8_t)(*huart->pTxBuffPtr++ & (uint8_t)0x00FF);
+ }
+
+ if(--huart->TxXferCount == 0)
+ {
+ /* Disable the UART Transmit Complete Interrupt */
+ __HAL_UART_DISABLE_IT(huart, UART_IT_TC);
+
+ /* Check if a receive process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_RX;
+ }
+ else
+ {
+ /* Disable the UART Parity Error Interrupt */
+ __HAL_UART_DISABLE_IT(huart, UART_IT_PE);
+
+ /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */
+ __HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
+
+ huart->State = HAL_UART_STATE_READY;
+ }
+ /* Call the Process Unlocked before calling the Tx callback API to give the possibility to
+ start again the Transmission under the Tx callback API */
+ __HAL_UNLOCK(huart);
+
+ HAL_UART_TxCpltCallback(huart);
+
+ return HAL_OK;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+/**
+ * @brief Receives an amount of data in non blocking mode
+ * @param huart: UART handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart)
+{
+ uint16_t* tmp;
+ uint32_t tmp1 = 0;
+
+ tmp1 = huart->State;
+ if((tmp1 == HAL_UART_STATE_BUSY_RX) || (tmp1 == HAL_UART_STATE_BUSY_TX_RX))
+ {
+ /* Process Locked */
+ __HAL_LOCK(huart);
+
+ if(huart->Init.WordLength == UART_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) huart->pRxBuffPtr;
+ if(huart->Init.Parity == UART_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x01FF);
+ huart->pRxBuffPtr += 2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x00FF);
+ huart->pRxBuffPtr += 1;
+ }
+ }
+ else
+ {
+ if(huart->Init.Parity == UART_PARITY_NONE)
+ {
+ *huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ *huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x007F);
+ }
+ }
+
+ if(--huart->RxXferCount == 0)
+ {
+ while(HAL_IS_BIT_SET(huart->Instance->SR, UART_FLAG_RXNE))
+ {
+ }
+ __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
+
+ /* Check if a transmit process is ongoing or not */
+ if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
+ {
+ huart->State = HAL_UART_STATE_BUSY_TX;
+ }
+ else
+ {
+ /* Disable the UART Parity Error Interrupt */
+ __HAL_UART_DISABLE_IT(huart, UART_IT_PE);
+
+ /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */
+ __HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
+
+ huart->State = HAL_UART_STATE_READY;
+ }
+ /* Call the Process Unlocked before calling the Rx callback API to give the possibility to
+ start again the reception under the Rx callback API */
+ __HAL_UNLOCK(huart);
+
+ HAL_UART_RxCpltCallback(huart);
+
+ return HAL_OK;
+ }
+ /* Process Unlocked */
+ __HAL_UNLOCK(huart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Configures the UART peripheral.
+ * @param huart: UART handle
+ * @retval None
+ */
+static void UART_SetConfig(UART_HandleTypeDef *huart)
+{
+ uint32_t tmpreg = 0x00;
+
+ /* Check the parameters */
+ assert_param(IS_UART_INSTANCE(huart->Instance));
+ assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate));
+ assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength));
+ assert_param(IS_UART_STOPBITS(huart->Init.StopBits));
+ assert_param(IS_UART_PARITY(huart->Init.Parity));
+ assert_param(IS_UART_MODE(huart->Init.Mode));
+ assert_param(IS_UART_HARDWARE_FLOW_CONTROL(huart->Init.HwFlowCtl));
+
+ /* The hardware flow control is available only for USART1, USART2, USART3 and USART6 */
+ if(huart->Init.HwFlowCtl != UART_HWCONTROL_NONE)
+ {
+ assert_param(IS_UART_HWFLOW_INSTANCE(huart->Instance));
+ }
+
+ /*-------------------------- USART CR2 Configuration -----------------------*/
+ tmpreg = huart->Instance->CR2;
+
+ /* Clear STOP[13:12] bits */
+ tmpreg &= (uint32_t)~((uint32_t)USART_CR2_STOP);
+
+ /* Configure the UART Stop Bits: Set STOP[13:12] bits according to huart->Init.StopBits value */
+ tmpreg |= (uint32_t)huart->Init.StopBits;
+
+ /* Write to USART CR2 */
+ huart->Instance->CR2 = (uint32_t)tmpreg;
+
+ /*-------------------------- USART CR1 Configuration -----------------------*/
+ tmpreg = huart->Instance->CR1;
+
+ /* Clear M, PCE, PS, TE and RE bits */
+ tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | \
+ USART_CR1_RE | USART_CR1_OVER8));
+
+ /* Configure the UART Word Length, Parity and mode:
+ Set the M bits according to huart->Init.WordLength value
+ Set PCE and PS bits according to huart->Init.Parity value
+ Set TE and RE bits according to huart->Init.Mode value
+ Set OVER8 bit according to huart->Init.OverSampling value */
+ tmpreg |= (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode | huart->Init.OverSampling;
+
+ /* Write to USART CR1 */
+ huart->Instance->CR1 = (uint32_t)tmpreg;
+
+ /*-------------------------- USART CR3 Configuration -----------------------*/
+ tmpreg = huart->Instance->CR3;
+
+ /* Clear CTSE and RTSE bits */
+ tmpreg &= (uint32_t)~((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE));
+
+ /* Configure the UART HFC: Set CTSE and RTSE bits according to huart->Init.HwFlowCtl value */
+ tmpreg |= huart->Init.HwFlowCtl;
+
+ /* Write to USART CR3 */
+ huart->Instance->CR3 = (uint32_t)tmpreg;
+
+ /* Check the Over Sampling */
+ if(huart->Init.OverSampling == UART_OVERSAMPLING_8)
+ {
+ /*-------------------------- USART BRR Configuration ---------------------*/
+ if((huart->Instance == USART1) || (huart->Instance == USART6))
+ {
+ huart->Instance->BRR = __UART_BRR_SAMPLING8(HAL_RCC_GetPCLK2Freq(), huart->Init.BaudRate);
+ }
+ else
+ {
+ huart->Instance->BRR = __UART_BRR_SAMPLING8(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate);
+ }
+ }
+ else
+ {
+ /*-------------------------- USART BRR Configuration ---------------------*/
+ if((huart->Instance == USART1) || (huart->Instance == USART6))
+ {
+ huart->Instance->BRR = __UART_BRR_SAMPLING16(HAL_RCC_GetPCLK2Freq(), huart->Init.BaudRate);
+ }
+ else
+ {
+ huart->Instance->BRR = __UART_BRR_SAMPLING16(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate);
+ }
+ }
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_UART_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_usart.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_usart.c
new file mode 100644
index 0000000..f0b7dbd
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_usart.c
@@ -0,0 +1,1821 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_usart.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief USART HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Universal Synchronous Asynchronous Receiver Transmitter (USART) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral Control functions
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ The USART HAL driver can be used as follows:
+
+ (#) Declare a USART_HandleTypeDef handle structure.
+ (#) Initialize the USART low level resources by implement the HAL_USART_MspInit ()API:
+ (##) Enable the USARTx interface clock.
+ (##) USART pins configuration:
+ (+++) Enable the clock for the USART GPIOs.
+ (+++) Configure these USART pins as alternate function pull-up.
+ (##) NVIC configuration if you need to use interrupt process (HAL_USART_Transmit_IT(),
+ HAL_USART_Receive_IT() and HAL_USART_TransmitReceive_IT() APIs):
+ (+++) Configure the USARTx interrupt priority.
+ (+++) Enable the NVIC USART IRQ handle.
+ (##) DMA Configuration if you need to use DMA process (HAL_USART_Transmit_DMA()
+ HAL_USART_Receive_IT() and HAL_USART_TransmitReceive_IT() APIs):
+ (+++) Declare a DMA handle structure for the Tx/Rx stream.
+ (+++) Enable the DMAx interface clock.
+ (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.
+ (+++) Configure the DMA Tx/Rx Stream.
+ (+++) Associate the initilalized DMA handle to the USART DMA Tx/Rx handle.
+ (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream.
+
+ (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware
+ flow control and Mode(Receiver/Transmitter) in the husart Init structure.
+
+ (#) Initialize the USART registers by calling the HAL_USART_Init() API:
+ (++) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc)
+ by calling the customed HAL_USART_MspInit(&husart) API.
+
+ -@@- The specific USART interrupts (Transmission complete interrupt,
+ RXNE interrupt and Error Interrupts) will be managed using the macros
+ __USART_ENABLE_IT() and __USART_DISABLE_IT() inside the transmit and receive process.
+
+ (#) Three mode of operations are available within this driver :
+
+ *** Polling mode IO operation ***
+ =================================
+ [..]
+ (+) Send an amount of data in blocking mode using HAL_USART_Transmit()
+ (+) Receive an amount of data in blocking mode using HAL_USART_Receive()
+
+ *** Interrupt mode IO operation ***
+ ===================================
+ [..]
+ (+) Send an amount of data in non blocking mode using HAL_USART_Transmit_IT()
+ (+) At transmission end of half transfer HAL_USART_TxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_USART_TxHalfCpltCallback
+ (+) At transmission end of transfer HAL_USART_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_USART_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode using HAL_USART_Receive_IT()
+ (+) At reception end of half transfer HAL_USART_RxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_USART_RxHalfCpltCallback
+ (+) At reception end of transfer HAL_USART_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_USART_RxCpltCallback
+ (+) In case of transfer Error, HAL_USART_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_USART_ErrorCallback
+
+ *** DMA mode IO operation ***
+ ==============================
+ [..]
+ (+) Send an amount of data in non blocking mode (DMA) using HAL_USART_Transmit_DMA()
+ (+) At transmission end of half transfer HAL_USART_TxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_USART_TxHalfCpltCallback
+ (+) At transmission end of transfer HAL_USART_TxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_USART_TxCpltCallback
+ (+) Receive an amount of data in non blocking mode (DMA) using HAL_USART_Receive_DMA()
+ (+) At reception end of half transfer HAL_USART_RxHalfCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_USART_RxHalfCpltCallback
+ (+) At reception end of transfer HAL_USART_RxCpltCallback is executed and user can
+ add his own code by customization of function pointer HAL_USART_RxCpltCallback
+ (+) In case of transfer Error, HAL_USART_ErrorCallback() function is executed and user can
+ add his own code by customization of function pointer HAL_USART_ErrorCallback
+ (+) Pause the DMA Transfer using HAL_USART_DMAPause()
+ (+) Resume the DMA Transfer using HAL_USART_DMAResume()
+ (+) Stop the DMA Transfer using HAL_USART_DMAStop()
+
+ *** USART HAL driver macros list ***
+ =============================================
+ [..]
+ Below the list of most used macros in USART HAL driver.
+
+ (+) __HAL_USART_ENABLE: Enable the USART peripheral
+ (+) __HAL_USART_DISABLE: Disable the USART peripheral
+ (+) __HAL_USART_GET_FLAG : Checks whether the specified USART flag is set or not
+ (+) __HAL_USART_CLEAR_FLAG : Clears the specified USART pending flag
+ (+) __HAL_USART_ENABLE_IT: Enables the specified USART interrupt
+ (+) __HAL_USART_DISABLE_IT: Disables the specified USART interrupt
+
+ [..]
+ (@) You can refer to the USART HAL driver header file for more useful macros
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup USART
+ * @brief HAL USART Synchronous module driver
+ * @{
+ */
+#ifdef HAL_USART_MODULE_ENABLED
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+#define DYMMY_DATA 0xFFFF
+#define USART_TIMEOUT_VALUE 22000
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart);
+static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart);
+static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart);
+static void USART_SetConfig (USART_HandleTypeDef *husart);
+static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma);
+static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma);
+static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
+static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma);
+static void USART_DMAError(DMA_HandleTypeDef *hdma);
+static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
+/* Private functions ---------------------------------------------------------*/
+
+
+/** @defgroup USART_Private_Functions
+ * @{
+ */
+
+/** @defgroup USART_Group1 USART Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and Configuration functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to initialize the USART
+ in asynchronous and in synchronous modes.
+ (+) For the asynchronous mode only these parameters can be configured:
+ (++) Baud Rate
+ (++) Word Length
+ (++) Stop Bit
+ (++) Parity: If the parity is enabled, then the MSB bit of the data written
+ in the data register is transmitted but is changed by the parity bit.
+ Depending on the frame length defined by the M bit (8-bits or 9-bits),
+ the possible USART frame formats are as listed in the following table:
+ +-------------------------------------------------------------+
+ | M bit | PCE bit | USART frame |
+ |---------------------|---------------------------------------|
+ | 0 | 0 | | SB | 8 bit data | STB | |
+ |---------|-----------|---------------------------------------|
+ | 0 | 1 | | SB | 7 bit data | PB | STB | |
+ |---------|-----------|---------------------------------------|
+ | 1 | 0 | | SB | 9 bit data | STB | |
+ |---------|-----------|---------------------------------------|
+ | 1 | 1 | | SB | 8 bit data | PB | STB | |
+ +-------------------------------------------------------------+
+ (++) USART polarity
+ (++) USART phase
+ (++) USART LastBit
+ (++) Receiver/transmitter modes
+
+ [..]
+ The HAL_USART_Init() function follows the USART synchronous configuration
+ procedure (details for the procedure are available in reference manual (RM0329)).
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the USART mode according to the specified
+ * parameters in the USART_InitTypeDef and create the associated handle.
+ * @param husart: USART handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart)
+{
+ /* Check the USART handle allocation */
+ if(husart == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_USART_INSTANCE(husart->Instance));
+
+ if(husart->State == HAL_USART_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_USART_MspInit(husart);
+ }
+
+ husart->State = HAL_USART_STATE_BUSY;
+
+ /* Set the USART Communication parameters */
+ USART_SetConfig(husart);
+
+ /* In USART mode, the following bits must be kept cleared:
+ - LINEN bit in the USART_CR2 register
+ - HDSEL, SCEN and IREN bits in the USART_CR3 register */
+ husart->Instance->CR2 &= ~USART_CR2_LINEN;
+ husart->Instance->CR3 &= ~(USART_CR3_IREN | USART_CR3_SCEN | USART_CR3_HDSEL);
+
+ /* Enable the Peripheral */
+ __USART_ENABLE(husart);
+
+ /* Initialize the USART state */
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State= HAL_USART_STATE_READY;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the USART peripheral.
+ * @param husart: USART handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart)
+{
+ /* Check the USART handle allocation */
+ if(husart == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_USART_INSTANCE(husart->Instance));
+
+ husart->State = HAL_USART_STATE_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_USART_MspDeInit(husart);
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief USART MSP Init.
+ * @param husart: USART handle
+ * @retval None
+ */
+ __weak void HAL_USART_MspInit(USART_HandleTypeDef *husart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_USART_MspInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @brief USART MSP DeInit.
+ * @param husart: USART handle
+ * @retval None
+ */
+ __weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_USART_MspDeInit could be implenetd in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup USART_Group2 IO operation functions
+ * @brief USART Transmit and Receive functions
+ *
+@verbatim
+ ==============================================================================
+ ##### IO operation functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the USART synchronous
+ data transfers.
+
+ [..]
+ The USART supports master mode only: it cannot receive or send data related to an input
+ clock (SCLK is always an output).
+
+ (#) There are two mode of transfer:
+ (++) Blocking mode: The communication is performed in polling mode.
+ The HAL status of all data processing is returned by the same function
+ after finishing transfer.
+ (++) No-Blocking mode: The communication is performed using Interrupts
+ or DMA, These API's return the HAL status.
+ The end of the data processing will be indicated through the
+ dedicated USART IRQ when using Interrupt mode or the DMA IRQ when
+ using DMA mode.
+ The HAL_USART_TxCpltCallback(), HAL_USART_RxCpltCallback() and HAL_USART_TxRxCpltCallback()
+ user callbacks
+ will be executed respectivelly at the end of the transmit or Receive process
+ The HAL_USART_ErrorCallback()user callback will be executed when a communication
+ error is detected
+
+ (#) Blocking mode API's are :
+ (++) HAL_USART_Transmit()in simplex mode
+ (++) HAL_USART_Receive() in full duplex receive only
+ (++) HAL_USART_TransmitReceive() in full duplex mode
+
+ (#) Non-Blocking mode API's with Interrupt are :
+ (++) HAL_USART_Transmit_IT()in simplex mode
+ (++) HAL_USART_Receive_IT() in full duplex receive only
+ (++) HAL_USART_TransmitReceive_IT()in full duplex mode
+ (++) HAL_USART_IRQHandler()
+
+ (#) No-Blocking mode functions with DMA are :
+ (++) HAL_USART_Transmit_DMA()in simplex mode
+ (++) HAL_USART_Receive_DMA() in full duplex receive only
+ (++) HAL_USART_TransmitReceie_DMA() in full duplex mode
+
+ (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode:
+ (++) HAL_USART_TxCpltCallback()
+ (++) HAL_USART_RxCpltCallback()
+ (++) HAL_USART_ErrorCallback()
+ (++) HAL_USART_TxRxCpltCallback()
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Simplex Send an amount of data in blocking mode.
+ * @param husart: USART handle
+ * @param pTxData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout)
+{
+ uint16_t* tmp;
+
+ if(husart->State == HAL_USART_STATE_READY)
+ {
+ if((pTxData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_BUSY_TX;
+
+ husart->TxXferSize = Size;
+ husart->TxXferCount = Size;
+ while(husart->TxXferCount > 0)
+ {
+ husart->TxXferCount--;
+ if(husart->Init.WordLength == USART_WORDLENGTH_9B)
+ {
+ /* Wait for TC flag in order to write data in DR */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pTxData;
+ husart->Instance->DR = (*tmp & (uint16_t)0x01FF);
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ pTxData += 2;
+ }
+ else
+ {
+ pTxData += 1;
+ }
+ }
+ else
+ {
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ husart->Instance->DR = (*pTxData++ & (uint8_t)0xFF);
+ }
+ }
+
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ husart->State = HAL_USART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Full-Duplex Receive an amount of data in blocking mode.
+ * @param husart: USART handle
+ * @param pRxData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout)
+{
+ uint16_t* tmp;
+
+ if(husart->State == HAL_USART_STATE_READY)
+ {
+ if((pRxData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_BUSY_RX;
+
+ husart->RxXferSize = Size;
+ husart->RxXferCount = Size;
+ /* Check the remain data to be received */
+ while(husart->RxXferCount > 0)
+ {
+ husart->RxXferCount--;
+ if(husart->Init.WordLength == USART_WORDLENGTH_9B)
+ {
+ /* Wait until TC flag is set to send dummy byte in order to generate the clock for the slave to send data */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ /* Send dummy byte in order to generate clock */
+ husart->Instance->DR = (DYMMY_DATA & (uint16_t)0x01FF);
+
+ /* Wait for RXNE Flag */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pRxData ;
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x01FF);
+ pRxData +=2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x00FF);
+ pRxData +=1;
+ }
+ }
+ else
+ {
+ /* Wait until TC flag is set to send dummy byte in order to generate the clock for the slave to send data */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+
+ /* Send Dummy Byte in order to generate clock */
+ husart->Instance->DR = (DYMMY_DATA & (uint16_t)0x00FF);
+
+ /* Wait until RXNE flag is set to receive the byte */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ /* Receive data */
+ *pRxData++ = (uint8_t)(husart->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ /* Receive data */
+ *pRxData++ = (uint8_t)(husart->Instance->DR & (uint8_t)0x007F);
+ }
+
+ }
+ }
+
+ husart->State = HAL_USART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Full-Duplex Send receive an amount of data in full-duplex mode (blocking mode).
+ * @param husart: USART handle
+ * @param pTxData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout)
+{
+ uint16_t* tmp;
+
+ if(husart->State == HAL_USART_STATE_READY)
+ {
+ if((pTxData == NULL) || (pRxData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_BUSY_RX;
+
+ husart->RxXferSize = Size;
+ husart->TxXferSize = Size;
+ husart->TxXferCount = Size;
+ husart->RxXferCount = Size;
+
+ /* Check the remain data to be received */
+ while(husart->TxXferCount > 0)
+ {
+ husart->TxXferCount--;
+ husart->RxXferCount--;
+ if(husart->Init.WordLength == USART_WORDLENGTH_9B)
+ {
+ /* Wait for TC flag in order to write data in DR */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pTxData;
+ husart->Instance->DR = (*tmp & (uint16_t)0x01FF);
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ pTxData += 2;
+ }
+ else
+ {
+ pTxData += 1;
+ }
+
+ /* Wait for RXNE Flag */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ tmp = (uint16_t*) pRxData ;
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x01FF);
+ pRxData += 2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x00FF);
+ pRxData += 1;
+ }
+ }
+ else
+ {
+ /* Wait for TC flag in order to write data in DR */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ husart->Instance->DR = (*pTxData++ & (uint8_t)0x00FF);
+
+ /* Wait for RXNE Flag */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK)
+ {
+ return HAL_TIMEOUT;
+ }
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ /* Receive data */
+ *pRxData++ = (uint8_t)(husart->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ /* Receive data */
+ *pRxData++ = (uint8_t)(husart->Instance->DR & (uint8_t)0x007F);
+ }
+ }
+ }
+
+ husart->State = HAL_USART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Simplex Send an amount of data in non-blocking mode.
+ * @param husart: USART handle
+ * @param pTxData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ * @note The USART errors are not managed to avoid the overrun error.
+ */
+HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size)
+{
+ if(husart->State == HAL_USART_STATE_READY)
+ {
+ if((pTxData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ husart->pTxBuffPtr = pTxData;
+ husart->TxXferSize = Size;
+ husart->TxXferCount = Size;
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_BUSY_TX;
+
+ /* The USART Error Interrupts: (Frame error, Noise error, Overrun error)
+ are not managed by the USART transmit process to avoid the overrun interrupt
+ when the USART mode is configured for transmit and receive "USART_MODE_TX_RX"
+ to benefit for the frame error and noise interrupts the USART mode should be
+ configured only for transmit "USART_MODE_TX"
+ The __USART_ENABLE_IT(husart, USART_IT_ERR) can be used to enable the Frame error,
+ Noise error interrupt */
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ /* Enable the USART Transmit Complete Interrupt */
+ __USART_ENABLE_IT(husart, USART_IT_TC);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Simplex Receive an amount of data in non-blocking mode.
+ * @param husart: USART handle
+ * @param pRxData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size)
+{
+ if(husart->State == HAL_USART_STATE_READY)
+ {
+ if((pRxData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ husart->pRxBuffPtr = pRxData;
+ husart->RxXferSize = Size;
+ husart->RxXferCount = Size;
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_BUSY_RX;
+
+ /* Enable the USART Data Register not empty Interrupt */
+ __USART_ENABLE_IT(husart, USART_IT_RXNE);
+
+ /* Enable the USART Parity Error Interrupt */
+ __USART_ENABLE_IT(husart, USART_IT_PE);
+
+ /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */
+ __USART_ENABLE_IT(husart, USART_IT_ERR);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ /* Send dummy byte in order to generate the clock for the slave to send data */
+ husart->Instance->DR = (DYMMY_DATA & (uint16_t)0x01FF);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Full-Duplex Send receive an amount of data in full-duplex mode (non-blocking).
+ * @param husart: USART handle
+ * @param pTxData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size)
+{
+ if(husart->State == HAL_USART_STATE_READY)
+ {
+ if((pTxData == NULL) || (pRxData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ husart->pRxBuffPtr = pRxData;
+ husart->RxXferSize = Size;
+ husart->RxXferCount = Size;
+ husart->pTxBuffPtr = pTxData;
+ husart->TxXferSize = Size;
+ husart->TxXferCount = Size;
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_BUSY_TX_RX;
+
+ /* Enable the USART Data Register not empty Interrupt */
+ __USART_ENABLE_IT(husart, USART_IT_RXNE);
+
+ /* Enable the USART Parity Error Interrupt */
+ __USART_ENABLE_IT(husart, USART_IT_PE);
+
+ /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */
+ __USART_ENABLE_IT(husart, USART_IT_ERR);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ /* Enable the USART Transmit Complete Interrupt */
+ __USART_ENABLE_IT(husart, USART_IT_TC);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Simplex Send an amount of data in non-blocking mode.
+ * @param husart: USART handle
+ * @param pData: Pointer to data buffer
+ * @param Size: Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size)
+{
+ uint32_t *tmp;
+
+ if(husart->State == HAL_USART_STATE_READY)
+ {
+ if((pTxData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ husart->pTxBuffPtr = pTxData;
+ husart->TxXferSize = Size;
+ husart->TxXferCount = Size;
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_BUSY_TX;
+
+ /* Set the USART DMA transfer complete callback */
+ husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt;
+
+ /* Set the USART DMA Half transfer complete callback */
+ husart->hdmatx->XferHalfCpltCallback = USART_DMATxHalfCplt;
+
+ /* Set the DMA error callback */
+ husart->hdmatx->XferErrorCallback = USART_DMAError;
+
+ /* Enable the USART transmit DMA Stream */
+ tmp = (uint32_t*)&pTxData;
+ HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->DR, Size);
+
+ /* Enable the DMA transfer for transmit request by setting the DMAT bit
+ in the USART CR3 register */
+ husart->Instance->CR3 |= USART_CR3_DMAT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Full-Duplex Receive an amount of data in non-blocking mode.
+ * @param husart: USART handle
+ * @param pRxData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @retval HAL status
+ * @note The USART DMA transmit stream must be configured in order to generate the clock for the slave.
+ * @note When the USART parity is enabled (PCE = 1) the data received contain the parity bit.
+ */
+HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size)
+{
+ uint32_t *tmp;
+
+ if(husart->State == HAL_USART_STATE_READY)
+ {
+ if((pRxData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ husart->pRxBuffPtr = pRxData;
+ husart->RxXferSize = Size;
+ husart->pTxBuffPtr = pRxData;
+ husart->TxXferSize = Size;
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_BUSY_RX;
+
+ /* Set the USART DMA Rx transfer complete callback */
+ husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt;
+
+ /* Set the USART DMA Half transfer complete callback */
+ husart->hdmarx->XferHalfCpltCallback = USART_DMARxHalfCplt;
+
+ /* Set the USART DMA Rx transfer error callback */
+ husart->hdmarx->XferErrorCallback = USART_DMAError;
+
+ /* Enable the USART receive DMA Stream */
+ tmp = (uint32_t*)&pRxData;
+ HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->DR, *(uint32_t*)tmp, Size);
+
+ /* Enable the USART transmit DMA Stream: the transmit stream is used in order
+ to generate in the non-blocking mode the clock to the slave device,
+ this mode isn't a simplex receive mode but a full-duplex receive one */
+ HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->DR, Size);
+
+ /* Enable the DMA transfer for the receiver request by setting the DMAR bit
+ in the USART CR3 register */
+ husart->Instance->CR3 |= USART_CR3_DMAR;
+
+ /* Enable the DMA transfer for transmit request by setting the DMAT bit
+ in the USART CR3 register */
+ husart->Instance->CR3 |= USART_CR3_DMAT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Full-Duplex Transmit Receive an amount of data in non-blocking mode.
+ * @param husart: USART handle
+ * @param pRxData: Pointer to data buffer
+ * @param Size: Amount of data to be received
+ * @note When the USART parity is enabled (PCE = 1) the data received contain the parity bit.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size)
+{
+ uint32_t *tmp;
+
+ if(husart->State == HAL_USART_STATE_READY)
+ {
+ if((pTxData == NULL) || (pRxData == NULL) || (Size == 0))
+ {
+ return HAL_ERROR;
+ }
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ husart->pRxBuffPtr = pRxData;
+ husart->RxXferSize = Size;
+ husart->pTxBuffPtr = pTxData;
+ husart->TxXferSize = Size;
+
+ husart->ErrorCode = HAL_USART_ERROR_NONE;
+ husart->State = HAL_USART_STATE_BUSY_TX_RX;
+
+ /* Set the USART DMA Rx transfer complete callback */
+ husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt;
+
+ /* Set the USART DMA Half transfer complete callback */
+ husart->hdmarx->XferHalfCpltCallback = USART_DMARxHalfCplt;
+
+ /* Set the USART DMA Tx transfer complete callback */
+ husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt;
+
+ /* Set the USART DMA Half transfer complete callback */
+ husart->hdmatx->XferHalfCpltCallback = USART_DMATxHalfCplt;
+
+ /* Set the USART DMA Tx transfer error callback */
+ husart->hdmatx->XferErrorCallback = USART_DMAError;
+
+ /* Set the USART DMA Rx transfer error callback */
+ husart->hdmarx->XferErrorCallback = USART_DMAError;
+
+ /* Enable the USART receive DMA Stream */
+ tmp = (uint32_t*)&pRxData;
+ HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->DR, *(uint32_t*)tmp, Size);
+
+ /* Enable the USART transmit DMA Stream */
+ tmp = (uint32_t*)&pTxData;
+ HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->DR, Size);
+
+ /* Enable the DMA transfer for the receiver request by setting the DMAR bit
+ in the USART CR3 register */
+ husart->Instance->CR3 |= USART_CR3_DMAR;
+
+ /* Enable the DMA transfer for transmit request by setting the DMAT bit
+ in the USART CR3 register */
+ husart->Instance->CR3 |= USART_CR3_DMAT;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Pauses the DMA Transfer.
+ * @param husart: USART handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart)
+{
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ if(husart->State == HAL_USART_STATE_BUSY_TX)
+ {
+ /* Disable the USART DMA Tx request */
+ husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT);
+ }
+ else if(husart->State == HAL_USART_STATE_BUSY_RX)
+ {
+ /* Disable the USART DMA Rx request */
+ husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR);
+ }
+ else if(husart->State == HAL_USART_STATE_BUSY_TX_RX)
+ {
+ /* Disable the USART DMA Tx request */
+ husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT);
+ /* Disable the USART DMA Rx request */
+ husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Resumes the DMA Transfer.
+ * @param husart: USART handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart)
+{
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ if(husart->State == HAL_USART_STATE_BUSY_TX)
+ {
+ /* Enable the USART DMA Tx request */
+ husart->Instance->CR3 |= USART_CR3_DMAT;
+ }
+ else if(husart->State == HAL_USART_STATE_BUSY_RX)
+ {
+ /* Enable the USART DMA Rx request */
+ husart->Instance->CR3 |= USART_CR3_DMAR;
+ }
+ else if(husart->State == HAL_USART_STATE_BUSY_TX_RX)
+ {
+ /* Enable the USART DMA Rx request before the DMA Tx request */
+ husart->Instance->CR3 |= USART_CR3_DMAR;
+ /* Enable the USART DMA Tx request */
+ husart->Instance->CR3 |= USART_CR3_DMAT;
+ }
+
+ /* If the USART peripheral is still not enabled, enable it */
+ if ((husart->Instance->CR1 & USART_CR1_UE) == 0)
+ {
+ /* Enable USART peripheral */
+ __USART_ENABLE(husart);
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Stops the DMA Transfer.
+ * @param husart: USART handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart)
+{
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ /* Disable the USART Tx/Rx DMA requests */
+ husart->Instance->CR3 &= ~USART_CR3_DMAT;
+ husart->Instance->CR3 &= ~USART_CR3_DMAR;
+
+ /* Abort the USART DMA Tx Stream */
+ if(husart->hdmatx != NULL)
+ {
+ HAL_DMA_Abort(husart->hdmatx);
+ }
+ /* Abort the USART DMA Rx Stream */
+ if(husart->hdmarx != NULL)
+ {
+ HAL_DMA_Abort(husart->hdmarx);
+ }
+ /* Disable USART peripheral */
+ __USART_DISABLE(husart);
+
+ husart->State = HAL_USART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief This function handles USART interrupt request.
+ * @param husart: USART handle
+ * @retval None
+ */
+void HAL_USART_IRQHandler(USART_HandleTypeDef *husart)
+{
+ uint32_t tmp1 = 0, tmp2 = 0;
+
+ tmp1 = __HAL_USART_GET_FLAG(husart, USART_FLAG_PE);
+ tmp2 = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_PE);
+ /* USART parity error interrupt occurred -----------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_USART_CLEAR_FLAG(husart, USART_FLAG_PE);
+ husart->ErrorCode |= HAL_USART_ERROR_PE;
+ }
+
+ tmp1 = __HAL_USART_GET_FLAG(husart, USART_FLAG_FE);
+ tmp2 = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR);
+ /* USART frame error interrupt occurred ------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_USART_CLEAR_FLAG(husart, USART_FLAG_FE);
+ husart->ErrorCode |= HAL_USART_ERROR_FE;
+ }
+
+ tmp1 = __HAL_USART_GET_FLAG(husart, USART_FLAG_NE);
+ tmp2 = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR);
+ /* USART noise error interrupt occurred ------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_USART_CLEAR_FLAG(husart, USART_FLAG_NE);
+ husart->ErrorCode |= HAL_USART_ERROR_NE;
+ }
+
+ tmp1 = __HAL_USART_GET_FLAG(husart, USART_FLAG_ORE);
+ tmp2 = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR);
+ /* USART Over-Run interrupt occurred ---------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ __HAL_USART_CLEAR_FLAG(husart, USART_FLAG_ORE);
+ husart->ErrorCode |= HAL_USART_ERROR_ORE;
+ }
+
+ if(husart->ErrorCode != HAL_USART_ERROR_NONE)
+ {
+ /* Set the USART state ready to be able to start again the process */
+ husart->State = HAL_USART_STATE_READY;
+
+ HAL_USART_ErrorCallback(husart);
+ }
+
+ tmp1 = __HAL_USART_GET_FLAG(husart, USART_FLAG_RXNE);
+ tmp2 = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_RXNE);
+ /* USART in mode Receiver --------------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ if(husart->State == HAL_USART_STATE_BUSY_RX)
+ {
+ USART_Receive_IT(husart);
+ }
+ else
+ {
+ USART_TransmitReceive_IT(husart);
+ }
+ }
+
+ tmp1 = __HAL_USART_GET_FLAG(husart, USART_FLAG_TC);
+ tmp2 = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_TC);
+ /* USART in mode Transmitter -----------------------------------------------*/
+ if((tmp1 != RESET) && (tmp2 != RESET))
+ {
+ if(husart->State == HAL_USART_STATE_BUSY_TX)
+ {
+ USART_Transmit_IT(husart);
+ }
+ else
+ {
+ USART_TransmitReceive_IT(husart);
+ }
+ }
+}
+
+/**
+ * @brief Tx Transfer completed callbacks.
+ * @param husart: USART handle
+ * @retval None
+ */
+ __weak void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_USART_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Tx Half Transfer completed callbacks.
+ * @param husart: USART handle
+ * @retval None
+ */
+ __weak void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_USART_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Rx Transfer completed callbacks.
+ * @param husart: USART handle
+ * @retval None
+ */
+__weak void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_USART_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Rx Half Transfer completed callbacks.
+ * @param husart: USART handle
+ * @retval None
+ */
+__weak void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_USART_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief Tx/Rx Transfers completed callback for the non-blocking process.
+ * @param husart: USART handle
+ * @retval None
+ */
+__weak void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_USART_TxCpltCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @brief USART error callbacks.
+ * @param husart: USART handle
+ * @retval None
+ */
+ __weak void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_USART_ErrorCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup USART_Group3 Peripheral State and Errors functions
+ * @brief USART State and Errors functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State and Errors functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to return the State of
+ USART communication
+ process, return Peripheral Errors occured during communication process
+ (+) HAL_USART_GetState() API can be helpful to check in run-time the state
+ of the USART peripheral.
+ (+) HAL_USART_GetError() check in run-time errors that could be occured durung
+ communication.
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the USART state.
+ * @param husart: USART handle
+ * @retval HAL state
+ */
+HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart)
+{
+ return husart->State;
+}
+
+/**
+ * @brief Return the USART error code
+ * @param husart : pointer to a USART_HandleTypeDef structure that contains
+ * the configuration information for the specified USART.
+ * @retval USART Error Code
+ */
+uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart)
+{
+ return husart->ErrorCode;
+}
+
+/**
+ * @}
+ */
+
+
+/**
+ * @brief DMA USART transmit process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma)
+{
+ USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ husart->TxXferCount = 0;
+ if(husart->State == HAL_USART_STATE_BUSY_TX)
+ {
+ /* Wait for USART TC Flag */
+ if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, USART_TIMEOUT_VALUE) != HAL_OK)
+ {
+ /* Timeout Occured */
+ husart->State = HAL_USART_STATE_TIMEOUT;
+ HAL_USART_ErrorCallback(husart);
+ }
+ else
+ {
+ /* No Timeout */
+ /* Disable the DMA transfer for transmit request by setting the DMAT bit
+ in the USART CR3 register */
+ husart->Instance->CR3 &= ~(USART_CR3_DMAT);
+ husart->State= HAL_USART_STATE_READY;
+ }
+ }
+ /* the usart state is HAL_USART_STATE_BUSY_TX_RX*/
+ else
+ {
+ husart->State= HAL_USART_STATE_BUSY_RX;
+ HAL_USART_TxCpltCallback(husart);
+ }
+}
+
+/**
+ * @brief DMA USART transmit process half complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma)
+{
+ USART_HandleTypeDef* husart = (USART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ HAL_USART_TxHalfCpltCallback(husart);
+}
+
+/**
+ * @brief DMA USART receive process complete callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
+{
+ USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ husart->RxXferCount = 0;
+
+ /* Disable the DMA transfer for the Transmit/receiver requests by setting the DMAT/DMAR bit
+ in the USART CR3 register */
+ husart->Instance->CR3 &= ~(USART_CR3_DMAR);
+ husart->Instance->CR3 &= ~(USART_CR3_DMAT);
+
+ husart->State= HAL_USART_STATE_READY;
+
+ HAL_USART_RxCpltCallback(husart);
+}
+
+/**
+ * @brief DMA USART receive process half complete callback
+ * @param hdma : DMA handle
+ * @retval None
+ */
+static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
+{
+ USART_HandleTypeDef* husart = (USART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
+
+ HAL_USART_RxHalfCpltCallback(husart);
+}
+
+/**
+ * @brief DMA USART communication error callback.
+ * @param hdma: DMA handle
+ * @retval None
+ */
+static void USART_DMAError(DMA_HandleTypeDef *hdma)
+{
+ USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+
+ husart->RxXferCount = 0;
+ husart->TxXferCount = 0;
+ husart->ErrorCode |= HAL_USART_ERROR_DMA;
+ husart->State= HAL_USART_STATE_READY;
+
+ HAL_USART_ErrorCallback(husart);
+}
+
+/**
+ * @brief This function handles USART Communication Timeout.
+ * @param husart: USART handle
+ * @param Flag: specifies the USART flag to check.
+ * @param Status: The new Flag status (SET or RESET).
+ * @param Timeout: Timeout duration
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Wait until flag is set */
+ if(Status == RESET)
+ {
+ while(__HAL_USART_GET_FLAG(husart, Flag) == RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
+ __USART_DISABLE_IT(husart, USART_IT_TXE);
+ __USART_DISABLE_IT(husart, USART_IT_RXNE);
+ __USART_DISABLE_IT(husart, USART_IT_PE);
+ __USART_DISABLE_IT(husart, USART_IT_ERR);
+
+ husart->State= HAL_USART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ else
+ {
+ while(__HAL_USART_GET_FLAG(husart, Flag) != RESET)
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
+ __USART_DISABLE_IT(husart, USART_IT_TXE);
+ __USART_DISABLE_IT(husart, USART_IT_RXNE);
+ __USART_DISABLE_IT(husart, USART_IT_PE);
+ __USART_DISABLE_IT(husart, USART_IT_ERR);
+
+ husart->State= HAL_USART_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+ }
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Simplex Send an amount of data in non-blocking mode.
+ * @param husart: USART handle
+ * @retval HAL status
+ * @note The USART errors are not managed to avoid the overrun error.
+ */
+static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart)
+{
+ uint16_t* tmp;
+
+ if(husart->State == HAL_USART_STATE_BUSY_TX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ if(husart->Init.WordLength == USART_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) husart->pTxBuffPtr;
+ husart->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF);
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ husart->pTxBuffPtr += 2;
+ }
+ else
+ {
+ husart->pTxBuffPtr += 1;
+ }
+ }
+ else
+ {
+ husart->Instance->DR = (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)0x00FF);
+ }
+
+ if(--husart->TxXferCount == 0)
+ {
+ /* Disable the USART Transmit Complete Interrupt */
+ __USART_DISABLE_IT(husart, USART_IT_TC);
+
+ /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */
+ __USART_DISABLE_IT(husart, USART_IT_ERR);
+
+ husart->State = HAL_USART_STATE_READY;
+
+ /* Call the Process Unlocked before calling the Tx callback API to give the possibility to
+ start again the Transmission under the Tx callback API */
+ __HAL_UNLOCK(husart);
+
+ HAL_USART_TxCpltCallback(husart);
+
+ return HAL_OK;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Simplex Receive an amount of data in non-blocking mode.
+ * @param husart: USART handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart)
+{
+ uint16_t* tmp;
+ if(husart->State == HAL_USART_STATE_BUSY_RX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(husart);
+
+ if(husart->Init.WordLength == USART_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) husart->pRxBuffPtr;
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x01FF);
+ husart->pRxBuffPtr += 2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x00FF);
+ husart->pRxBuffPtr += 1;
+ }
+ if(--husart->RxXferCount != 0x00)
+ {
+ /* Send dummy byte in order to generate the clock for the slave to send the next data */
+ husart->Instance->DR = (DYMMY_DATA & (uint16_t)0x01FF);
+ }
+ }
+ else
+ {
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ *husart->pRxBuffPtr++ = (uint8_t)(husart->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ *husart->pRxBuffPtr++ = (uint8_t)(husart->Instance->DR & (uint8_t)0x007F);
+ }
+
+ if(--husart->RxXferCount != 0x00)
+ {
+ /* Send dummy byte in order to generate the clock for the slave to send the next data */
+ husart->Instance->DR = (DYMMY_DATA & (uint16_t)0x00FF);
+ }
+ }
+
+ if(husart->RxXferCount == 0)
+ {
+ /* Disable the USART RXNE Interrupt */
+ __USART_DISABLE_IT(husart, USART_IT_RXNE);
+
+ /* Disable the USART Parity Error Interrupt */
+ __USART_DISABLE_IT(husart, USART_IT_PE);
+
+ /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */
+ __USART_DISABLE_IT(husart, USART_IT_ERR);
+
+ husart->State = HAL_USART_STATE_READY;
+ /* Call the Process Unlocked before calling the Rx callback API to give the possibility to
+ start again the reception under the Rx callback API */
+ __HAL_UNLOCK(husart);
+
+ HAL_USART_RxCpltCallback(husart);
+
+ return HAL_OK;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Full-Duplex Send receive an amount of data in full-duplex mode (non-blocking).
+ * @param husart: USART handle
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart)
+{
+ uint16_t* tmp;
+
+ if(husart->State == HAL_USART_STATE_BUSY_TX_RX)
+ {
+ /* Process Locked */
+ __HAL_LOCK(husart);
+ if(husart->TxXferCount != 0x00)
+ {
+ if(__HAL_USART_GET_FLAG(husart, USART_FLAG_TXE) != RESET)
+ {
+ if(husart->Init.WordLength == USART_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) husart->pTxBuffPtr;
+ husart->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF);
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ husart->pTxBuffPtr += 2;
+ }
+ else
+ {
+ husart->pTxBuffPtr += 1;
+ }
+ }
+ else
+ {
+ husart->Instance->DR = (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)0x00FF);
+ }
+ husart->TxXferCount--;
+
+ /* Check the latest data transmitted */
+ if(husart->TxXferCount == 0)
+ {
+ __USART_DISABLE_IT(husart, USART_IT_TC);
+ }
+ }
+ }
+
+ if(husart->RxXferCount != 0x00)
+ {
+ if(__HAL_USART_GET_FLAG(husart, USART_FLAG_RXNE) != RESET)
+ {
+ if(husart->Init.WordLength == USART_WORDLENGTH_9B)
+ {
+ tmp = (uint16_t*) husart->pRxBuffPtr;
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x01FF);
+ husart->pRxBuffPtr += 2;
+ }
+ else
+ {
+ *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x00FF);
+ husart->pRxBuffPtr += 1;
+ }
+ }
+ else
+ {
+ if(husart->Init.Parity == USART_PARITY_NONE)
+ {
+ *husart->pRxBuffPtr++ = (uint8_t)(husart->Instance->DR & (uint8_t)0x00FF);
+ }
+ else
+ {
+ *husart->pRxBuffPtr++ = (uint8_t)(husart->Instance->DR & (uint8_t)0x007F);
+ }
+ }
+ husart->RxXferCount--;
+ }
+ }
+
+ /* Check the latest data received */
+ if(husart->RxXferCount == 0)
+ {
+ __USART_DISABLE_IT(husart, USART_IT_RXNE);
+
+ /* Disable the USART Parity Error Interrupt */
+ __USART_DISABLE_IT(husart, USART_IT_PE);
+
+ /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */
+ __USART_DISABLE_IT(husart, USART_IT_ERR);
+
+ husart->State = HAL_USART_STATE_READY;
+
+ /* Call the Process Unlocked before calling the Tx\Rx callback API to give the possibility to
+ start again the Transmission\Reception under the Tx\Rx callback API */
+ __HAL_UNLOCK(husart);
+
+ HAL_USART_TxRxCpltCallback(husart);
+
+ return HAL_OK;
+ }
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(husart);
+
+ return HAL_OK;
+ }
+ else
+ {
+ return HAL_BUSY;
+ }
+}
+
+/**
+ * @brief Configures the USART peripheral.
+ * @param husart: USART handle
+ * @retval None
+ */
+static void USART_SetConfig(USART_HandleTypeDef *husart)
+{
+ uint32_t tmpreg = 0x00;
+
+ /* Check the parameters */
+ assert_param(IS_USART_INSTANCE(husart->Instance));
+ assert_param(IS_USART_POLARITY(husart->Init.CLKPolarity));
+ assert_param(IS_USART_PHASE(husart->Init.CLKPhase));
+ assert_param(IS_USART_LASTBIT(husart->Init.CLKLastBit));
+ assert_param(IS_USART_BAUDRATE(husart->Init.BaudRate));
+ assert_param(IS_USART_WORD_LENGTH(husart->Init.WordLength));
+ assert_param(IS_USART_STOPBITS(husart->Init.StopBits));
+ assert_param(IS_USART_PARITY(husart->Init.Parity));
+ assert_param(IS_USART_MODE(husart->Init.Mode));
+
+ /* The LBCL, CPOL and CPHA bits have to be selected when both the transmitter and the
+ receiver are disabled (TE=RE=0) to ensure that the clock pulses function correctly. */
+ husart->Instance->CR1 &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE));
+
+ /*---------------------------- USART CR2 Configuration ---------------------*/
+ tmpreg = husart->Instance->CR2;
+ /* Clear CLKEN, CPOL, CPHA and LBCL bits */
+ tmpreg &= (uint32_t)~((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_CLKEN | USART_CR2_LBCL | USART_CR2_STOP));
+ /* Configure the USART Clock, CPOL, CPHA and LastBit -----------------------*/
+ /* Set CPOL bit according to husart->Init.CLKPolarity value */
+ /* Set CPHA bit according to husart->Init.CLKPhase value */
+ /* Set LBCL bit according to husart->Init.CLKLastBit value */
+ /* Set Stop Bits: Set STOP[13:12] bits according to husart->Init.StopBits value */
+ tmpreg |= (uint32_t)(USART_CLOCK_ENABLED| husart->Init.CLKPolarity |
+ husart->Init.CLKPhase| husart->Init.CLKLastBit | husart->Init.StopBits);
+ /* Write to USART CR2 */
+ husart->Instance->CR2 = (uint32_t)tmpreg;
+
+ /*-------------------------- USART CR1 Configuration -----------------------*/
+ tmpreg = husart->Instance->CR1;
+
+ /* Clear M, PCE, PS, TE and RE bits */
+ tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | \
+ USART_CR1_RE));
+
+ /* Configure the USART Word Length, Parity and mode:
+ Set the M bits according to husart->Init.WordLength value
+ Set PCE and PS bits according to husart->Init.Parity value
+ Set TE and RE bits according to husart->Init.Mode value */
+ tmpreg |= (uint32_t)husart->Init.WordLength | husart->Init.Parity | husart->Init.Mode;
+
+ /* Write to USART CR1 */
+ husart->Instance->CR1 = (uint32_t)tmpreg;
+
+ /*-------------------------- USART CR3 Configuration -----------------------*/
+ /* Clear CTSE and RTSE bits */
+ husart->Instance->CR3 &= (uint32_t)~((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE));
+
+ /*-------------------------- USART BRR Configuration -----------------------*/
+ if((husart->Instance == USART1) || (husart->Instance == USART6))
+ {
+ husart->Instance->BRR = __USART_BRR(HAL_RCC_GetPCLK2Freq(), husart->Init.BaudRate);
+ }
+ else
+ {
+ husart->Instance->BRR = __USART_BRR(HAL_RCC_GetPCLK1Freq(), husart->Init.BaudRate);
+ }
+}
+
+/**
+ * @}
+ */
+
+#endif /* HAL_USART_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_wwdg.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_wwdg.c
new file mode 100644
index 0000000..499542a
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_wwdg.c
@@ -0,0 +1,451 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_hal_wwdg.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief WWDG HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities of the Window Watchdog (WWDG) peripheral:
+ * + Initialization and de-initialization functions
+ * + IO operation functions
+ * + Peripheral State functions
+ @verbatim
+ ==============================================================================
+ ##### WWDG specific features #####
+ ==============================================================================
+ [..]
+ Once enabled the WWDG generates a system reset on expiry of a programmed
+ time period, unless the program refreshes the counter (downcounter)
+ before reaching 0x3F value (i.e. a reset is generated when the counter
+ value rolls over from 0x40 to 0x3F).
+
+ (+) An MCU reset is also generated if the counter value is refreshed
+ before the counter has reached the refresh window value. This
+ implies that the counter must be refreshed in a limited window.
+ (+) Once enabled the WWDG cannot be disabled except by a system reset.
+ (+) WWDGRST flag in RCC_CSR register can be used to inform when a WWDG
+ reset occurs.
+ (+) The WWDG counter input clock is derived from the APB clock divided
+ by a programmable prescaler.
+ (+) WWDG clock (Hz) = PCLK1 / (4096 * Prescaler)
+ (+) WWDG timeout (mS) = 1000 * Counter / WWDG clock
+ (+) WWDG Counter refresh is allowed between the following limits :
+ (++) min time (mS) = 1000 * (Counter – Window) / WWDG clock
+ (++) max time (mS) = 1000 * (Counter – 0x40) / WWDG clock
+
+ (+) Min-max timeout value at 50 MHz(PCLK1): 81.9 us / 41.9 ms
+
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (+) Enable WWDG APB1 clock using __WWDG_CLK_ENABLE().
+ (+) Set the WWDG prescaler, refresh window and counter value
+ using HAL_WWDG_Init() function.
+ (+) Start the WWDG using HAL_WWDG_Start() function.
+ When the WWDG is enabled the counter value should be configured to
+ a value greater than 0x40 to prevent generating an immediate reset.
+ (+) Optionally you can enable the Early Wakeup Interrupt (EWI) which is
+ generated when the counter reaches 0x40, and then start the WWDG using
+ HAL_WWDG_Start_IT(). At EWI HAL_WWDG_WakeupCallback is executed and user can
+ add his own code by customization of function pointer HAL_WWDG_WakeupCallback
+ Once enabled, EWI interrupt cannot be disabled except by a system reset.
+ (+) Then the application program must refresh the WWDG counter at regular
+ intervals during normal operation to prevent an MCU reset, using
+ HAL_WWDG_Refresh() function. This operation must occur only when
+ the counter is lower than the refresh window value already programmed.
+
+ *** WWDG HAL driver macros list ***
+ ==================================
+ [..]
+ Below the list of most used macros in WWDG HAL driver.
+
+ (+) __HAL_WWDG_ENABLE: Enable the WWDG peripheral
+ (+) __HAL_IWDG_GET_FLAG: Get the selected WWDG's flag status
+ (+) __HAL_IWDG_CLEAR_FLAG: Clear the WWDG's pending flags
+ (+) __HAL_IWDG_RELOAD_COUNTER: Enables the WWDG early wakeup interrupt
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup WWDG
+ * @brief WWDG HAL module driver.
+ * @{
+ */
+
+#ifdef HAL_WWDG_MODULE_ENABLED
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup WWDG_Private_Functions
+ * @{
+ */
+
+/** @defgroup WWDG_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de-initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize the WWDG according to the specified parameters
+ in the WWDG_InitTypeDef and create the associated handle
+ (+) DeInitialize the WWDG peripheral
+ (+) Initialize the WWDG MSP
+ (+) DeInitialize the WWDG MSP
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the WWDG according to the specified
+ * parameters in the WWDG_InitTypeDef and creates the associated handle.
+ * @param hwwdg: WWDG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg)
+{
+ uint32_t tmp = 0;
+
+ /* Check the WWDG handle allocation */
+ if(hwwdg == NULL)
+ {
+ return HAL_ERROR;
+ }
+
+ /* Check the parameters */
+ assert_param(IS_WWDG_PRESCALER(hwwdg->Init.Prescaler));
+ assert_param(IS_WWDG_WINDOW(hwwdg->Init.Window));
+ assert_param(IS_WWDG_COUNTER(hwwdg->Init.Counter));
+
+ if(hwwdg->State == HAL_WWDG_STATE_RESET)
+ {
+ /* Init the low level hardware */
+ HAL_WWDG_MspInit(hwwdg);
+ }
+
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_BUSY;
+
+ /* Set WWDG Prescaler and Window */
+ /* Get the CFR register value */
+ tmp = hwwdg->Instance->CFR;
+
+ /* Clear WDGTB[1:0] and W[6:0] bits */
+ tmp &= ((uint32_t)~(WWDG_CFR_WDGTB | WWDG_CFR_W));
+
+ /* Prepare the WWDG Prescaler and Window parameters */
+ tmp |= hwwdg->Init.Prescaler | hwwdg->Init.Window;
+
+ /* Write to WWDG CFR */
+ hwwdg->Instance->CFR = tmp;
+
+ /* Set WWDG Counter */
+ /* Get the CR register value */
+ tmp = hwwdg->Instance->CR;
+
+ /* Clear T[6:0] bits */
+ tmp &= ((uint32_t)~(WWDG_CR_T));
+
+ /* Prepare the WWDG Counter parameter */
+ tmp |= (hwwdg->Init.Counter);
+
+ /* Write to WWDG CR */
+ hwwdg->Instance->CR = tmp;
+
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_READY;
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the WWDG peripheral.
+ * @param hwwdg: WWDG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg)
+{
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_BUSY;
+
+ /* DeInit the low level hardware */
+ HAL_WWDG_MspDeInit(hwwdg);
+
+ /* Reset WWDG Control register */
+ hwwdg->Instance->CR = (uint32_t)0x0000007F;
+
+ /* Reset WWDG Configuration register */
+ hwwdg->Instance->CFR = (uint32_t)0x0000007F;
+
+ /* Reset WWDG Status register */
+ hwwdg->Instance->SR = 0;
+
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_RESET;
+
+ /* Release Lock */
+ __HAL_UNLOCK(hwwdg);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the WWDG MSP.
+ * @param hwwdg: WWDG handle
+ * @retval None
+ */
+__weak void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_WWDG_MspInit could be implemented in the user file
+ */
+}
+
+/**
+ * @brief DeInitializes the WWDG MSP.
+ * @param hwwdg: WWDG handle
+ * @retval None
+ */
+__weak void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_WWDG_MspDeInit could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup WWDG_Group2 IO operation functions
+ * @brief IO operation functions
+ *
+@verbatim
+ ==============================================================================
+ ##### IO operation functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Start the WWDG.
+ (+) Refresh the WWDG.
+ (+) Handle WWDG interrupt request.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Starts the WWDG.
+ * @param hwwdg: WWDG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg)
+{
+ /* Process Locked */
+ __HAL_LOCK(hwwdg);
+
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_BUSY;
+
+ /* Enable the peripheral */
+ __HAL_WWDG_ENABLE(hwwdg);
+
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hwwdg);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Starts the WWDG with interrupt enabled.
+ * @param hwwdg: WWDG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg)
+{
+ /* Process Locked */
+ __HAL_LOCK(hwwdg);
+
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_BUSY;
+
+ /* Enable the Early Wakeup Interrupt */
+ __HAL_WWDG_ENABLE_IT(WWDG_IT_EWI);
+
+ /* Enable the peripheral */
+ __HAL_WWDG_ENABLE(hwwdg);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Refreshes the WWDG.
+ * @param hwwdg: WWDG handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter)
+{
+ /* Process Locked */
+ __HAL_LOCK(hwwdg);
+
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_BUSY;
+
+ /* Check the parameters */
+ assert_param(IS_WWDG_COUNTER(Counter));
+
+ /* Write to WWDG CR the WWDG Counter value to refresh with */
+ MODIFY_REG(hwwdg->Instance->CR, WWDG_CR_T, Counter);
+
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_READY;
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hwwdg);
+
+ /* Return function status */
+ return HAL_OK;
+}
+
+/**
+ * @brief Handles WWDG interrupt request.
+ * @note The Early Wakeup Interrupt (EWI) can be used if specific safety operations
+ * or data logging must be performed before the actual reset is generated.
+ * The EWI interrupt is enabled using __HAL_WWDG_ENABLE_IT() macro.
+ * When the downcounter reaches the value 0x40, and EWI interrupt is
+ * generated and the corresponding Interrupt Service Routine (ISR) can
+ * be used to trigger specific actions (such as communications or data
+ * logging), before resetting the device.
+ * @param hwwdg: WWDG handle
+ * @retval None
+ */
+void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg)
+{
+ /* WWDG Early Wakeup Interrupt occurred */
+ if(__HAL_WWDG_GET_FLAG(hwwdg, WWDG_FLAG_EWIF) != RESET)
+ {
+ /* Early Wakeup callback */
+ HAL_WWDG_WakeupCallback(hwwdg);
+
+ /* Change WWDG peripheral state */
+ hwwdg->State = HAL_WWDG_STATE_READY;
+
+ /* Clear the WWDG Data Ready flag */
+ __HAL_WWDG_CLEAR_FLAG(hwwdg, WWDG_FLAG_EWIF);
+
+ /* Process Unlocked */
+ __HAL_UNLOCK(hwwdg);
+ }
+}
+
+/**
+ * @brief Early Wakeup WWDG callback.
+ * @param hwwdg: WWDG handle
+ * @retval None
+ */
+__weak void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg)
+{
+ /* NOTE: This function Should not be modified, when the callback is needed,
+ the HAL_WWDG_WakeupCallback could be implemented in the user file
+ */
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup WWDG_Group3 Peripheral State functions
+ * @brief Peripheral State functions.
+ *
+@verbatim
+ ==============================================================================
+ ##### Peripheral State functions #####
+ ==============================================================================
+ [..]
+ This subsection permits to get in run-time the status of the peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Returns the WWDG state.
+ * @param hwwdg: WWDG handle
+ * @retval HAL state
+ */
+HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg)
+{
+ return hwwdg->State;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* HAL_WWDG_MODULE_ENABLED */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_fmc.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_fmc.c
new file mode 100644
index 0000000..536659e
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_fmc.c
@@ -0,0 +1,1273 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_ll_fmc.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief FMC Low Layer HAL module driver.
+ *
+ * This file provides firmware functions to manage the following
+ * functionalities of the Flexible Memory Controller (FMC) peripheral memories:
+ * + Initialization/de-initialization functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### FMC peripheral features #####
+ ==============================================================================
+ [..] The Flexible memory controller (FMC) includes three memory controllers:
+ (+) The NOR/PSRAM memory controller
+ (+) The NAND/PC Card memory controller
+ (+) The Synchronous DRAM (SDRAM) controller
+
+ [..] The FMC functional block makes the interface with synchronous and asynchronous static
+ memories, SDRAM memories, and 16-bit PC memory cards. Its main purposes are:
+ (+) to translate AHB transactions into the appropriate external device protocol
+ (+) to meet the access time requirements of the external memory devices
+
+ [..] All external memories share the addresses, data and control signals with the controller.
+ Each external device is accessed by means of a unique Chip Select. The FMC performs
+ only one access at a time to an external device.
+ The main features of the FMC controller are the following:
+ (+) Interface with static-memory mapped devices including:
+ (++) Static random access memory (SRAM)
+ (++) Read-only memory (ROM)
+ (++) NOR Flash memory/OneNAND Flash memory
+ (++) PSRAM (4 memory banks)
+ (++) 16-bit PC Card compatible devices
+ (++) Two banks of NAND Flash memory with ECC hardware to check up to 8 Kbytes of
+ data
+ (+) Interface with synchronous DRAM (SDRAM) memories
+ (+) Independent Chip Select control for each memory bank
+ (+) Independent configuration for each memory bank
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup FMC
+ * @brief FMC driver modules
+ * @{
+ */
+
+#if defined (HAL_SRAM_MODULE_ENABLED) || defined(HAL_NOR_MODULE_ENABLED) || defined(HAL_NAND_MODULE_ENABLED) || defined(HAL_PCCARD_MODULE_ENABLED) || defined(HAL_SDRAM_MODULE_ENABLED)
+
+#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup FMC_Private_Functions
+ * @{
+ */
+
+/** @defgroup FMC_NORSRAM Controller functions
+ * @brief NORSRAM Controller functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use NORSRAM device driver #####
+ ==============================================================================
+
+ [..]
+ This driver contains a set of APIs to interface with the FMC NORSRAM banks in order
+ to run the NORSRAM external devices.
+
+ (+) FMC NORSRAM bank reset using the function FMC_NORSRAM_DeInit()
+ (+) FMC NORSRAM bank control configuration using the function FMC_NORSRAM_Init()
+ (+) FMC NORSRAM bank timing configuration using the function FMC_NORSRAM_Timing_Init()
+ (+) FMC NORSRAM bank extended timing configuration using the function
+ FMC_NORSRAM_Extended_Timing_Init()
+ (+) FMC NORSRAM bank enable/disable write operation using the functions
+ FMC_NORSRAM_WriteOperation_Enable()/FMC_NORSRAM_WriteOperation_Disable()
+
+
+@endverbatim
+ * @{
+ */
+
+/** @defgroup HAL_FMC_NORSRAM_Group1 Initialization/de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### Initialization and de_initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the FMC NORSRAM interface
+ (+) De-initialize the FMC NORSRAM interface
+ (+) Configure the FMC clock and associated GPIOs
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initialize the FMC_NORSRAM device according to the specified
+ * control parameters in the FMC_NORSRAM_InitTypeDef
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Init: Pointer to NORSRAM Initialization structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NORSRAM_Init(FMC_NORSRAM_TypeDef *Device, FMC_NORSRAM_InitTypeDef* Init)
+{
+ uint32_t tmpr = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_NORSRAM_DEVICE(Device));
+ assert_param(IS_FMC_NORSRAM_BANK(Init->NSBank));
+ assert_param(IS_FMC_MUX(Init->DataAddressMux));
+ assert_param(IS_FMC_MEMORY(Init->MemoryType));
+ assert_param(IS_FMC_NORSRAM_MEMORY_WIDTH(Init->MemoryDataWidth));
+ assert_param(IS_FMC_BURSTMODE(Init->BurstAccessMode));
+ assert_param(IS_FMC_WAIT_POLARITY(Init->WaitSignalPolarity));
+ assert_param(IS_FMC_WRAP_MODE(Init->WrapMode));
+ assert_param(IS_FMC_WAIT_SIGNAL_ACTIVE(Init->WaitSignalActive));
+ assert_param(IS_FMC_WRITE_OPERATION(Init->WriteOperation));
+ assert_param(IS_FMC_WAITE_SIGNAL(Init->WaitSignal));
+ assert_param(IS_FMC_EXTENDED_MODE(Init->ExtendedMode));
+ assert_param(IS_FMC_ASYNWAIT(Init->AsynchronousWait));
+ assert_param(IS_FMC_WRITE_BURST(Init->WriteBurst));
+ assert_param(IS_FMC_CONTINOUS_CLOCK(Init->ContinuousClock));
+
+ /* Set NORSRAM device control parameters */
+ tmpr = (uint32_t)(Init->DataAddressMux |\
+ Init->MemoryType |\
+ Init->MemoryDataWidth |\
+ Init->BurstAccessMode |\
+ Init->WaitSignalPolarity |\
+ Init->WrapMode |\
+ Init->WaitSignalActive |\
+ Init->WriteOperation |\
+ Init->WaitSignal |\
+ Init->ExtendedMode |\
+ Init->AsynchronousWait |\
+ Init->WriteBurst |\
+ Init->ContinuousClock
+ );
+
+ if(Init->MemoryType == FMC_MEMORY_TYPE_NOR)
+ {
+ tmpr |= (uint32_t)FMC_NORSRAM_FLASH_ACCESS_ENABLE;
+ }
+
+ Device->BTCR[Init->NSBank] = tmpr;
+
+ /* Configure synchronous mode when Continuous clock is enabled for bank2..4 */
+ if((Init->ContinuousClock == FMC_CONTINUOUS_CLOCK_SYNC_ASYNC) && (Init->NSBank != FMC_NORSRAM_BANK1))
+ {
+ Init->BurstAccessMode = FMC_BURST_ACCESS_MODE_ENABLE;
+ Device->BTCR[FMC_NORSRAM_BANK1] |= (uint32_t)(Init->BurstAccessMode |\
+ Init->ContinuousClock);
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief DeInitialize the FMC_NORSRAM peripheral
+ * @param Device: Pointer to NORSRAM device instance
+ * @param ExDevice: Pointer to NORSRAM extended mode device instance
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NORSRAM_DeInit(FMC_NORSRAM_TypeDef *Device, FMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_NORSRAM_DEVICE(Device));
+ assert_param(IS_FMC_NORSRAM_EXTENDED_DEVICE(ExDevice));
+ assert_param(IS_FMC_NORSRAM_BANK(Bank));
+
+ /* Disable the FMC_NORSRAM device */
+ __FMC_NORSRAM_DISABLE(Device, Bank);
+
+ /* De-initialize the FMC_NORSRAM device */
+ /* FMC_NORSRAM_BANK1 */
+ if(Bank == FMC_NORSRAM_BANK1)
+ {
+ Device->BTCR[Bank] = 0x000030DB;
+ }
+ /* FMC_NORSRAM_BANK2, FMC_NORSRAM_BANK3 or FMC_NORSRAM_BANK4 */
+ else
+ {
+ Device->BTCR[Bank] = 0x000030D2;
+ }
+
+ Device->BTCR[Bank + 1] = 0x0FFFFFFF;
+ ExDevice->BWTR[Bank] = 0x0FFFFFFF;
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Initialize the FMC_NORSRAM Timing according to the specified
+ * parameters in the FMC_NORSRAM_TimingTypeDef
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Timing: Pointer to NORSRAM Timing structure
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NORSRAM_Timing_Init(FMC_NORSRAM_TypeDef *Device, FMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank)
+{
+ uint32_t tmpr = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_NORSRAM_DEVICE(Device));
+ assert_param(IS_FMC_ADDRESS_SETUP_TIME(Timing->AddressSetupTime));
+ assert_param(IS_FMC_ADDRESS_HOLD_TIME(Timing->AddressHoldTime));
+ assert_param(IS_FMC_DATASETUP_TIME(Timing->DataSetupTime));
+ assert_param(IS_FMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration));
+ assert_param(IS_FMC_CLK_DIV(Timing->CLKDivision));
+ assert_param(IS_FMC_DATA_LATENCY(Timing->DataLatency));
+ assert_param(IS_FMC_ACCESS_MODE(Timing->AccessMode));
+ assert_param(IS_FMC_NORSRAM_BANK(Bank));
+
+ /* Set FMC_NORSRAM device timing parameters */
+ tmpr = (uint32_t)(Timing->AddressSetupTime |\
+ ((Timing->AddressHoldTime) << 4) |\
+ ((Timing->DataSetupTime) << 8) |\
+ ((Timing->BusTurnAroundDuration) << 16) |\
+ (((Timing->CLKDivision)-1) << 20) |\
+ (((Timing->DataLatency)-2) << 24) |\
+ (Timing->AccessMode)
+ );
+
+ Device->BTCR[Bank + 1] = tmpr;
+
+ /* Configure Clock division value (in NORSRAM bank 1) when continuous clock is enabled */
+ if(HAL_IS_BIT_SET(Device->BTCR[FMC_NORSRAM_BANK1], FMC_BCR1_CCLKEN))
+ {
+ tmpr = (uint32_t)(Device->BTCR[FMC_NORSRAM_BANK1 + 1] & ~(((uint32_t)0x0F) << 20));
+ tmpr |= (uint32_t)(((Timing->CLKDivision)-1) << 20);
+ Device->BTCR[FMC_NORSRAM_BANK1 + 1] = tmpr;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initialize the FMC_NORSRAM Extended mode Timing according to the specified
+ * parameters in the FMC_NORSRAM_TimingTypeDef
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Timing: Pointer to NORSRAM Timing structure
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NORSRAM_Extended_Timing_Init(FMC_NORSRAM_EXTENDED_TypeDef *Device, FMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, uint32_t ExtendedMode)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_EXTENDED_MODE(ExtendedMode));
+
+ /* Set NORSRAM device timing register for write configuration, if extended mode is used */
+ if(ExtendedMode == FMC_EXTENDED_MODE_ENABLE)
+ {
+ /* Check the parameters */
+ assert_param(IS_FMC_NORSRAM_EXTENDED_DEVICE(Device));
+ assert_param(IS_FMC_ADDRESS_SETUP_TIME(Timing->AddressSetupTime));
+ assert_param(IS_FMC_ADDRESS_HOLD_TIME(Timing->AddressHoldTime));
+ assert_param(IS_FMC_DATASETUP_TIME(Timing->DataSetupTime));
+ assert_param(IS_FMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration));
+ assert_param(IS_FMC_CLK_DIV(Timing->CLKDivision));
+ assert_param(IS_FMC_DATA_LATENCY(Timing->DataLatency));
+ assert_param(IS_FMC_ACCESS_MODE(Timing->AccessMode));
+ assert_param(IS_FMC_NORSRAM_BANK(Bank));
+
+ Device->BWTR[Bank] = (uint32_t)(Timing->AddressSetupTime |\
+ ((Timing->AddressHoldTime) << 4) |\
+ ((Timing->DataSetupTime) << 8) |\
+ ((Timing->BusTurnAroundDuration) << 16) |\
+ (((Timing->CLKDivision)-1) << 20) |\
+ (((Timing->DataLatency)-2) << 24) |\
+ (Timing->AccessMode));
+ }
+ else
+ {
+ Device->BWTR[Bank] = 0x0FFFFFFF;
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @}
+ */
+
+
+/** @defgroup HAL_FMC_NORSRAM_Group3 Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### FMC_NORSRAM Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control dynamically
+ the FMC NORSRAM interface.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables dynamically FMC_NORSRAM write operation.
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NORSRAM_WriteOperation_Enable(FMC_NORSRAM_TypeDef *Device, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_NORSRAM_DEVICE(Device));
+ assert_param(IS_FMC_NORSRAM_BANK(Bank));
+
+ /* Enable write operation */
+ Device->BTCR[Bank] |= FMC_WRITE_OPERATION_ENABLE;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables dynamically FMC_NORSRAM write operation.
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NORSRAM_WriteOperation_Disable(FMC_NORSRAM_TypeDef *Device, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_NORSRAM_DEVICE(Device));
+ assert_param(IS_FMC_NORSRAM_BANK(Bank));
+
+ /* Disable write operation */
+ Device->BTCR[Bank] &= ~FMC_WRITE_OPERATION_ENABLE;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/** @defgroup FMC_PCCARD Controller functions
+ * @brief PCCARD Controller functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use NAND device driver #####
+ ==============================================================================
+ [..]
+ This driver contains a set of APIs to interface with the FMC NAND banks in order
+ to run the NAND external devices.
+
+ (+) FMC NAND bank reset using the function FMC_NAND_DeInit()
+ (+) FMC NAND bank control configuration using the function FMC_NAND_Init()
+ (+) FMC NAND bank common space timing configuration using the function
+ FMC_NAND_CommonSpace_Timing_Init()
+ (+) FMC NAND bank attribute space timing configuration using the function
+ FMC_NAND_AttributeSpace_Timing_Init()
+ (+) FMC NAND bank enable/disable ECC correction feature using the functions
+ FMC_NAND_ECC_Enable()/FMC_NAND_ECC_Disable()
+ (+) FMC NAND bank get ECC correction code using the function FMC_NAND_GetECC()
+
+@endverbatim
+ * @{
+ */
+
+/** @defgroup HAL_FMC_NAND_Group1 Initialization/de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de_initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the FMC NAND interface
+ (+) De-initialize the FMC NAND interface
+ (+) Configure the FMC clock and associated GPIOs
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the FMC_NAND device according to the specified
+ * control parameters in the FMC_NAND_HandleTypeDef
+ * @param Device: Pointer to NAND device instance
+ * @param Init: Pointer to NAND Initialization structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NAND_Init(FMC_NAND_TypeDef *Device, FMC_NAND_InitTypeDef *Init)
+{
+ uint32_t tmppcr = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_NAND_DEVICE(Device));
+ assert_param(IS_FMC_NAND_BANK(Init->NandBank));
+ assert_param(IS_FMC_WAIT_FEATURE(Init->Waitfeature));
+ assert_param(IS_FMC_NAND_MEMORY_WIDTH(Init->MemoryDataWidth));
+ assert_param(IS_FMC_ECC_STATE(Init->EccComputation));
+ assert_param(IS_FMC_ECCPAGE_SIZE(Init->ECCPageSize));
+ assert_param(IS_FMC_TCLR_TIME(Init->TCLRSetupTime));
+ assert_param(IS_FMC_TAR_TIME(Init->TARSetupTime));
+
+ /* Set NAND device control parameters */
+ tmppcr = (uint32_t)(Init->Waitfeature |\
+ FMC_PCR_MEMORY_TYPE_NAND |\
+ Init->MemoryDataWidth |\
+ Init->EccComputation |\
+ Init->ECCPageSize |\
+ ((Init->TCLRSetupTime) << 9) |\
+ ((Init->TARSetupTime) << 13)
+ );
+
+ if(Init->NandBank == FMC_NAND_BANK2)
+ {
+ /* NAND bank 2 registers configuration */
+ Device->PCR2 = tmppcr;
+ }
+ else
+ {
+ /* NAND bank 3 registers configuration */
+ Device->PCR3 = tmppcr;
+ }
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Initializes the FMC_NAND Common space Timing according to the specified
+ * parameters in the FMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to NAND device instance
+ * @param Timing: Pointer to NAND timing structure
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NAND_CommonSpace_Timing_Init(FMC_NAND_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank)
+{
+ uint32_t tmppmem = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_NAND_DEVICE(Device));
+ assert_param(IS_FMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FMC_HIZ_TIME(Timing->HiZSetupTime));
+ assert_param(IS_FMC_NAND_BANK(Bank));
+
+ /* Set FMC_NAND device timing parameters */
+ tmppmem = (uint32_t)(Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ ((Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ if(Bank == FMC_NAND_BANK2)
+ {
+ /* NAND bank 2 registers configuration */
+ Device->PMEM2 = tmppmem;
+ }
+ else
+ {
+ /* NAND bank 3 registers configuration */
+ Device->PMEM3 = tmppmem;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the FMC_NAND Attribute space Timing according to the specified
+ * parameters in the FMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to NAND device instance
+ * @param Timing: Pointer to NAND timing structure
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NAND_AttributeSpace_Timing_Init(FMC_NAND_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank)
+{
+ uint32_t tmppatt = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_NAND_DEVICE(Device));
+ assert_param(IS_FMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FMC_HIZ_TIME(Timing->HiZSetupTime));
+ assert_param(IS_FMC_NAND_BANK(Bank));
+
+ /* Set FMC_NAND device timing parameters */
+ tmppatt = (uint32_t)(Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ ((Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ if(Bank == FMC_NAND_BANK2)
+ {
+ /* NAND bank 2 registers configuration */
+ Device->PATT2 = tmppatt;
+ }
+ else
+ {
+ /* NAND bank 3 registers configuration */
+ Device->PATT3 = tmppatt;
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief DeInitializes the FMC_NAND device
+ * @param Device: Pointer to NAND device instance
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NAND_DeInit(FMC_NAND_TypeDef *Device, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_NAND_DEVICE(Device));
+ assert_param(IS_FMC_NAND_BANK(Bank));
+
+ /* Disable the NAND Bank */
+ __FMC_NAND_DISABLE(Device, Bank);
+
+ /* De-initialize the NAND Bank */
+ if(Bank == FMC_NAND_BANK2)
+ {
+ /* Set the FMC_NAND_BANK2 registers to their reset values */
+ Device->PCR2 = 0x00000018;
+ Device->SR2 = 0x00000040;
+ Device->PMEM2 = 0xFCFCFCFC;
+ Device->PATT2 = 0xFCFCFCFC;
+ }
+ /* FMC_Bank3_NAND */
+ else
+ {
+ /* Set the FMC_NAND_BANK3 registers to their reset values */
+ Device->PCR3 = 0x00000018;
+ Device->SR3 = 0x00000040;
+ Device->PMEM3 = 0xFCFCFCFC;
+ Device->PATT3 = 0xFCFCFCFC;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+
+/** @defgroup HAL_FMC_NAND_Group3 Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### FMC_NAND Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control dynamically
+ the FMC NAND interface.
+
+@endverbatim
+ * @{
+ */
+
+
+/**
+ * @brief Enables dynamically FMC_NAND ECC feature.
+ * @param Device: Pointer to NAND device instance
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NAND_ECC_Enable(FMC_NAND_TypeDef *Device, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_NAND_DEVICE(Device));
+ assert_param(IS_FMC_NAND_BANK(Bank));
+
+ /* Enable ECC feature */
+ if(Bank == FMC_NAND_BANK2)
+ {
+ Device->PCR2 |= FMC_PCR2_ECCEN;
+ }
+ else
+ {
+ Device->PCR3 |= FMC_PCR3_ECCEN;
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Disables dynamically FMC_NAND ECC feature.
+ * @param Device: Pointer to NAND device instance
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NAND_ECC_Disable(FMC_NAND_TypeDef *Device, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_NAND_DEVICE(Device));
+ assert_param(IS_FMC_NAND_BANK(Bank));
+
+ /* Disable ECC feature */
+ if(Bank == FMC_NAND_BANK2)
+ {
+ Device->PCR2 &= ~FMC_PCR2_ECCEN;
+ }
+ else
+ {
+ Device->PCR3 &= ~FMC_PCR3_ECCEN;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables dynamically FMC_NAND ECC feature.
+ * @param Device: Pointer to NAND device instance
+ * @param ECCval: Pointer to ECC value
+ * @param Bank: NAND bank number
+ * @param Timeout: Timeout wait value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_NAND_GetECC(FMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_NAND_DEVICE(Device));
+ assert_param(IS_FMC_NAND_BANK(Bank));
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Wait untill FIFO is empty */
+ while(__FMC_NAND_GET_FLAG(Device, Bank, FMC_FLAG_FEMPT))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ if(Bank == FMC_NAND_BANK2)
+ {
+ /* Get the ECCR2 register value */
+ *ECCval = (uint32_t)Device->ECCR2;
+ }
+ else
+ {
+ /* Get the ECCR3 register value */
+ *ECCval = (uint32_t)Device->ECCR3;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/** @defgroup FMC_PCCARD Controller functions
+ * @brief PCCARD Controller functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use PCCARD device driver #####
+ ==============================================================================
+ [..]
+ This driver contains a set of APIs to interface with the FMC PCCARD bank in order
+ to run the PCCARD/compact flash external devices.
+
+ (+) FMC PCCARD bank reset using the function FMC_PCCARD_DeInit()
+ (+) FMC PCCARD bank control configuration using the function FMC_PCCARD_Init()
+ (+) FMC PCCARD bank common space timing configuration using the function
+ FMC_PCCARD_CommonSpace_Timing_Init()
+ (+) FMC PCCARD bank attribute space timing configuration using the function
+ FMC_PCCARD_AttributeSpace_Timing_Init()
+ (+) FMC PCCARD bank IO space timing configuration using the function
+ FMC_PCCARD_IOSpace_Timing_Init()
+
+
+@endverbatim
+ * @{
+ */
+
+/** @defgroup HAL_FMC_PCCARD_Group1 Initialization/de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de_initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the FMC PCCARD interface
+ (+) De-initialize the FMC PCCARD interface
+ (+) Configure the FMC clock and associated GPIOs
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the FMC_PCCARD device according to the specified
+ * control parameters in the FMC_PCCARD_HandleTypeDef
+ * @param Device: Pointer to PCCARD device instance
+ * @param Init: Pointer to PCCARD Initialization structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_PCCARD_Init(FMC_PCCARD_TypeDef *Device, FMC_PCCARD_InitTypeDef *Init)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_PCCARD_DEVICE(Device));
+ assert_param(IS_FMC_WAIT_FEATURE(Init->Waitfeature));
+ assert_param(IS_FMC_TCLR_TIME(Init->TCLRSetupTime));
+ assert_param(IS_FMC_TAR_TIME(Init->TARSetupTime));
+
+ /* Set FMC_PCCARD device control parameters */
+ Device->PCR4 = (uint32_t)(Init->Waitfeature |\
+ FMC_NAND_PCC_MEM_BUS_WIDTH_16 |\
+ (Init->TCLRSetupTime << 9) |\
+ (Init->TARSetupTime << 13));
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Initializes the FMC_PCCARD Common space Timing according to the specified
+ * parameters in the FMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to PCCARD device instance
+ * @param Timing: Pointer to PCCARD timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_PCCARD_CommonSpace_Timing_Init(FMC_PCCARD_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_PCCARD_DEVICE(Device));
+ assert_param(IS_FMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FMC_HIZ_TIME(Timing->HiZSetupTime));
+
+ /* Set PCCARD timing parameters */
+ Device->PMEM4 = (uint32_t)((Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ (Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the FMC_PCCARD Attribute space Timing according to the specified
+ * parameters in the FMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to PCCARD device instance
+ * @param Timing: Pointer to PCCARD timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_PCCARD_AttributeSpace_Timing_Init(FMC_PCCARD_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_PCCARD_DEVICE(Device));
+ assert_param(IS_FMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FMC_HIZ_TIME(Timing->HiZSetupTime));
+
+ /* Set PCCARD timing parameters */
+ Device->PATT4 = (uint32_t)((Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ (Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the FMC_PCCARD IO space Timing according to the specified
+ * parameters in the FMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to PCCARD device instance
+ * @param Timing: Pointer to PCCARD timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_PCCARD_IOSpace_Timing_Init(FMC_PCCARD_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_PCCARD_DEVICE(Device));
+ assert_param(IS_FMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FMC_HIZ_TIME(Timing->HiZSetupTime));
+
+ /* Set FMC_PCCARD device timing parameters */
+ Device->PIO4 = (uint32_t)((Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ (Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the FMC_PCCARD device
+ * @param Device: Pointer to PCCARD device instance
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_PCCARD_DeInit(FMC_PCCARD_TypeDef *Device)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_PCCARD_DEVICE(Device));
+
+ /* Disable the FMC_PCCARD device */
+ __FMC_PCCARD_DISABLE(Device);
+
+ /* De-initialize the FMC_PCCARD device */
+ Device->PCR4 = 0x00000018;
+ Device->SR4 = 0x00000000;
+ Device->PMEM4 = 0xFCFCFCFC;
+ Device->PATT4 = 0xFCFCFCFC;
+ Device->PIO4 = 0xFCFCFCFC;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+
+/** @defgroup FMC_SDRAM Controller functions
+ * @brief SDRAM Controller functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use SDRAM device driver #####
+ ==============================================================================
+ [..]
+ This driver contains a set of APIs to interface with the FMC SDRAM banks in order
+ to run the SDRAM external devices.
+
+ (+) FMC SDRAM bank reset using the function FMC_SDRAM_DeInit()
+ (+) FMC SDRAM bank control configuration using the function FMC_SDRAM_Init()
+ (+) FMC SDRAM bank timing configuration using the function FMC_SDRAM_Timing_Init()
+ (+) FMC SDRAM bank enable/disable write operation using the functions
+ FMC_SDRAM_WriteOperation_Enable()/FMC_SDRAM_WriteOperation_Disable()
+ (+) FMC SDRAM bank send command using the function FMC_SDRAM_SendCommand()
+
+@endverbatim
+ * @{
+ */
+
+/** @defgroup HAL_FMC_SDRAM_Group1 Initialization/de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de_initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the FMC SDRAM interface
+ (+) De-initialize the FMC SDRAM interface
+ (+) Configure the FMC clock and associated GPIOs
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the FMC_SDRAM device according to the specified
+ * control parameters in the FMC_SDRAM_InitTypeDef
+ * @param Device: Pointer to SDRAM device instance
+ * @param Init: Pointer to SDRAM Initialization structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_SDRAM_Init(FMC_SDRAM_TypeDef *Device, FMC_SDRAM_InitTypeDef *Init)
+{
+ uint32_t tmpr1 = 0;
+ uint32_t tmpr2 = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_SDRAM_DEVICE(Device));
+ assert_param(IS_FMC_SDRAM_BANK(Init->SDBank));
+ assert_param(IS_FMC_COLUMNBITS_NUMBER(Init->ColumnBitsNumber));
+ assert_param(IS_FMC_ROWBITS_NUMBER(Init->RowBitsNumber));
+ assert_param(IS_FMC_SDMEMORY_WIDTH(Init->MemoryDataWidth));
+ assert_param(IS_FMC_INTERNALBANK_NUMBER(Init->InternalBankNumber));
+ assert_param(IS_FMC_CAS_LATENCY(Init->CASLatency));
+ assert_param(IS_FMC_WRITE_PROTECTION(Init->WriteProtection));
+ assert_param(IS_FMC_SDCLOCK_PERIOD(Init->SDClockPeriod));
+ assert_param(IS_FMC_READ_BURST(Init->ReadBurst));
+ assert_param(IS_FMC_READPIPE_DELAY(Init->ReadPipeDelay));
+
+ /* Set SDRAM bank configuration parameters */
+ if (Init->SDBank != FMC_SDRAM_BANK2)
+ {
+ Device->SDCR[FMC_SDRAM_BANK1] = (uint32_t)(Init->ColumnBitsNumber |\
+ Init->RowBitsNumber |\
+ Init->MemoryDataWidth |\
+ Init->InternalBankNumber |\
+ Init->CASLatency |\
+ Init->WriteProtection |\
+ Init->SDClockPeriod |\
+ Init->ReadBurst |\
+ Init->ReadPipeDelay
+ );
+ }
+ else /* FMC_Bank2_SDRAM */
+ {
+ tmpr1 = (uint32_t)(Init->SDClockPeriod |\
+ Init->ReadBurst |\
+ Init->ReadPipeDelay
+ );
+
+ tmpr2 = (uint32_t)(Init->ColumnBitsNumber |\
+ Init->RowBitsNumber |\
+ Init->MemoryDataWidth |\
+ Init->InternalBankNumber |\
+ Init->CASLatency |\
+ Init->WriteProtection
+ );
+
+ Device->SDCR[FMC_SDRAM_BANK1] = tmpr1;
+ Device->SDCR[FMC_SDRAM_BANK2] = tmpr2;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the FMC_SDRAM device timing according to the specified
+ * parameters in the FMC_SDRAM_TimingTypeDef
+ * @param Device: Pointer to SDRAM device instance
+ * @param Timing: Pointer to SDRAM Timing structure
+ * @param Bank: SDRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_SDRAM_Timing_Init(FMC_SDRAM_TypeDef *Device, FMC_SDRAM_TimingTypeDef *Timing, uint32_t Bank)
+{
+ uint32_t tmpr1 = 0;
+ uint32_t tmpr2 = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_SDRAM_DEVICE(Device));
+ assert_param(IS_FMC_LOADTOACTIVE_DELAY(Timing->LoadToActiveDelay));
+ assert_param(IS_FMC_EXITSELFREFRESH_DELAY(Timing->ExitSelfRefreshDelay));
+ assert_param(IS_FMC_SELFREFRESH_TIME(Timing->SelfRefreshTime));
+ assert_param(IS_FMC_ROWCYCLE_DELAY(Timing->RowCycleDelay));
+ assert_param(IS_FMC_WRITE_RECOVERY_TIME(Timing->WriteRecoveryTime));
+ assert_param(IS_FMC_RP_DELAY(Timing->RPDelay));
+ assert_param(IS_FMC_RCD_DELAY(Timing->RCDDelay));
+ assert_param(IS_FMC_SDRAM_BANK(Bank));
+
+ /* Set SDRAM device timing parameters */
+ if (Bank != FMC_SDRAM_BANK2)
+ {
+ Device->SDTR[FMC_SDRAM_BANK1] = (uint32_t)(((Timing->LoadToActiveDelay)-1) |\
+ (((Timing->ExitSelfRefreshDelay)-1) << 4) |\
+ (((Timing->SelfRefreshTime)-1) << 8) |\
+ (((Timing->RowCycleDelay)-1) << 12) |\
+ (((Timing->WriteRecoveryTime)-1) <<16) |\
+ (((Timing->RPDelay)-1) << 20) |\
+ (((Timing->RCDDelay)-1) << 24)
+ );
+ }
+ else /* FMC_Bank2_SDRAM */
+ {
+
+ tmpr1 = (uint32_t)(((Timing->LoadToActiveDelay)-1) |\
+ (((Timing->ExitSelfRefreshDelay)-1) << 4) |\
+ (((Timing->SelfRefreshTime)-1) << 8) |\
+ (((Timing->WriteRecoveryTime)-1) <<16) |\
+ (((Timing->RCDDelay)-1) << 24)
+ );
+
+ tmpr2 = (uint32_t)((((Timing->RowCycleDelay)-1) << 12) |\
+ (((Timing->RPDelay)-1) << 20)
+ );
+
+ Device->SDTR[FMC_SDRAM_BANK2] = tmpr1;
+ Device->SDTR[FMC_SDRAM_BANK1] = tmpr2;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the FMC_SDRAM peripheral
+ * @param Device: Pointer to SDRAM device instance
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_SDRAM_DeInit(FMC_SDRAM_TypeDef *Device, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_SDRAM_DEVICE(Device));
+ assert_param(IS_FMC_SDRAM_BANK(Bank));
+
+ /* De-initialize the SDRAM device */
+ Device->SDCR[Bank] = 0x000002D0;
+ Device->SDTR[Bank] = 0x0FFFFFFF;
+ Device->SDCMR = 0x00000000;
+ Device->SDRTR = 0x00000000;
+ Device->SDSR = 0x00000000;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+
+/** @defgroup HAL_FMC_SDRAM_Group3 Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### FMC_SDRAM Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control dynamically
+ the FMC SDRAM interface.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables dynamically FMC_SDRAM write protection.
+ * @param Device: Pointer to SDRAM device instance
+ * @param Bank: SDRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_SDRAM_WriteProtection_Enable(FMC_SDRAM_TypeDef *Device, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_SDRAM_DEVICE(Device));
+ assert_param(IS_FMC_SDRAM_BANK(Bank));
+
+ /* Enable write protection */
+ Device->SDCR[Bank] |= FMC_SDRAM_WRITE_PROTECTION_ENABLE;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables dynamically FMC_SDRAM write protection.
+ * @param hsdram: FMC_SDRAM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FMC_SDRAM_WriteProtection_Disable(FMC_SDRAM_TypeDef *Device, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_SDRAM_DEVICE(Device));
+ assert_param(IS_FMC_SDRAM_BANK(Bank));
+
+ /* Disable write protection */
+ Device->SDCR[Bank] &= ~FMC_SDRAM_WRITE_PROTECTION_ENABLE;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Send Command to the FMC SDRAM bank
+ * @param Device: Pointer to SDRAM device instance
+ * @param Command: Pointer to SDRAM command structure
+ * @param Timing: Pointer to SDRAM Timing structure
+ * @param Timeout: Timeout wait value
+ * @retval HAL state
+ */
+HAL_StatusTypeDef FMC_SDRAM_SendCommand(FMC_SDRAM_TypeDef *Device, FMC_SDRAM_CommandTypeDef *Command, uint32_t Timeout)
+{
+ __IO uint32_t tmpr = 0;
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_SDRAM_DEVICE(Device));
+ assert_param(IS_FMC_COMMAND_MODE(Command->CommandMode));
+ assert_param(IS_FMC_COMMAND_TARGET(Command->CommandTarget));
+ assert_param(IS_FMC_AUTOREFRESH_NUMBER(Command->AutoRefreshNumber));
+ assert_param(IS_FMC_MODE_REGISTER(Command->ModeRegisterDefinition));
+
+ /* Set command register */
+ tmpr = (uint32_t)((Command->CommandMode) |\
+ (Command->CommandTarget) |\
+ (((Command->AutoRefreshNumber)-1) << 5) |\
+ ((Command->ModeRegisterDefinition) << 9)
+ );
+
+ Device->SDCMR = tmpr;
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* wait until command is send */
+ while(HAL_IS_BIT_SET(Device->SDSR, FMC_SDSR_BUSY))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+
+ return HAL_ERROR;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Program the SDRAM Memory Refresh rate.
+ * @param Device: Pointer to SDRAM device instance
+ * @param RefreshRate: The SDRAM refresh rate value.
+ * @retval HAL state
+ */
+HAL_StatusTypeDef FMC_SDRAM_ProgramRefreshRate(FMC_SDRAM_TypeDef *Device, uint32_t RefreshRate)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_SDRAM_DEVICE(Device));
+ assert_param(IS_FMC_REFRESH_RATE(RefreshRate));
+
+ /* Set the refresh rate in command register */
+ Device->SDRTR |= (RefreshRate<<1);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Set the Number of consecutive SDRAM Memory auto Refresh commands.
+ * @param Device: Pointer to SDRAM device instance
+ * @param AutoRefreshNumber: Specifies the auto Refresh number.
+ * @retval None
+ */
+HAL_StatusTypeDef FMC_SDRAM_SetAutoRefreshNumber(FMC_SDRAM_TypeDef *Device, uint32_t AutoRefreshNumber)
+{
+ /* Check the parameters */
+ assert_param(IS_FMC_SDRAM_DEVICE(Device));
+ assert_param(IS_FMC_AUTOREFRESH_NUMBER(AutoRefreshNumber));
+
+ /* Set the Auto-refresh number in command register */
+ Device->SDCMR |= (AutoRefreshNumber << 5);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Returns the indicated FMC SDRAM bank mode status.
+ * @param Device: Pointer to SDRAM device instance
+ * @param Bank: Defines the FMC SDRAM bank. This parameter can be
+ * FMC_Bank1_SDRAM or FMC_Bank2_SDRAM.
+ * @retval The FMC SDRAM bank mode status, could be on of the following values:
+ * FMC_SDRAM_NORMAL_MODE, FMC_SDRAM_SELF_REFRESH_MODE or
+ * FMC_SDRAM_POWER_DOWN_MODE.
+ */
+uint32_t FMC_SDRAM_GetModeStatus(FMC_SDRAM_TypeDef *Device, uint32_t Bank)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FMC_SDRAM_DEVICE(Device));
+ assert_param(IS_FMC_SDRAM_BANK(Bank));
+
+ /* Get the corresponding bank mode */
+ if(Bank == FMC_SDRAM_BANK1)
+ {
+ tmpreg = (uint32_t)(Device->SDSR & FMC_SDSR_MODES1);
+ }
+ else
+ {
+ tmpreg = ((uint32_t)(Device->SDSR & FMC_SDSR_MODES2) >> 2);
+ }
+
+ /* Return the mode status */
+ return tmpreg;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
+
+#endif /* HAL_FMC_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_fsmc.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_fsmc.c
new file mode 100644
index 0000000..21d5b75
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_fsmc.c
@@ -0,0 +1,856 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_ll_fsmc.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief FSMC Low Layer HAL module driver.
+ *
+ * This file provides firmware functions to manage the following
+ * functionalities of the Flexible Static Memory Controller (FSMC) peripheral memories:
+ * + Initialization/de-initialization functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### FSMC peripheral features #####
+ ==============================================================================
+ [..] The Flexible static memory controller (FSMC) includes two memory controllers:
+ (+) The NOR/PSRAM memory controller
+ (+) The NAND/PC Card memory controller
+
+ [..] The FSMC functional block makes the interface with synchronous and asynchronous static
+ memories, SDRAM memories, and 16-bit PC memory cards. Its main purposes are:
+ (+) to translate AHB transactions into the appropriate external device protocol.
+ (+) to meet the access time requirements of the external memory devices.
+
+ [..] All external memories share the addresses, data and control signals with the controller.
+ Each external device is accessed by means of a unique Chip Select. The FSMC performs
+ only one access at a time to an external device.
+ The main features of the FSMC controller are the following:
+ (+) Interface with static-memory mapped devices including:
+ (++) Static random access memory (SRAM).
+ (++) Read-only memory (ROM).
+ (++) NOR Flash memory/OneNAND Flash memory.
+ (++) PSRAM (4 memory banks).
+ (++) 16-bit PC Card compatible devices.
+ (++) Two banks of NAND Flash memory with ECC hardware to check up to 8 Kbytes of
+ data.
+ (+) Independent Chip Select control for each memory bank.
+ (+) Independent configuration for each memory bank.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup FSMC
+ * @brief FSMC driver modules
+ * @{
+ */
+
+#if defined (HAL_SRAM_MODULE_ENABLED) || defined(HAL_NOR_MODULE_ENABLED) || defined(HAL_NAND_MODULE_ENABLED) || defined(HAL_PCCARD_MODULE_ENABLED)
+
+#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup FSMC_Private_Functions
+ * @{
+ */
+
+/** @defgroup FSMC_NORSRAM Controller functions
+ * @brief NORSRAM Controller functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use NORSRAM device driver #####
+ ==============================================================================
+
+ [..]
+ This driver contains a set of APIs to interface with the FSMC NORSRAM banks in order
+ to run the NORSRAM external devices.
+
+ (+) FSMC NORSRAM bank reset using the function FSMC_NORSRAM_DeInit()
+ (+) FSMC NORSRAM bank control configuration using the function FSMC_NORSRAM_Init()
+ (+) FSMC NORSRAM bank timing configuration using the function FSMC_NORSRAM_Timing_Init()
+ (+) FSMC NORSRAM bank extended timing configuration using the function
+ FSMC_NORSRAM_Extended_Timing_Init()
+ (+) FSMC NORSRAM bank enable/disable write operation using the functions
+ FSMC_NORSRAM_WriteOperation_Enable()/FSMC_NORSRAM_WriteOperation_Disable()
+
+@endverbatim
+ * @{
+ */
+
+/** @defgroup HAL_FSMC_NORSRAM_Group1 Initialization/de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### Initialization and de_initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the FSMC NORSRAM interface
+ (+) De-initialize the FSMC NORSRAM interface
+ (+) Configure the FSMC clock and associated GPIOs
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initialize the FSMC_NORSRAM device according to the specified
+ * control parameters in the FSMC_NORSRAM_InitTypeDef
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Init: Pointer to NORSRAM Initialization structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_InitTypeDef* Init)
+{
+ uint32_t tmpr = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FSMC_NORSRAM_BANK(Init->NSBank));
+ assert_param(IS_FSMC_MUX(Init->DataAddressMux));
+ assert_param(IS_FSMC_MEMORY(Init->MemoryType));
+ assert_param(IS_FSMC_NORSRAM_MEMORY_WIDTH(Init->MemoryDataWidth));
+ assert_param(IS_FSMC_BURSTMODE(Init->BurstAccessMode));
+ assert_param(IS_FSMC_WAIT_POLARITY(Init->WaitSignalPolarity));
+ assert_param(IS_FSMC_WRAP_MODE(Init->WrapMode));
+ assert_param(IS_FSMC_WAIT_SIGNAL_ACTIVE(Init->WaitSignalActive));
+ assert_param(IS_FSMC_WRITE_OPERATION(Init->WriteOperation));
+ assert_param(IS_FSMC_WAITE_SIGNAL(Init->WaitSignal));
+ assert_param(IS_FSMC_EXTENDED_MODE(Init->ExtendedMode));
+ assert_param(IS_FSMC_ASYNWAIT(Init->AsynchronousWait));
+ assert_param(IS_FSMC_WRITE_BURST(Init->WriteBurst));
+
+ /* Set NORSRAM device control parameters */
+ tmpr = (uint32_t)(Init->DataAddressMux |\
+ Init->MemoryType |\
+ Init->MemoryDataWidth |\
+ Init->BurstAccessMode |\
+ Init->WaitSignalPolarity |\
+ Init->WrapMode |\
+ Init->WaitSignalActive |\
+ Init->WriteOperation |\
+ Init->WaitSignal |\
+ Init->ExtendedMode |\
+ Init->AsynchronousWait |\
+ Init->WriteBurst
+ );
+
+ if(Init->MemoryType == FSMC_MEMORY_TYPE_NOR)
+ {
+ tmpr |= (uint32_t)FSMC_NORSRAM_FLASH_ACCESS_ENABLE;
+ }
+
+ Device->BTCR[Init->NSBank] = tmpr;
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief DeInitialize the FSMC_NORSRAM peripheral
+ * @param Device: Pointer to NORSRAM device instance
+ * @param ExDevice: Pointer to NORSRAM extended mode device instance
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank)
+{
+ /* Check the parameters */
+ assert_param(IS_FSMC_NORSRAM_DEVICE(Device));
+ assert_param(IS_FSMC_NORSRAM_EXTENDED_DEVICE(ExDevice));
+
+ /* Disable the FSMC_NORSRAM device */
+ __FSMC_NORSRAM_DISABLE(Device, Bank);
+
+ /* De-initialize the FSMC_NORSRAM device */
+ /* FSMC_NORSRAM_BANK1 */
+ if(Bank == FSMC_NORSRAM_BANK1)
+ {
+ Device->BTCR[Bank] = 0x000030DB;
+ }
+ /* FSMC_NORSRAM_BANK2, FSMC_NORSRAM_BANK3 or FSMC_NORSRAM_BANK4 */
+ else
+ {
+ Device->BTCR[Bank] = 0x000030D2;
+ }
+
+ Device->BTCR[Bank + 1] = 0x0FFFFFFF;
+ ExDevice->BWTR[Bank] = 0x0FFFFFFF;
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Initialize the FSMC_NORSRAM Timing according to the specified
+ * parameters in the FSMC_NORSRAM_TimingTypeDef
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Timing: Pointer to NORSRAM Timing structure
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank)
+{
+ uint32_t tmpr = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FSMC_ADDRESS_SETUP_TIME(Timing->AddressSetupTime));
+ assert_param(IS_FSMC_ADDRESS_HOLD_TIME(Timing->AddressHoldTime));
+ assert_param(IS_FSMC_DATASETUP_TIME(Timing->DataSetupTime));
+ assert_param(IS_FSMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration));
+ assert_param(IS_FSMC_CLK_DIV(Timing->CLKDivision));
+ assert_param(IS_FSMC_DATA_LATENCY(Timing->DataLatency));
+ assert_param(IS_FSMC_ACCESS_MODE(Timing->AccessMode));
+
+ /* Set FSMC_NORSRAM device timing parameters */
+ tmpr = (uint32_t)(Timing->AddressSetupTime |\
+ ((Timing->AddressHoldTime) << 4) |\
+ ((Timing->DataSetupTime) << 8) |\
+ ((Timing->BusTurnAroundDuration) << 16) |\
+ (((Timing->CLKDivision)-1) << 20) |\
+ (((Timing->DataLatency)-2) << 24) |\
+ (Timing->AccessMode)
+ );
+
+ Device->BTCR[Bank + 1] = tmpr;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initialize the FSMC_NORSRAM Extended mode Timing according to the specified
+ * parameters in the FSMC_NORSRAM_TimingTypeDef
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Timing: Pointer to NORSRAM Timing structure
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NORSRAM_Extended_Timing_Init(FSMC_NORSRAM_EXTENDED_TypeDef *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, uint32_t ExtendedMode)
+{
+ /* Set NORSRAM device timing register for write configuration, if extended mode is used */
+ if(ExtendedMode == FSMC_EXTENDED_MODE_ENABLE)
+ {
+ /* Check the parameters */
+ assert_param(IS_FSMC_ADDRESS_SETUP_TIME(Timing->AddressSetupTime));
+ assert_param(IS_FSMC_ADDRESS_HOLD_TIME(Timing->AddressHoldTime));
+ assert_param(IS_FSMC_DATASETUP_TIME(Timing->DataSetupTime));
+ assert_param(IS_FSMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration));
+ assert_param(IS_FSMC_CLK_DIV(Timing->CLKDivision));
+ assert_param(IS_FSMC_DATA_LATENCY(Timing->DataLatency));
+ assert_param(IS_FSMC_ACCESS_MODE(Timing->AccessMode));
+
+ Device->BWTR[Bank] = (uint32_t)(Timing->AddressSetupTime |\
+ ((Timing->AddressHoldTime) << 4) |\
+ ((Timing->DataSetupTime) << 8) |\
+ ((Timing->BusTurnAroundDuration) << 16) |\
+ (((Timing->CLKDivision)-1) << 20) |\
+ (((Timing->DataLatency)-2) << 24) |\
+ (Timing->AccessMode));
+ }
+ else
+ {
+ Device->BWTR[Bank] = 0x0FFFFFFF;
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @}
+ */
+
+
+/** @defgroup HAL_FSMC_NORSRAM_Group3 Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### FSMC_NORSRAM Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control dynamically
+ the FSMC NORSRAM interface.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Enables dynamically FSMC_NORSRAM write operation.
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Enable(FSMC_NORSRAM_TypeDef *Device, uint32_t Bank)
+{
+ /* Enable write operation */
+ Device->BTCR[Bank] |= FSMC_WRITE_OPERATION_ENABLE;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables dynamically FSMC_NORSRAM write operation.
+ * @param Device: Pointer to NORSRAM device instance
+ * @param Bank: NORSRAM bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Device, uint32_t Bank)
+{
+ /* Disable write operation */
+ Device->BTCR[Bank] &= ~FSMC_WRITE_OPERATION_ENABLE;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/** @defgroup FSMC_PCCARD Controller functions
+ * @brief PCCARD Controller functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use NAND device driver #####
+ ==============================================================================
+ [..]
+ This driver contains a set of APIs to interface with the FSMC NAND banks in order
+ to run the NAND external devices.
+
+ (+) FSMC NAND bank reset using the function FSMC_NAND_DeInit()
+ (+) FSMC NAND bank control configuration using the function FSMC_NAND_Init()
+ (+) FSMC NAND bank common space timing configuration using the function
+ FSMC_NAND_CommonSpace_Timing_Init()
+ (+) FSMC NAND bank attribute space timing configuration using the function
+ FSMC_NAND_AttributeSpace_Timing_Init()
+ (+) FSMC NAND bank enable/disable ECC correction feature using the functions
+ FSMC_NAND_ECC_Enable()/FSMC_NAND_ECC_Disable()
+ (+) FSMC NAND bank get ECC correction code using the function FSMC_NAND_GetECC()
+
+@endverbatim
+ * @{
+ */
+
+/** @defgroup HAL_FSMC_NAND_Group1 Initialization/de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de_initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the FSMC NAND interface
+ (+) De-initialize the FSMC NAND interface
+ (+) Configure the FSMC clock and associated GPIOs
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the FSMC_NAND device according to the specified
+ * control parameters in the FSMC_NAND_HandleTypeDef
+ * @param Device: Pointer to NAND device instance
+ * @param Init: Pointer to NAND Initialization structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDef *Init)
+{
+ uint32_t tmppcr = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FSMC_NAND_BANK(Init->NandBank));
+ assert_param(IS_FSMC_WAIT_FEATURE(Init->Waitfeature));
+ assert_param(IS_FSMC_NAND_MEMORY_WIDTH(Init->MemoryDataWidth));
+ assert_param(IS_FSMC_ECC_STATE(Init->EccComputation));
+ assert_param(IS_FSMC_ECCPAGE_SIZE(Init->ECCPageSize));
+ assert_param(IS_FSMC_TCLR_TIME(Init->TCLRSetupTime));
+ assert_param(IS_FSMC_TAR_TIME(Init->TARSetupTime));
+
+ /* Set NAND device control parameters */
+ tmppcr = (uint32_t)(Init->Waitfeature |\
+ FSMC_PCR_MEMORY_TYPE_NAND |\
+ Init->MemoryDataWidth |\
+ Init->EccComputation |\
+ Init->ECCPageSize |\
+ ((Init->TCLRSetupTime) << 9) |\
+ ((Init->TARSetupTime) << 13)
+ );
+
+ if(Init->NandBank == FSMC_NAND_BANK2)
+ {
+ /* NAND bank 2 registers configuration */
+ Device->PCR2 = tmppcr;
+ }
+ else
+ {
+ /* NAND bank 3 registers configuration */
+ Device->PCR3 = tmppcr;
+ }
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Initializes the FSMC_NAND Common space Timing according to the specified
+ * parameters in the FSMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to NAND device instance
+ * @param Timing: Pointer to NAND timing structure
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank)
+{
+ uint32_t tmppmem = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FSMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FSMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FSMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FSMC_HIZ_TIME(Timing->HiZSetupTime));
+
+ /* Set FSMC_NAND device timing parameters */
+ tmppmem = (uint32_t)(Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ ((Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ if(Bank == FSMC_NAND_BANK2)
+ {
+ /* NAND bank 2 registers configuration */
+ Device->PMEM2 = tmppmem;
+ }
+ else
+ {
+ /* NAND bank 3 registers configuration */
+ Device->PMEM3 = tmppmem;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the FSMC_NAND Attribute space Timing according to the specified
+ * parameters in the FSMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to NAND device instance
+ * @param Timing: Pointer to NAND timing structure
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank)
+{
+ uint32_t tmppatt = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FSMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FSMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FSMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FSMC_HIZ_TIME(Timing->HiZSetupTime));
+
+ /* Set FSMC_NAND device timing parameters */
+ tmppatt = (uint32_t)(Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ ((Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ if(Bank == FSMC_NAND_BANK2)
+ {
+ /* NAND bank 2 registers configuration */
+ Device->PATT2 = tmppatt;
+ }
+ else
+ {
+ /* NAND bank 3 registers configuration */
+ Device->PATT3 = tmppatt;
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief DeInitializes the FSMC_NAND device
+ * @param Device: Pointer to NAND device instance
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank)
+{
+ /* Disable the NAND Bank */
+ __FSMC_NAND_DISABLE(Device, Bank);
+
+ /* De-initialize the NAND Bank */
+ if(Bank == FSMC_NAND_BANK2)
+ {
+ /* Set the FSMC_NAND_BANK2 registers to their reset values */
+ Device->PCR2 = 0x00000018;
+ Device->SR2 = 0x00000040;
+ Device->PMEM2 = 0xFCFCFCFC;
+ Device->PATT2 = 0xFCFCFCFC;
+ }
+ /* FSMC_Bank3_NAND */
+ else
+ {
+ /* Set the FSMC_NAND_BANK3 registers to their reset values */
+ Device->PCR3 = 0x00000018;
+ Device->SR3 = 0x00000040;
+ Device->PMEM3 = 0xFCFCFCFC;
+ Device->PATT3 = 0xFCFCFCFC;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+
+/** @defgroup HAL_FSMC_NAND_Group3 Control functions
+ * @brief management functions
+ *
+@verbatim
+ ==============================================================================
+ ##### FSMC_NAND Control functions #####
+ ==============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control dynamically
+ the FSMC NAND interface.
+
+@endverbatim
+ * @{
+ */
+
+
+/**
+ * @brief Enables dynamically FSMC_NAND ECC feature.
+ * @param Device: Pointer to NAND device instance
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NAND_ECC_Enable(FSMC_NAND_TypeDef *Device, uint32_t Bank)
+{
+ /* Enable ECC feature */
+ if(Bank == FSMC_NAND_BANK2)
+ {
+ Device->PCR2 |= FSMC_PCR2_ECCEN;
+ }
+ else
+ {
+ Device->PCR3 |= FSMC_PCR3_ECCEN;
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Disables dynamically FSMC_NAND ECC feature.
+ * @param Device: Pointer to NAND device instance
+ * @param Bank: NAND bank number
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank)
+{
+ /* Disable ECC feature */
+ if(Bank == FSMC_NAND_BANK2)
+ {
+ Device->PCR2 &= ~FSMC_PCR2_ECCEN;
+ }
+ else
+ {
+ Device->PCR3 &= ~FSMC_PCR3_ECCEN;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Disables dynamically FSMC_NAND ECC feature.
+ * @param Device: Pointer to NAND device instance
+ * @param ECCval: Pointer to ECC value
+ * @param Bank: NAND bank number
+ * @param Timeout: Timeout wait value
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, uint32_t Timeout)
+{
+ uint32_t timeout = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FSMC_NAND_DEVICE(Device));
+ assert_param(IS_FSMC_NAND_BANK(Bank));
+
+ timeout = HAL_GetTick() + Timeout;
+
+ /* Wait untill FIFO is empty */
+ while(__FSMC_NAND_GET_FLAG(Device, Bank, FSMC_FLAG_FEMPT))
+ {
+ /* Check for the Timeout */
+ if(Timeout != HAL_MAX_DELAY)
+ {
+ if(HAL_GetTick() >= timeout)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ }
+
+ if(Bank == FSMC_NAND_BANK2)
+ {
+ /* Get the ECCR2 register value */
+ *ECCval = (uint32_t)Device->ECCR2;
+ }
+ else
+ {
+ /* Get the ECCR3 register value */
+ *ECCval = (uint32_t)Device->ECCR3;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/** @defgroup FSMC_PCCARD Controller functions
+ * @brief PCCARD Controller functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use PCCARD device driver #####
+ ==============================================================================
+ [..]
+ This driver contains a set of APIs to interface with the FSMC PCCARD bank in order
+ to run the PCCARD/compact flash external devices.
+
+ (+) FSMC PCCARD bank reset using the function FSMC_PCCARD_DeInit()
+ (+) FSMC PCCARD bank control configuration using the function FSMC_PCCARD_Init()
+ (+) FSMC PCCARD bank common space timing configuration using the function
+ FSMC_PCCARD_CommonSpace_Timing_Init()
+ (+) FSMC PCCARD bank attribute space timing configuration using the function
+ FSMC_PCCARD_AttributeSpace_Timing_Init()
+ (+) FSMC PCCARD bank IO space timing configuration using the function
+ FSMC_PCCARD_IOSpace_Timing_Init()
+
+@endverbatim
+ * @{
+ */
+
+/** @defgroup HAL_FSMC_PCCARD_Group1 Initialization/de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ==============================================================================
+ ##### Initialization and de_initialization functions #####
+ ==============================================================================
+ [..]
+ This section provides functions allowing to:
+ (+) Initialize and configure the FSMC PCCARD interface
+ (+) De-initialize the FSMC PCCARD interface
+ (+) Configure the FSMC clock and associated GPIOs
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the FSMC_PCCARD device according to the specified
+ * control parameters in the FSMC_PCCARD_HandleTypeDef
+ * @param Device: Pointer to PCCARD device instance
+ * @param Init: Pointer to PCCARD Initialization structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_InitTypeDef *Init)
+{
+ /* Check the parameters */
+ assert_param(IS_FSMC_WAIT_FEATURE(Init->Waitfeature));
+ assert_param(IS_FSMC_TCLR_TIME(Init->TCLRSetupTime));
+ assert_param(IS_FSMC_TAR_TIME(Init->TARSetupTime));
+
+ /* Set FSMC_PCCARD device control parameters */
+ Device->PCR4 = (uint32_t)(Init->Waitfeature |\
+ FSMC_NAND_PCC_MEM_BUS_WIDTH_16 |\
+ (Init->TCLRSetupTime << 9) |\
+ (Init->TARSetupTime << 13));
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Initializes the FSMC_PCCARD Common space Timing according to the specified
+ * parameters in the FSMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to PCCARD device instance
+ * @param Timing: Pointer to PCCARD timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing)
+{
+ /* Check the parameters */
+ assert_param(IS_FSMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FSMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FSMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FSMC_HIZ_TIME(Timing->HiZSetupTime));
+
+ /* Set PCCARD timing parameters */
+ Device->PMEM4 = (uint32_t)((Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ (Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the FSMC_PCCARD Attribute space Timing according to the specified
+ * parameters in the FSMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to PCCARD device instance
+ * @param Timing: Pointer to PCCARD timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing)
+{
+ /* Check the parameters */
+ assert_param(IS_FSMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FSMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FSMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FSMC_HIZ_TIME(Timing->HiZSetupTime));
+
+ /* Set PCCARD timing parameters */
+ Device->PATT4 = (uint32_t)((Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ (Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initializes the FSMC_PCCARD IO space Timing according to the specified
+ * parameters in the FSMC_NAND_PCC_TimingTypeDef
+ * @param Device: Pointer to PCCARD device instance
+ * @param Timing: Pointer to PCCARD timing structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_PCCARD_IOSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing)
+{
+ /* Check the parameters */
+ assert_param(IS_FSMC_SETUP_TIME(Timing->SetupTime));
+ assert_param(IS_FSMC_WAIT_TIME(Timing->WaitSetupTime));
+ assert_param(IS_FSMC_HOLD_TIME(Timing->HoldSetupTime));
+ assert_param(IS_FSMC_HIZ_TIME(Timing->HiZSetupTime));
+
+ /* Set FSMC_PCCARD device timing parameters */
+ Device->PIO4 = (uint32_t)((Timing->SetupTime |\
+ ((Timing->WaitSetupTime) << 8) |\
+ (Timing->HoldSetupTime) << 16) |\
+ ((Timing->HiZSetupTime) << 24)
+ );
+
+ return HAL_OK;
+}
+
+/**
+ * @brief DeInitializes the FSMC_PCCARD device
+ * @param Device: Pointer to PCCARD device instance
+ * @retval HAL status
+ */
+HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device)
+{
+ /* Disable the FSMC_PCCARD device */
+ __FSMC_PCCARD_DISABLE(Device);
+
+ /* De-initialize the FSMC_PCCARD device */
+ Device->PCR4 = 0x00000018;
+ Device->SR4 = 0x00000000;
+ Device->PMEM4 = 0xFCFCFCFC;
+ Device->PATT4 = 0xFCFCFCFC;
+ Device->PIO4 = 0xFCFCFCFC;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */
+
+#endif /* HAL_FSMC_MODULE_ENABLED */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_sdmmc.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_sdmmc.c
new file mode 100644
index 0000000..f06ceb8
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_sdmmc.c
@@ -0,0 +1,555 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_ll_sdmmc.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief SDMMC Low Layer HAL module driver.
+ *
+ * This file provides firmware functions to manage the following
+ * functionalities of the SDMMC peripheral:
+ * + Initialization/de-initialization functions
+ * + I/O operation functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### SDMMC peripheral features #####
+ ==============================================================================
+ [..] The SD/SDIO MMC card host interface (SDIO) provides an interface between the APB2
+ peripheral bus and MultiMedia cards (MMCs), SD memory cards, SDIO cards and CE-ATA
+ devices.
+
+ [..] The MultiMedia Card system specifications are available through the MultiMedia Card
+ Association website at www.mmca.org, published by the MMCA technical committee.
+ SD memory card and SD I/O card system specifications are available through the SD card
+ Association website at www.sdcard.org.
+ CE-ATA system specifications are available through the CE-ATA work group web site at
+ www.ce-ata.org.
+
+ [..] The SDIO features include the following:
+ (+) Full compliance with MultiMedia Card System Specification Version 4.2. Card support
+ for three different databus modes: 1-bit (default), 4-bit and 8-bit
+ (+) Full compatibility with previous versions of MultiMedia Cards (forward compatibility)
+ (+) Full compliance with SD Memory Card Specifications Version 2.0
+ (+) Full compliance with SD I/O Card Specification Version 2.0: card support for two
+ different data bus modes: 1-bit (default) and 4-bit
+ (+) Full support of the CE-ATA features (full compliance with CE-ATA digital protocol
+ Rev1.1)
+ (+) Data transfer up to 48 MHz for the 8 bit mode
+ (+) Data and command output enable signals to control external bidirectional drivers.
+
+
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ This driver is a considered as a driver of service for external devices drivers
+ that interfaces with the SDIO peripheral.
+ According to the device used (SD card/ MMC card / SDIO card ...), a set of APIs
+ is used in the device's driver to perform SDIO operations and functionalities.
+
+ This driver is almost transparent for the final user, it is only used to implement other
+ functionalities of the external device.
+
+ [..]
+ (+) The SDIO clock (SDIOCLK = 48 MHz) is coming from a specific output of PLL
+ (PLL48CLK). Before start working with SDIO peripheral make sure that the
+ PLL is well configured.
+ The SDIO peripheral uses two clock signals:
+ (++) SDIO adapter clock (SDIOCLK = 48 MHz)
+ (++) APB2 bus clock (PCLK2)
+
+ -@@- PCLK2 and SDIO_CK clock frequencies must respect the following condition:
+ Frequency(PCLK2) >= (3 / 8 x Frequency(SDIO_CK))
+
+ (+) Enable/Disable peripheral clock using RCC peripheral macros related to SDIO
+ peripheral.
+
+ (+) Enable the Power ON State using the HAL_SDIO_PowerState_ON(hsdio)
+ function and disable it using the function HAL_SDIO_PowerState_OFF(hsdio).
+
+ (+) Enable/Disable the clock using the __SDIO_ENABLE()/__SDIO_DISABLE() macros.
+
+ (+) Enable/Disable the peripheral interrupts using the macros __SDIO_ENABLE_IT(hsdio, IT)
+ and __SDIO_DISABLE_IT(hsdio, IT) if you need to use interrupt mode.
+
+ (+) When using the DMA mode
+ (++) Configure the DMA in the MSP layer of the external device
+ (++) Active the needed channel Request
+ (++) Enable the DMA using __SDIO_DMA_ENABLE() macro or Disable it using the macro
+ __SDIO_DMA_DISABLE().
+
+ (+) To control the CPSM (Command Path State Machine) and send
+ commands to the card use the HAL_SDIO_SendCommand(),
+ HAL_SDIO_GetCommandResponse() and HAL_SDIO_GetResponse() functions. First, user has
+ to fill the command structure (pointer to SDIO_CmdInitTypeDef) according
+ to the selected command to be sent.
+ The parameters that should be filled are:
+ (++) Command Argument
+ (++) Command Index
+ (++) Command Response type
+ (++) Command Wait
+ (++) CPSM Status (Enable or Disable).
+
+ -@@- To check if the command is well received, read the SDIO_CMDRESP
+ register using the HAL_SDIO_GetCommandResponse().
+ The SDIO responses registers (SDIO_RESP1 to SDIO_RESP2), use the
+ HAL_SDIO_GetResponse() function.
+
+ (+) To control the DPSM (Data Path State Machine) and send/receive
+ data to/from the card use the HAL_SDIO_DataConfig(), HAL_SDIO_GetDataCounter(),
+ HAL_SDIO_ReadFIFO(), HAL_SDIO_WriteFIFO() and HAL_SDIO_GetFIFOCount() functions.
+
+ *** Read Operations ***
+ =======================
+ [..]
+ (#) First, user has to fill the data structure (pointer to
+ SDIO_DataInitTypeDef) according to the selected data type to be received.
+ The parameters that should be filled are:
+ (++) Data TimeOut
+ (++) Data Length
+ (++) Data Block size
+ (++) Data Transfer direction: should be from card (To SDIO)
+ (++) Data Transfer mode
+ (++) DPSM Status (Enable or Disable)
+
+ (#) Configure the SDIO resources to receive the data from the card
+ according to selected transfer mode (Refer to Step 8, 9 and 10).
+
+ (#) Send the selected Read command (refer to step 11).
+
+ (#) Use the SDIO flags/interrupts to check the transfer status.
+
+ *** Write Operations ***
+ ========================
+ [..]
+ (#) First, user has to fill the data structure (pointer to
+ SDIO_DataInitTypeDef) according to the selected data type to be received.
+ The parameters that should be filled are:
+ (++) Data TimeOut
+ (++) Data Length
+ (++) Data Block size
+ (++) Data Transfer direction: should be to card (To CARD)
+ (++) Data Transfer mode
+ (++) DPSM Status (Enable or Disable)
+
+ (#) Configure the SDIO resources to send the data to the card according to
+ selected transfer mode (Refer to Step 8, 9 and 10).
+
+ (#) Send the selected Write command (refer to step 11).
+
+ (#) Use the SDIO flags/interrupts to check the transfer status.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_HAL_Driver
+ * @{
+ */
+
+/** @defgroup SDMMC
+ * @brief SDMMC HAL module driver
+ * @{
+ */
+
+#if defined (HAL_SD_MODULE_ENABLED) || defined(HAL_MMC_MODULE_ENABLED)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/** @defgroup SDIO_Private_Functions
+ * @{
+ */
+
+/** @defgroup HAL_SDIO_Group1 Initialization/de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization/de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the SDIO according to the specified
+ * parameters in the SDIO_InitTypeDef and create the associated handle.
+ * @param SDIOx: Pointer to SDIO register base
+ * @param Init: SDIO initialization structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init)
+{
+ __IO uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_SDIO_ALL_INSTANCE(SDIOx));
+ assert_param(IS_SDIO_CLOCK_EDGE(Init.ClockEdge));
+ assert_param(IS_SDIO_CLOCK_BYPASS(Init.ClockBypass));
+ assert_param(IS_SDIO_CLOCK_POWER_SAVE(Init.ClockPowerSave));
+ assert_param(IS_SDIO_BUS_WIDE(Init.BusWide));
+ assert_param(IS_SDIO_HARDWARE_FLOW_CONTROL(Init.HardwareFlowControl));
+ assert_param(IS_SDIO_CLKDIV(Init.ClockDiv));
+
+ /* Get the SDIO CLKCR value */
+ tmpreg = SDIOx->CLKCR;
+
+ /* Clear CLKDIV, PWRSAV, BYPASS, WIDBUS, NEGEDGE, HWFC_EN bits */
+ tmpreg &= CLKCR_CLEAR_MASK;
+
+ /* Set SDIO configuration parameters */
+ tmpreg |= (Init.ClockEdge |\
+ Init.ClockBypass |\
+ Init.ClockPowerSave |\
+ Init.BusWide |\
+ Init.HardwareFlowControl |\
+ Init.ClockDiv
+ );
+
+ /* Write to SDIO CLKCR */
+ SDIOx->CLKCR = tmpreg;
+
+ return HAL_OK;
+}
+
+
+
+/**
+ * @}
+ */
+
+/** @defgroup HAL_SDIO_Group2 I/O operation functions
+ * @brief Data transfers functions
+ *
+@verbatim
+ ===============================================================================
+ ##### I/O operation functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to manage the SDIO data
+ transfers.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Read data (word) from Rx FIFO in blocking mode (polling)
+ * @param SDIOx: Pointer to SDIO register base
+ * @param ReadData: Data to read
+ * @retval HAL status
+ */
+uint32_t SDIO_ReadFIFO(SDIO_TypeDef *SDIOx)
+{
+ /* Read data from Rx FIFO */
+ return (SDIOx->FIFO);
+}
+
+/**
+ * @brief Write data (word) to Tx FIFO in blocking mode (polling)
+ * @param SDIOx: Pointer to SDIO register base
+ * @param pWriteData: pointer to data to write
+ * @retval HAL status
+ */
+HAL_StatusTypeDef SDIO_WriteFIFO(SDIO_TypeDef *SDIOx, uint32_t *pWriteData)
+{
+ /* Write data to FIFO */
+ SDIOx->FIFO = *pWriteData;
+
+ return HAL_OK;
+}
+
+/**
+ * @}
+ */
+
+/** @defgroup HAL_SDIO_Group3 Peripheral Control functions
+ * @brief management functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral Control functions #####
+ ===============================================================================
+ [..]
+ This subsection provides a set of functions allowing to control the SDIO data
+ transfers.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Set SDIO Power state to ON.
+ * @param SDIOx: Pointer to SDIO register base
+ * @retval HAL status
+ */
+HAL_StatusTypeDef SDIO_PowerState_ON(SDIO_TypeDef *SDIOx)
+{
+ /* Set power state to ON */
+ SDIOx->POWER = (uint32_t)0x00000003;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Set SDIO Power state to OFF.
+ * @param SDIOx: Pointer to SDIO register base
+ * @retval HAL status
+ */
+HAL_StatusTypeDef SDIO_PowerState_OFF(SDIO_TypeDef *SDIOx)
+{
+ /* Set power state to OFF */
+ SDIOx->POWER = (uint32_t)0x00000000;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Get SDIO Power state.
+ * @param SDIOx: Pointer to SDIO register base
+ * @retval Power status of the controller. The returned value can be one of the
+ * following values:
+ * - 0x00: Power OFF
+ * - 0x02: Power UP
+ * - 0x03: Power ON
+ */
+uint32_t SDIO_GetPowerState(SDIO_TypeDef *SDIOx)
+{
+ return (SDIOx->POWER & (~PWR_PWRCTRL_MASK));
+}
+
+/**
+ * @brief Configure the SDIO command path according to the specified parameters in
+ * SDIO_CmdInitTypeDef structure and send the command
+ * @param SDIOx: Pointer to SDIO register base
+ * @param SDIO_CmdInitStruct: pointer to a SDIO_CmdInitTypeDef structure that contains
+ * the configuration information for the SDIO command
+ * @retval HAL status
+ */
+HAL_StatusTypeDef SDIO_SendCommand(SDIO_TypeDef *SDIOx, SDIO_CmdInitTypeDef *SDIO_CmdInitStruct)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_SDIO_CMD_INDEX(SDIO_CmdInitStruct->CmdIndex));
+ assert_param(IS_SDIO_RESPONSE(SDIO_CmdInitStruct->Response));
+ assert_param(IS_SDIO_WAIT(SDIO_CmdInitStruct->WaitForInterrupt));
+ assert_param(IS_SDIO_CPSM(SDIO_CmdInitStruct->CPSM));
+
+ /* Set the SDIO Argument value */
+ SDIOx->ARG = SDIO_CmdInitStruct->Argument;
+
+ /* SDIO CMD Configuration */
+ /* Get the SDIO CMD value */
+ tmpreg = SDIOx->CMD;
+
+ /* Clear CMDINDEX, WAITRESP, WAITINT, WAITPEND, CPSMEN bits */
+ tmpreg &= CMD_CLEAR_MASK;
+
+ /* Set SDIO command parameters */
+ tmpreg |= (uint32_t)(SDIO_CmdInitStruct->CmdIndex |\
+ SDIO_CmdInitStruct->Response |\
+ SDIO_CmdInitStruct->WaitForInterrupt |\
+ SDIO_CmdInitStruct->CPSM);
+
+ /* Write to SDIO CMD register */
+ SDIOx->CMD = tmpreg;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Return the command index of last command for which response received
+ * @param SDIOx: Pointer to SDIO register base
+ * @retval Command index of the last command response received
+ */
+uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx)
+{
+ return (uint8_t)(SDIOx->RESPCMD);
+}
+
+
+/**
+ * @brief Return the response received from the card for the last command
+ * @param SDIO_RESP: Specifies the SDIO response register.
+ * This parameter can be one of the following values:
+ * @arg SDIO_RESP1: Response Register 1
+ * @arg SDIO_RESP2: Response Register 2
+ * @arg SDIO_RESP3: Response Register 3
+ * @arg SDIO_RESP4: Response Register 4
+ * @retval The Corresponding response register value
+ */
+uint32_t SDIO_GetResponse(uint32_t SDIO_RESP)
+{
+ __IO uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_SDIO_RESP(SDIO_RESP));
+
+ /* Get the response */
+ tmp = SDIO_RESP_ADDR + SDIO_RESP;
+
+ return (*(__IO uint32_t *) tmp);
+}
+
+/**
+ * @brief Configure the SDIO data path according to the specified
+ * parameters in the SDIO_DataInitTypeDef.
+ * @param SDIOx: Pointer to SDIO register base
+ * @param SDIO_DataInitStruct : pointer to a SDIO_DataInitTypeDef structure
+ * that contains the configuration information for the SDIO command.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef SDIO_DataConfig(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* SDIO_DataInitStruct)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_SDIO_DATA_LENGTH(SDIO_DataInitStruct->DataLength));
+ assert_param(IS_SDIO_BLOCK_SIZE(SDIO_DataInitStruct->DataBlockSize));
+ assert_param(IS_SDIO_TRANSFER_DIR(SDIO_DataInitStruct->TransferDir));
+ assert_param(IS_SDIO_TRANSFER_MODE(SDIO_DataInitStruct->TransferMode));
+ assert_param(IS_SDIO_DPSM(SDIO_DataInitStruct->DPSM));
+
+ /* Set the SDIO Data TimeOut value */
+ SDIOx->DTIMER = SDIO_DataInitStruct->DataTimeOut;
+
+ /* Set the SDIO DataLength value */
+ SDIOx->DLEN = SDIO_DataInitStruct->DataLength;
+
+/* SDIO DCTRL Configuration */
+ /* Get the SDIO DCTRL value */
+ tmpreg = SDIOx->DCTRL;
+
+ /* Clear DEN, DTMODE, DTDIR and DBCKSIZE bits */
+ tmpreg &= DCTRL_CLEAR_MASK;
+
+ /* Set the SDIO data configuration parameters */
+ tmpreg |= (uint32_t)(SDIO_DataInitStruct->DataBlockSize |\
+ SDIO_DataInitStruct->TransferDir |\
+ SDIO_DataInitStruct->TransferMode |\
+ SDIO_DataInitStruct->DPSM);
+
+ /* Write to SDIO DCTRL */
+ SDIOx->DCTRL = tmpreg;
+
+ return HAL_OK;
+
+}
+
+/**
+ * @brief Returns number of remaining data bytes to be transferred.
+ * @param SDIOx: Pointer to SDIO register base
+ * @retval Number of remaining data bytes to be transferred
+ */
+uint32_t SDIO_GetDataCounter(SDIO_TypeDef *SDIOx)
+{
+ return (SDIOx->DCOUNT);
+}
+
+/**
+ * @brief Get the FIFO data
+ * @param hsdio: SDIO handle
+ * @retval Data received
+ */
+uint32_t SDIO_GetFIFOCount(SDIO_TypeDef *SDIOx)
+{
+ return (SDIOx->FIFO);
+}
+
+
+/**
+ * @brief Sets one of the two options of inserting read wait interval.
+ * @param SDIO_ReadWaitMode: SD I/O Read Wait operation mode.
+ * This parameter can be:
+ * @arg SDIO_READ_WAIT_MODE_CLK: Read Wait control by stopping SDIOCLK
+ * @arg SDIO_READ_WAIT_MODE_DATA2: Read Wait control using SDIO_DATA2
+ * @retval None
+ */
+HAL_StatusTypeDef SDIO_SetSDIOReadWaitMode(uint32_t SDIO_ReadWaitMode)
+{
+ /* Check the parameters */
+ assert_param(IS_SDIO_READWAIT_MODE(SDIO_ReadWaitMode));
+
+ *(__IO uint32_t *)DCTRL_RWMOD_BB = SDIO_ReadWaitMode;
+
+ return HAL_OK;
+}
+
+
+/**
+ * @}
+ */
+
+/** @defgroup HAL_SDIO_Group3 Peripheral State functions
+ * @brief Peripheral State functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Peripheral State functions #####
+ ===============================================================================
+ [..]
+ This subsection permit to get in runtime the status of the SDIO peripheral
+ and the data flow.
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* (HAL_SD_MODULE_ENABLED) || (HAL_MMC_MODULE_ENABLED) */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_usb.c b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_usb.c
new file mode 100644
index 0000000..cbad954
--- /dev/null
+++ b/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_usb.c
@@ -0,0 +1,1684 @@
+/**
+ ******************************************************************************
+ * @file stm32f4xx_ll_usb.c
+ * @author MCD Application Team
+ * @version V1.0.0
+ * @date 18-February-2014
+ * @brief USB Low Layer HAL module driver.
+ *
+ * This file provides firmware functions to manage the following
+ * functionalities of the USB Peripheral Controller:
+ * + Initialization/de-initialization functions
+ * + I/O operation functions
+ * + Peripheral Control functions
+ * + Peripheral State functions
+ *
+ @verbatim
+ ==============================================================================
+ ##### How to use this driver #####
+ ==============================================================================
+ [..]
+ (#) Fill parameters of Init structure in USB_OTG_CfgTypeDef structure.
+
+ (#) Call USB_CoreInit() API to initialize the USB Core peripheral.
+
+ (#) The upper HAL HCD/PCD driver will call the righ routines for its internal processes.
+
+ @endverbatim
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. Neither the name of STMicroelectronics nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+
+/** @addtogroup STM32F4xx_LL_USB_DRIVER
+ * @{
+ */
+
+#if defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED)
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx);
+
+/** @defgroup PCD_Private_Functions
+ * @{
+ */
+
+/** @defgroup LL_USB_Group1 Initialization/de-initialization functions
+ * @brief Initialization and Configuration functions
+ *
+@verbatim
+ ===============================================================================
+ ##### Initialization/de-initialization functions #####
+ ===============================================================================
+ [..] This section provides functions allowing to:
+
+@endverbatim
+ * @{
+ */
+
+/**
+ * @brief Initializes the USB Core
+ * @param USBx: USB Instance
+ * @param cfg : pointer to a USB_OTG_CfgTypeDef structure that contains
+ * the configuration information for the specified USBx peripheral.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_CoreInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg)
+{
+ if (cfg.phy_itface == USB_OTG_ULPI_PHY)
+ {
+
+ USBx->GCCFG &= ~(USB_OTG_GCCFG_PWRDWN);
+
+ /* Init The ULPI Interface */
+ USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_TSDPS | USB_OTG_GUSBCFG_ULPIFSLS | USB_OTG_GUSBCFG_PHYSEL);
+
+ /* Select vbus source */
+ USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_ULPIEVBUSD | USB_OTG_GUSBCFG_ULPIEVBUSI);
+ if(cfg.use_external_vbus == 1)
+ {
+ USBx->GUSBCFG |= USB_OTG_GUSBCFG_ULPIEVBUSD;
+ }
+ /* Reset after a PHY select */
+ USB_CoreReset(USBx);
+ }
+ else /* FS interface (embedded Phy) */
+ {
+
+ /* Select FS Embedded PHY */
+ USBx->GUSBCFG |= USB_OTG_GUSBCFG_PHYSEL;
+
+ /* Reset after a PHY select and set Host mode */
+ USB_CoreReset(USBx);
+
+ /* Deactivate the power down*/
+ USBx->GCCFG = USB_OTG_GCCFG_PWRDWN;
+ }
+
+ if(cfg.dma_enable == ENABLE)
+ {
+ USBx->GAHBCFG |= (USB_OTG_GAHBCFG_HBSTLEN_1 | USB_OTG_GAHBCFG_HBSTLEN_2);
+ USBx->GAHBCFG |= USB_OTG_GAHBCFG_DMAEN;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_EnableGlobalInt
+ * Enables the controller's Global Int in the AHB Config reg
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_EnableGlobalInt(USB_OTG_GlobalTypeDef *USBx)
+{
+ USBx->GAHBCFG |= USB_OTG_GAHBCFG_GINT;
+ return HAL_OK;
+}
+
+
+/**
+ * @brief USB_DisableGlobalInt
+ * Disable the controller's Global Int in the AHB Config reg
+ * @param USBx : Selected device
+ * @retval HAL status
+*/
+HAL_StatusTypeDef USB_DisableGlobalInt(USB_OTG_GlobalTypeDef *USBx)
+{
+ USBx->GAHBCFG &= ~USB_OTG_GAHBCFG_GINT;
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_SetCurrentMode : Set functional mode
+ * @param USBx : Selected device
+ * @param mode : current core mode
+ * This parameter can be one of the these values:
+ * @arg USB_OTG_DEVICE_MODE: Peripheral mode mode
+ * @arg USB_OTG_HOST_MODE: Host mode
+ * @arg USB_OTG_DRD_MODE: Dual Role Device mode
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx , USB_OTG_ModeTypeDef mode)
+{
+ USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_FHMOD | USB_OTG_GUSBCFG_FDMOD);
+
+ if ( mode == USB_OTG_HOST_MODE)
+ {
+ USBx->GUSBCFG |= USB_OTG_GUSBCFG_FHMOD;
+ }
+ else if ( mode == USB_OTG_DEVICE_MODE)
+ {
+ USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD;
+ }
+ HAL_Delay(50);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_DevInit : Initializes the USB_OTG controller registers
+ * for device mode
+ * @param USBx : Selected device
+ * @param cfg : pointer to a USB_OTG_CfgTypeDef structure that contains
+ * the configuration information for the specified USBx peripheral.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_DevInit (USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg)
+{
+ uint32_t i = 0;
+
+ /*Activate VBUS Sensing B */
+ USBx->GCCFG |= USB_OTG_GCCFG_VBUSBSEN;
+
+ if (cfg.vbus_sensing_enable == 0)
+ {
+ USBx->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS;
+ }
+
+ /* Restart the Phy Clock */
+ USBx_PCGCCTL = 0;
+
+ /* Device mode configuration */
+ USBx_DEVICE->DCFG |= DCFG_FRAME_INTERVAL_80;
+
+ if(cfg.phy_itface == USB_OTG_ULPI_PHY)
+ {
+ if(cfg.speed == USB_OTG_SPEED_HIGH)
+ {
+ /* Set High speed phy */
+ USB_SetDevSpeed (USBx , USB_OTG_SPEED_HIGH);
+ }
+ else
+ {
+ /* set High speed phy in Full speed mode */
+ USB_SetDevSpeed (USBx , USB_OTG_SPEED_HIGH_IN_FULL);
+ }
+ }
+ else
+ {
+ /* Set Full speed phy */
+ USB_SetDevSpeed (USBx , USB_OTG_SPEED_FULL);
+ }
+
+ /* Flush the FIFOs */
+ USB_FlushTxFifo(USBx , 0x10); /* all Tx FIFOs */
+ USB_FlushRxFifo(USBx);
+
+
+ /* Clear all pending Device Interrupts */
+ USBx_DEVICE->DIEPMSK = 0;
+ USBx_DEVICE->DOEPMSK = 0;
+ USBx_DEVICE->DAINT = 0xFFFFFFFF;
+ USBx_DEVICE->DAINTMSK = 0;
+
+ for (i = 0; i < cfg.dev_endpoints; i++)
+ {
+ if ((USBx_INEP(i)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA)
+ {
+ USBx_INEP(i)->DIEPCTL = (USB_OTG_DIEPCTL_EPDIS | USB_OTG_DIEPCTL_SNAK);
+ }
+ else
+ {
+ USBx_INEP(i)->DIEPCTL = 0;
+ }
+
+ USBx_INEP(i)->DIEPTSIZ = 0;
+ USBx_INEP(i)->DIEPINT = 0xFF;
+ }
+
+ for (i = 0; i < cfg.dev_endpoints; i++)
+ {
+ if ((USBx_OUTEP(i)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA)
+ {
+ USBx_OUTEP(i)->DOEPCTL = (USB_OTG_DOEPCTL_EPDIS | USB_OTG_DOEPCTL_SNAK);
+ }
+ else
+ {
+ USBx_OUTEP(i)->DOEPCTL = 0;
+ }
+
+ USBx_OUTEP(i)->DOEPTSIZ = 0;
+ USBx_OUTEP(i)->DOEPINT = 0xFF;
+ }
+
+ USBx_DEVICE->DIEPMSK &= ~(USB_OTG_DIEPMSK_TXFURM);
+
+ if (cfg.dma_enable == 1)
+ {
+ /*Set threshold parameters */
+ USBx_DEVICE->DTHRCTL = (USB_OTG_DTHRCTL_TXTHRLEN_6 | USB_OTG_DTHRCTL_RXTHRLEN_6);
+ USBx_DEVICE->DTHRCTL |= (USB_OTG_DTHRCTL_RXTHREN | USB_OTG_DTHRCTL_ISOTHREN | USB_OTG_DTHRCTL_NONISOTHREN);
+
+ i= USBx_DEVICE->DTHRCTL;
+ }
+
+ /* Disable all interrupts. */
+ USBx->GINTMSK = 0;
+
+ /* Clear any pending interrupts */
+ USBx->GINTSTS = 0xBFFFFFFF;
+
+ /* Enable the common interrupts */
+ if (cfg.dma_enable == DISABLE)
+ {
+ USBx->GINTMSK |= USB_OTG_GINTMSK_RXFLVLM;
+ }
+
+ /* Enable interrupts matching to the Device mode ONLY */
+ USBx->GINTMSK |= (USB_OTG_GINTMSK_USBSUSPM | USB_OTG_GINTMSK_USBRST |\
+ USB_OTG_GINTMSK_ENUMDNEM | USB_OTG_GINTMSK_IEPINT |\
+ USB_OTG_GINTMSK_OEPINT | USB_OTG_GINTMSK_IISOIXFRM|\
+ USB_OTG_GINTMSK_PXFRM_IISOOXFRM | USB_OTG_GINTMSK_WUIM);
+
+ if(cfg.Sof_enable)
+ {
+ USBx->GINTMSK |= USB_OTG_GINTMSK_SOFM;
+ }
+
+ if (cfg.vbus_sensing_enable == ENABLE)
+ {
+ USBx->GINTMSK |= (USB_OTG_GINTMSK_SRQIM | USB_OTG_GINTMSK_OTGINT);
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief USB_OTG_FlushTxFifo : Flush a Tx FIFO
+ * @param USBx : Selected device
+ * @param num : FIFO number
+ * This parameter can be a value from 1 to 15
+ 15 means Flush all Tx FIFOs
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_FlushTxFifo (USB_OTG_GlobalTypeDef *USBx, uint32_t num )
+{
+ uint32_t count = 0;
+
+ USBx->GRSTCTL = ( USB_OTG_GRSTCTL_TXFFLSH |(uint32_t)( num << 5 ));
+
+ do
+ {
+ if (++count > 200000)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_TXFFLSH) == USB_OTG_GRSTCTL_TXFFLSH);
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief USB_FlushRxFifo : Flush Rx FIFO
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx)
+{
+ uint32_t count = 0;
+
+ USBx->GRSTCTL = USB_OTG_GRSTCTL_RXFFLSH;
+
+ do
+ {
+ if (++count > 200000)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_RXFFLSH) == USB_OTG_GRSTCTL_RXFFLSH);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_SetDevSpeed :Initializes the DevSpd field of DCFG register
+ * depending the PHY type and the enumeration speed of the device.
+ * @param USBx : Selected device
+ * @param speed : device speed
+ * This parameter can be one of the these values:
+ * @arg USB_OTG_SPEED_HIGH: High speed mode
+ * @arg USB_OTG_SPEED_HIGH_IN_FULL: High speed core in Full Speed mode
+ * @arg USB_OTG_SPEED_FULL: Full speed mode
+ * @arg USB_OTG_SPEED_LOW: Low speed mode
+ * @retval Hal status
+ */
+HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx , uint8_t speed)
+{
+ USBx_DEVICE->DCFG |= speed;
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_GetDevSpeed :Return the Dev Speed
+ * @param USBx : Selected device
+ * @retval speed : device speed
+ * This parameter can be one of the these values:
+ * @arg USB_OTG_SPEED_HIGH: High speed mode
+ * @arg USB_OTG_SPEED_FULL: Full speed mode
+ * @arg USB_OTG_SPEED_LOW: Low speed mode
+ */
+uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx)
+{
+ uint8_t speed = 0;
+
+ if((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_HS_PHY_30MHZ_OR_60MHZ)
+ {
+ speed = USB_OTG_SPEED_HIGH;
+ }
+ else if (((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ)||
+ ((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_FS_PHY_48MHZ))
+ {
+ speed = USB_OTG_SPEED_FULL;
+ }
+ else if((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_LS_PHY_6MHZ)
+ {
+ speed = USB_OTG_SPEED_LOW;
+ }
+
+ return speed;
+}
+
+/**
+ * @brief Activate and configure an endpoint
+ * @param USBx : Selected device
+ * @param ep: pointer to endpoint structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep)
+{
+ if (ep->is_in == 1)
+ {
+ USBx_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_IEPM & ((1 << (ep->num)));
+
+ if (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_USBAEP) == 0)
+ {
+ USBx_INEP(ep->num)->DIEPCTL |= ((ep->maxpacket & USB_OTG_DIEPCTL_MPSIZ ) | (ep->type << 18 ) |\
+ ((ep->num) << 22 ) | (USB_OTG_DIEPCTL_SD0PID_SEVNFRM) | (USB_OTG_DIEPCTL_USBAEP));
+ }
+
+ }
+ else
+ {
+ USBx_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_OEPM & ((1 << (ep->num)) << 16);
+
+ if (((USBx_OUTEP(ep->num)->DOEPCTL) & USB_OTG_DOEPCTL_USBAEP) == 0)
+ {
+ USBx_OUTEP(ep->num)->DOEPCTL |= ((ep->maxpacket & USB_OTG_DOEPCTL_MPSIZ ) | (ep->type << 18 ) |\
+ (USB_OTG_DIEPCTL_SD0PID_SEVNFRM)| (USB_OTG_DOEPCTL_USBAEP));
+ }
+ }
+ return HAL_OK;
+}
+/**
+ * @brief Activate and configure a dedicated endpoint
+ * @param USBx : Selected device
+ * @param ep: pointer to endpoint structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep)
+{
+ static __IO uint32_t debug = 0;
+
+ /* Read DEPCTLn register */
+ if (ep->is_in == 1)
+ {
+ if (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_USBAEP) == 0)
+ {
+ USBx_INEP(ep->num)->DIEPCTL |= ((ep->maxpacket & USB_OTG_DIEPCTL_MPSIZ ) | (ep->type << 18 ) |\
+ ((ep->num) << 22 ) | (USB_OTG_DIEPCTL_SD0PID_SEVNFRM) | (USB_OTG_DIEPCTL_USBAEP));
+ }
+
+
+ debug |= ((ep->maxpacket & USB_OTG_DIEPCTL_MPSIZ ) | (ep->type << 18 ) |\
+ ((ep->num) << 22 ) | (USB_OTG_DIEPCTL_SD0PID_SEVNFRM) | (USB_OTG_DIEPCTL_USBAEP));
+
+ USBx_DEVICE->DEACHMSK |= USB_OTG_DAINTMSK_IEPM & ((1 << (ep->num)));
+ }
+ else
+ {
+ if (((USBx_OUTEP(ep->num)->DOEPCTL) & USB_OTG_DOEPCTL_USBAEP) == 0)
+ {
+ USBx_OUTEP(ep->num)->DOEPCTL |= ((ep->maxpacket & USB_OTG_DOEPCTL_MPSIZ ) | (ep->type << 18 ) |\
+ ((ep->num) << 22 ) | (USB_OTG_DOEPCTL_USBAEP));
+
+ debug = (uint32_t)(((uint32_t )USBx) + USB_OTG_OUT_ENDPOINT_BASE + (0)*USB_OTG_EP_REG_SIZE);
+ debug = (uint32_t )&USBx_OUTEP(ep->num)->DOEPCTL;
+ debug |= ((ep->maxpacket & USB_OTG_DOEPCTL_MPSIZ ) | (ep->type << 18 ) |\
+ ((ep->num) << 22 ) | (USB_OTG_DOEPCTL_USBAEP));
+ }
+
+ USBx_DEVICE->DEACHMSK |= USB_OTG_DAINTMSK_OEPM & ((1 << (ep->num)) << 16);
+ }
+
+ return HAL_OK;
+}
+/**
+ * @brief De-activate and de-initialize an endpoint
+ * @param USBx : Selected device
+ * @param ep: pointer to endpoint structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep)
+{
+ /* Read DEPCTLn register */
+ if (ep->is_in == 1)
+ {
+ USBx_DEVICE->DEACHMSK &= ~(USB_OTG_DAINTMSK_IEPM & ((1 << (ep->num))));
+ USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_IEPM & ((1 << (ep->num))));
+ USBx_INEP(ep->num)->DIEPCTL &= ~ USB_OTG_DIEPCTL_USBAEP;
+ }
+ else
+ {
+
+ USBx_DEVICE->DEACHMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((1 << (ep->num)) << 16));
+ USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((1 << (ep->num)) << 16));
+ USBx_OUTEP(ep->num)->DOEPCTL &= ~USB_OTG_DOEPCTL_USBAEP;
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief De-activate and de-initialize a dedicated endpoint
+ * @param USBx : Selected device
+ * @param ep: pointer to endpoint structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep)
+{
+ /* Read DEPCTLn register */
+ if (ep->is_in == 1)
+ {
+ USBx_INEP(ep->num)->DIEPCTL &= ~ USB_OTG_DIEPCTL_USBAEP;
+ USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_IEPM & ((1 << (ep->num))));
+ }
+ else
+ {
+ USBx_OUTEP(ep->num)->DOEPCTL &= ~USB_OTG_DOEPCTL_USBAEP;
+ USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((1 << (ep->num)) << 16));
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_EPStartXfer : setup and starts a transfer over an EP
+ * @param USBx : Selected device
+ * @param ep: pointer to endpoint structure
+ * @param dma: USB dma enabled or disabled
+ * This parameter can be one of the these values:
+ * 0 : DMA feature not used
+ * 1 : DMA feature used
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep, uint8_t dma)
+{
+ uint16_t pktcnt = 0;
+
+ /* IN endpoint */
+ if (ep->is_in == 1)
+ {
+ /* Zero Length Packet? */
+ if (ep->xfer_len == 0)
+ {
+ USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT);
+ USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1 << 19)) ;
+ USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ);
+ }
+ else
+ {
+ /* Program the transfer size and packet count
+ * as follows: xfersize = N * maxpacket +
+ * short_packet pktcnt = N + (short_packet
+ * exist ? 1 : 0)
+ */
+ USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ);
+ USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT);
+ USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (((ep->xfer_len + ep->maxpacket -1)/ ep->maxpacket) << 19)) ;
+ USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_XFRSIZ & ep->xfer_len);
+
+ if (ep->type == EP_TYPE_ISOC)
+ {
+ USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_MULCNT);
+ USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_MULCNT & (1 << 29));
+ }
+ }
+
+ if (dma == 1)
+ {
+ USBx_INEP(ep->num)->DIEPDMA = (uint32_t)(ep->dma_addr);
+ }
+ else
+ {
+ if (ep->type != EP_TYPE_ISOC)
+ {
+ /* Enable the Tx FIFO Empty Interrupt for this EP */
+ if (ep->xfer_len > 0)
+ {
+ USBx_DEVICE->DIEPEMPMSK |= 1 << ep->num;
+ }
+ }
+ }
+
+ if (ep->type == EP_TYPE_ISOC)
+ {
+ if ((USBx_DEVICE->DSTS & ( 1 << 8 )) == 0)
+ {
+ USBx_INEP(ep->num)->DIEPCTL |= USB_OTG_DIEPCTL_SODDFRM;
+ }
+ else
+ {
+ USBx_INEP(ep->num)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM;
+ }
+ }
+
+ /* EP enable, IN data in FIFO */
+ USBx_INEP(ep->num)->DIEPCTL |= (USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA);
+
+ if (ep->type == EP_TYPE_ISOC)
+ {
+ USB_WritePacket(USBx, ep->xfer_buff, ep->num, ep->xfer_len, dma);
+ }
+ }
+ else /* OUT endpoint */
+ {
+ /* Program the transfer size and packet count as follows:
+ * pktcnt = N
+ * xfersize = N * maxpacket
+ */
+ USBx_OUTEP(ep->num)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_XFRSIZ);
+ USBx_OUTEP(ep->num)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_PKTCNT);
+
+ if (ep->xfer_len == 0)
+ {
+ USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & ep->maxpacket);
+ USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19)) ;
+ }
+ else
+ {
+ pktcnt = (ep->xfer_len + ep->maxpacket -1)/ ep->maxpacket;
+ USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (pktcnt << 19)); ;
+ USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & (ep->maxpacket * pktcnt));
+ }
+
+ if (dma == 1)
+ {
+ USBx_OUTEP(ep->num)->DOEPDMA = (uint32_t)ep->xfer_buff;
+ }
+
+ if (ep->type == EP_TYPE_ISOC)
+ {
+ if ((USBx_DEVICE->DSTS & ( 1 << 8 )) == 0)
+ {
+ USBx_OUTEP(ep->num)->DOEPCTL |= USB_OTG_DOEPCTL_SODDFRM;
+ }
+ else
+ {
+ USBx_OUTEP(ep->num)->DOEPCTL |= USB_OTG_DOEPCTL_SD0PID_SEVNFRM;
+ }
+ }
+ /* EP enable */
+ USBx_OUTEP(ep->num)->DOEPCTL |= (USB_OTG_DOEPCTL_CNAK | USB_OTG_DOEPCTL_EPENA);
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_EP0StartXfer : setup and starts a transfer over the EP 0
+ * @param USBx : Selected device
+ * @param ep: pointer to endpoint structure
+ * @param dma: USB dma enabled or disabled
+ * This parameter can be one of the these values:
+ * 0 : DMA feature not used
+ * 1 : DMA feature used
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep, uint8_t dma)
+{
+ /* IN endpoint */
+ if (ep->is_in == 1)
+ {
+ /* Zero Length Packet? */
+ if (ep->xfer_len == 0)
+ {
+ USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT);
+ USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1 << 19)) ;
+ USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ);
+ }
+ else
+ {
+ /* Program the transfer size and packet count
+ * as follows: xfersize = N * maxpacket +
+ * short_packet pktcnt = N + (short_packet
+ * exist ? 1 : 0)
+ */
+ USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ);
+ USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT);
+
+ if(ep->xfer_len > ep->maxpacket)
+ {
+ ep->xfer_len = ep->maxpacket;
+ }
+ USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1 << 19)) ;
+ USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_XFRSIZ & ep->xfer_len);
+
+ }
+
+ if (dma == 1)
+ {
+ USBx_INEP(ep->num)->DIEPDMA = (uint32_t)(ep->dma_addr);
+ }
+ else
+ {
+ /* Enable the Tx FIFO Empty Interrupt for this EP */
+ if (ep->xfer_len > 0)
+ {
+ USBx_DEVICE->DIEPEMPMSK |= 1 << (ep->num);
+ }
+ }
+
+ /* EP enable, IN data in FIFO */
+ USBx_INEP(ep->num)->DIEPCTL |= (USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA);
+ }
+ else /* OUT endpoint */
+ {
+ /* Program the transfer size and packet count as follows:
+ * pktcnt = N
+ * xfersize = N * maxpacket
+ */
+ USBx_OUTEP(ep->num)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_XFRSIZ);
+ USBx_OUTEP(ep->num)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_PKTCNT);
+
+ if (ep->xfer_len > 0)
+ {
+ ep->xfer_len = ep->maxpacket;
+ }
+
+ USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19));
+ USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & (ep->maxpacket));
+
+
+ if (dma == 1)
+ {
+ USBx_OUTEP(ep->num)->DOEPDMA = (uint32_t)(ep->xfer_buff);
+ }
+
+ /* EP enable */
+ USBx_OUTEP(ep->num)->DOEPCTL |= (USB_OTG_DOEPCTL_CNAK | USB_OTG_DOEPCTL_EPENA);
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_WritePacket : Writes a packet into the Tx FIFO associated
+ * with the EP/channel
+ * @param USBx : Selected device
+ * @param src : pointer to source buffer
+ * @param ch_ep_num : endpoint or host channel number
+ * @param len : Number of bytes to write
+ * @param dma: USB dma enabled or disabled
+ * This parameter can be one of the these values:
+ * 0 : DMA feature not used
+ * 1 : DMA feature used
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len, uint8_t dma)
+{
+ uint32_t count32b= 0 , i= 0;
+
+ if (dma == 0)
+ {
+ count32b = (len + 3) / 4;
+ for (i = 0; i < count32b; i++, src += 4)
+ {
+ USBx_DFIFO(ch_ep_num) = *((__packed uint32_t *)src);
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_ReadPacket : read a packet from the Tx FIFO associated
+ * with the EP/channel
+ * @param USBx : Selected device
+ * @param src : source pointer
+ * @param ch_ep_num : endpoint or host channel number
+ * @param len : Noumber of bytes to read
+ * @param dma: USB dma enabled or disabled
+ * This parameter can be one of the these values:
+ * 0 : DMA feature not used
+ * 1 : DMA feature used
+ * @retval pointer to desctination buffer
+ */
+void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len)
+{
+ uint32_t i=0;
+ uint32_t count32b = (len + 3) / 4;
+
+ for ( i = 0; i < count32b; i++, dest += 4 )
+ {
+ *(__packed uint32_t *)dest = USBx_DFIFO(0);
+
+ }
+ return ((void *)dest);
+}
+
+/**
+ * @brief USB_EPSetStall : set a stall condition over an EP
+ * @param USBx : Selected device
+ * @param ep: pointer to endpoint structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep)
+{
+ if (ep->is_in == 1)
+ {
+ if (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_EPENA) == 0)
+ {
+ USBx_INEP(ep->num)->DIEPCTL &= ~(USB_OTG_DIEPCTL_EPDIS);
+ }
+ USBx_INEP(ep->num)->DIEPCTL |= USB_OTG_DIEPCTL_STALL;
+ }
+ else
+ {
+ if (((USBx_OUTEP(ep->num)->DOEPCTL) & USB_OTG_DOEPCTL_EPENA) == 0)
+ {
+ USBx_OUTEP(ep->num)->DOEPCTL &= ~(USB_OTG_DOEPCTL_EPDIS);
+ }
+ USBx_OUTEP(ep->num)->DOEPCTL |= USB_OTG_DOEPCTL_STALL;
+ }
+ return HAL_OK;
+}
+
+
+/**
+ * @brief USB_EPClearStall : Clear a stall condition over an EP
+ * @param USBx : Selected device
+ * @param ep: pointer to endpoint structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep)
+{
+ if (ep->is_in == 1)
+ {
+ USBx_INEP(ep->num)->DIEPCTL &= ~USB_OTG_DIEPCTL_STALL;
+ if (ep->type == EP_TYPE_INTR || ep->type == EP_TYPE_BULK)
+ {
+ USBx_INEP(ep->num)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM; /* DATA0 */
+ }
+ }
+ else
+ {
+ USBx_OUTEP(ep->num)->DOEPCTL &= ~USB_OTG_DOEPCTL_STALL;
+ if (ep->type == EP_TYPE_INTR || ep->type == EP_TYPE_BULK)
+ {
+ USBx_OUTEP(ep->num)->DOEPCTL |= USB_OTG_DOEPCTL_SD0PID_SEVNFRM; /* DATA0 */
+ }
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_StopDevice : Stop the usb device mode
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx)
+{
+ uint32_t i;
+
+ /* Clear Pending interrupt */
+ for (i = 0; i < 15 ; i++)
+ {
+ USBx_INEP(i)->DIEPINT = 0xFF;
+ USBx_OUTEP(i)->DOEPINT = 0xFF;
+ }
+ USBx_DEVICE->DAINT = 0xFFFFFFFF;
+
+ /* Clear interrupt masks */
+ USBx_DEVICE->DIEPMSK = 0;
+ USBx_DEVICE->DOEPMSK = 0;
+ USBx_DEVICE->DAINTMSK = 0;
+
+ /* Flush the FIFO */
+ USB_FlushRxFifo(USBx);
+ USB_FlushTxFifo(USBx , 0x10 );
+
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_SetDevAddress : Stop the usb device mode
+ * @param USBx : Selected device
+ * @param address : new device address to be assigned
+ * This parameter can be a value from 0 to 255
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_SetDevAddress (USB_OTG_GlobalTypeDef *USBx, uint8_t address)
+{
+ USBx_DEVICE->DCFG &= ~ (USB_OTG_DCFG_DAD);
+ USBx_DEVICE->DCFG |= (address << 4) & USB_OTG_DCFG_DAD ;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_DevConnect : Connect the USB device by enabling the pull-up/pull-down
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_DevConnect (USB_OTG_GlobalTypeDef *USBx)
+{
+ USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_SDIS ;
+ HAL_Delay(3);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_DevDisconnect : Disconnect the USB device by disabling the pull-up/pull-down
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_DevDisconnect (USB_OTG_GlobalTypeDef *USBx)
+{
+ USBx_DEVICE->DCTL |= USB_OTG_DCTL_SDIS ;
+ HAL_Delay(3);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_ReadInterrupts: return the global USB interrupt status
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+uint32_t USB_ReadInterrupts (USB_OTG_GlobalTypeDef *USBx)
+{
+ uint32_t v = 0;
+
+ v = USBx->GINTSTS;
+ v &= USBx->GINTMSK;
+ return v;
+}
+
+/**
+ * @brief USB_ReadDevAllOutEpInterrupt: return the USB device OUT endpoints interrupt status
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+uint32_t USB_ReadDevAllOutEpInterrupt (USB_OTG_GlobalTypeDef *USBx)
+{
+ uint32_t v;
+ v = USBx_DEVICE->DAINT;
+ v &= USBx_DEVICE->DAINTMSK;
+ return ((v & 0xffff0000) >> 16);
+}
+
+/**
+ * @brief USB_ReadDevAllInEpInterrupt: return the USB device IN endpoints interrupt status
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+uint32_t USB_ReadDevAllInEpInterrupt (USB_OTG_GlobalTypeDef *USBx)
+{
+ uint32_t v;
+ v = USBx_DEVICE->DAINT;
+ v &= USBx_DEVICE->DAINTMSK;
+ return ((v & 0xFFFF));
+}
+
+/**
+ * @brief Returns Device OUT EP Interrupt register
+ * @param USBx : Selected device
+ * @param epnum : endpoint number
+ * This parameter can be a value from 0 to 15
+ * @retval Device OUT EP Interrupt register
+ */
+uint32_t USB_ReadDevOutEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum)
+{
+ uint32_t v;
+ v = USBx_OUTEP(epnum)->DOEPINT;
+ v &= USBx_DEVICE->DOEPMSK;
+ return v;
+}
+
+/**
+ * @brief Returns Device IN EP Interrupt register
+ * @param USBx : Selected device
+ * @param epnum : endpoint number
+ * This parameter can be a value from 0 to 15
+ * @retval Device IN EP Interrupt register
+ */
+uint32_t USB_ReadDevInEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum)
+{
+ uint32_t v, msk, emp;
+
+ msk = USBx_DEVICE->DIEPMSK;
+ emp = USBx_DEVICE->DIEPEMPMSK;
+ msk |= ((emp >> epnum) & 0x1) << 7;
+ v = USBx_INEP(epnum)->DIEPINT & msk;
+ return v;
+}
+
+/**
+ * @brief USB_ClearInterrupts: clear a USB interrupt
+ * @param USBx : Selected device
+ * @param interrupt : interrupt flag
+ * @retval None
+ */
+void USB_ClearInterrupts (USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt)
+{
+ USBx->GINTSTS |= interrupt;
+}
+
+/**
+ * @brief Returns USB core mode
+ * @param USBx : Selected device
+ * @retval return core mode : Host or Device
+ * This parameter can be one of the these values:
+ * 0 : Host
+ * 1 : Device
+ */
+uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx)
+{
+ return ((USBx->GINTSTS ) & 0x1);
+}
+
+
+/**
+ * @brief Activate EP0 for Setup transactions
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_ActivateSetup (USB_OTG_GlobalTypeDef *USBx)
+{
+ /* Set the MPS of the IN EP based on the enumeration speed */
+ USBx_INEP(0)->DIEPCTL &= ~USB_OTG_DIEPCTL_MPSIZ;
+
+ if((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_LS_PHY_6MHZ)
+ {
+ USBx_INEP(0)->DIEPCTL |= 3;
+ }
+ USBx_DEVICE->DCTL |= USB_OTG_DCTL_CGINAK;
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Prepare the EP0 to start the first control setup
+ * @param USBx : Selected device
+ * @param dma: USB dma enabled or disabled
+ * This parameter can be one of the these values:
+ * 0 : DMA feature not used
+ * 1 : DMA feature used
+ * @param psetup : pointer to setup packet
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t dma, uint8_t *psetup)
+{
+ USBx_OUTEP(0)->DOEPTSIZ = 0;
+ USBx_OUTEP(0)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19)) ;
+ USBx_OUTEP(0)->DOEPTSIZ |= (3 * 8);
+ USBx_OUTEP(0)->DOEPTSIZ |= USB_OTG_DOEPTSIZ_STUPCNT;
+
+ if (dma == 1)
+ {
+ USBx_OUTEP(0)->DOEPDMA = (uint32_t)psetup;
+ /* EP enable */
+ USBx_OUTEP(0)->DOEPCTL = 0x80008000;
+ }
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief Reset the USB Core (needed after USB clock settings change)
+ * @param USBx : Selected device
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx)
+{
+ uint32_t count = 0;
+
+ /* Wait for AHB master IDLE state. */
+ do
+ {
+ if (++count > 200000)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0);
+
+ /* Core Soft Reset */
+ count = 0;
+ USBx->GRSTCTL |= USB_OTG_GRSTCTL_CSRST;
+
+ do
+ {
+ if (++count > 200000)
+ {
+ return HAL_TIMEOUT;
+ }
+ }
+ while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_CSRST) == USB_OTG_GRSTCTL_CSRST);
+
+ return HAL_OK;
+}
+
+
+/**
+ * @brief USB_HostInit : Initializes the USB OTG controller registers
+ * for Host mode
+ * @param USBx : Selected device
+ * @param cfg : pointer to a USB_OTG_CfgTypeDef structure that contains
+ * the configuration information for the specified USBx peripheral.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_HostInit (USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg)
+{
+ uint32_t i;
+
+ /* Restart the Phy Clock */
+ USBx_PCGCCTL = 0;
+
+ /* no VBUS sensing*/
+ USBx->GCCFG &=~ (USB_OTG_GCCFG_VBUSASEN);
+ USBx->GCCFG &=~ (USB_OTG_GCCFG_VBUSBSEN);
+ USBx->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS;
+
+ /* Disable the FS/LS support mode only */
+ if((cfg.speed == USB_OTG_SPEED_FULL)&&
+ (USBx != USB_OTG_FS))
+ {
+ USBx_HOST->HCFG |= USB_OTG_HCFG_FSLSS;
+ }
+ else
+ {
+ USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSS);
+ }
+
+ /* Make sure the FIFOs are flushed. */
+ USB_FlushTxFifo(USBx, 0x10 ); /* all Tx FIFOs */
+ USB_FlushRxFifo(USBx);
+
+ /* Clear all pending HC Interrupts */
+ for (i = 0; i < cfg.Host_channels; i++)
+ {
+ USBx_HC(i)->HCINT = 0xFFFFFFFF;
+ USBx_HC(i)->HCINTMSK = 0;
+ }
+
+ /* Enable VBUS driving */
+ USB_DriveVbus(USBx, 1);
+
+ HAL_Delay(200);
+
+ /* Disable all interrupts. */
+ USBx->GINTMSK = 0;
+
+ /* Clear any pending interrupts */
+ USBx->GINTSTS = 0xFFFFFFFF;
+
+
+ if(USBx == USB_OTG_FS)
+ {
+ /* set Rx FIFO size */
+ USBx->GRXFSIZ = (uint32_t )0x80;
+ USBx->DIEPTXF0_HNPTXFSIZ = (uint32_t )(((0x60 << 16)& USB_OTG_NPTXFD) | 0x80);
+ USBx->HPTXFSIZ = (uint32_t )(((0x40 << 16)& USB_OTG_HPTXFSIZ_PTXFD) | 0xE0);
+
+ }
+
+ else
+ {
+ /* set Rx FIFO size */
+ USBx->GRXFSIZ = (uint32_t )0x200;
+ USBx->DIEPTXF0_HNPTXFSIZ = (uint32_t )(((0x100 << 16)& USB_OTG_NPTXFD) | 0x200);
+ USBx->HPTXFSIZ = (uint32_t )(((0xE0 << 16)& USB_OTG_HPTXFSIZ_PTXFD) | 0x300);
+ }
+
+ /* Enable the common interrupts */
+ if (cfg.dma_enable == DISABLE)
+ {
+ USBx->GINTMSK |= USB_OTG_GINTMSK_RXFLVLM;
+ }
+
+ /* Enable interrupts matching to the Host mode ONLY */
+ USBx->GINTMSK |= (USB_OTG_GINTMSK_PRTIM | USB_OTG_GINTMSK_HCIM |\
+ USB_OTG_GINTMSK_SOFM |USB_OTG_GINTSTS_DISCINT|\
+ USB_OTG_GINTMSK_PXFRM_IISOOXFRM | USB_OTG_GINTMSK_WUIM);
+
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_InitFSLSPClkSel : Initializes the FSLSPClkSel field of the
+ * HCFG register on the PHY type and set the right frame interval
+ * @param USBx : Selected device
+ * @param freq : clock frequency
+ * This parameter can be one of the these values:
+ * HCFG_48_MHZ : Full Speed 48 MHz Clock
+ * HCFG_6_MHZ : Low Speed 6 MHz Clock
+ * @retval HAL status
+ */
+HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx , uint8_t freq)
+{
+ USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSPCS);
+ USBx_HOST->HCFG |= (freq & USB_OTG_HCFG_FSLSPCS);
+
+ if (freq == HCFG_48_MHZ)
+ {
+ USBx_HOST->HFIR = (uint32_t)48000;
+ }
+ else if (freq == HCFG_6_MHZ)
+ {
+ USBx_HOST->HFIR = (uint32_t)6000;
+ }
+ return HAL_OK;
+}
+
+/**
+* @brief USB_OTG_ResetPort : Reset Host Port
+ * @param USBx : Selected device
+ * @retval HAL status
+ * @note : (1)The application must wait at least 10 ms
+ * before clearing the reset bit.
+ */
+HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx)
+{
+ __IO uint32_t hprt0;
+
+ hprt0 = USBx_HPRT0;
+
+ hprt0 &= ~(USB_OTG_HPRT_PENA | USB_OTG_HPRT_PCDET |\
+ USB_OTG_HPRT_PENCHNG | USB_OTG_HPRT_POCCHNG );
+
+ USBx_HPRT0 = (USB_OTG_HPRT_PRST | hprt0);
+ HAL_Delay (10); /* See Note #1 */
+ USBx_HPRT0 = ((~USB_OTG_HPRT_PRST) & hprt0);
+ return HAL_OK;
+}
+
+/**
+ * @brief USB_DriveVbus : activate or de-activate vbus
+ * @param state : VBUS state
+ * This parameter can be one of the these values:
+ * 0 : VBUS Active
+ * 1 : VBUS Inactive
+ * @retval HAL status
+*/
+HAL_StatusTypeDef USB_DriveVbus (USB_OTG_GlobalTypeDef *USBx, uint8_t state)
+{
+ __IO uint32_t hprt0;
+
+ hprt0 = USBx_HPRT0;
+ hprt0 &= ~(USB_OTG_HPRT_PENA | USB_OTG_HPRT_PCDET |\
+ USB_OTG_HPRT_PENCHNG | USB_OTG_HPRT_POCCHNG );
+
+ if (((hprt0 & USB_OTG_HPRT_PPWR) == 0 ) && (state == 1 ))
+ {
+ USBx_HPRT0 = (USB_OTG_HPRT_PPWR | hprt0);
+ }
+ if (((hprt0 & USB_OTG_HPRT_PPWR) == USB_OTG_HPRT_PPWR) && (state == 0 ))
+ {
+ USBx_HPRT0 = ((~USB_OTG_HPRT_PPWR) & hprt0);
+ }
+ return HAL_OK;
+}
+
+/**
+ * @brief Return Host Core speed
+ * @param USBx : Selected device
+ * @retval speed : Host speed
+ * This parameter can be one of the these values:
+ * @arg USB_OTG_SPEED_HIGH: High speed mode
+ * @arg USB_OTG_SPEED_FULL: Full speed mode
+ * @arg USB_OTG_SPEED_LOW: Low speed mode
+ */
+uint32_t USB_GetHostSpeed (USB_OTG_GlobalTypeDef *USBx)
+{
+ __IO uint32_t hprt0;
+
+ hprt0 = USBx_HPRT0;
+ return ((hprt0 & USB_OTG_HPRT_PSPD) >> 17);
+}
+
+/**
+ * @brief Return Host Current Frame number
+ * @param USBx : Selected device
+ * @retval current frame number
+*/
+uint32_t USB_GetCurrentFrame (USB_OTG_GlobalTypeDef *USBx)
+{
+ return (USBx_HOST->HFNUM & USB_OTG_HFNUM_FRNUM);
+}
+
+/**
+ * @brief Initialize a host channel
+ * @param USBx : Selected device
+ * @param ch_num : Channel number
+ * This parameter can be a value from 1 to 15
+ * @param epnum : Endpoint number
+ * This parameter can be a value from 1 to 15
+ * @param dev_address : Current device address
+ * This parameter can be a value from 0 to 255
+ * @param speed : Current device speed
+ * This parameter can be one of the these values:
+ * @arg USB_OTG_SPEED_HIGH: High speed mode
+ * @arg USB_OTG_SPEED_FULL: Full speed mode
+ * @arg USB_OTG_SPEED_LOW: Low speed mode
+ * @param ep_type : Endpoint Type
+ * This parameter can be one of the these values:
+ * @arg EP_TYPE_CTRL: Control type
+ * @arg EP_TYPE_ISOC: Isochrounous type
+ * @arg EP_TYPE_BULK: Bulk type
+ * @arg EP_TYPE_INTR: Interrupt type
+ * @param mps : Max Packet Size
+ * This parameter can be a value from 0 to32K
+ * @retval HAL state
+ */
+HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx,
+ uint8_t ch_num,
+ uint8_t epnum,
+ uint8_t dev_address,
+ uint8_t speed,
+ uint8_t ep_type,
+ uint16_t mps)
+{
+
+ /* Clear old interrupt conditions for this host channel. */
+ USBx_HC(ch_num)->HCINT = 0xFFFFFFFF;
+
+ /* Enable channel interrupts required for this transfer. */
+ switch (ep_type)
+ {
+ case EP_TYPE_CTRL:
+ case EP_TYPE_BULK:
+
+ USBx_HC(ch_num)->HCINTMSK = USB_OTG_HCINTMSK_XFRCM |\
+ USB_OTG_HCINTMSK_STALLM |\
+ USB_OTG_HCINTMSK_TXERRM |\
+ USB_OTG_HCINTMSK_DTERRM |\
+ USB_OTG_HCINTMSK_AHBERR |\
+ USB_OTG_HCINTMSK_NAKM ;
+
+ if (epnum & 0x80)
+ {
+ USBx_HC(ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_BBERRM;
+ }
+ else
+ {
+ if(USBx != USB_OTG_FS)
+ {
+ USBx_HC(ch_num)->HCINTMSK |= (USB_OTG_HCINTMSK_NYET | USB_OTG_HCINTMSK_ACKM);
+ }
+ }
+ break;
+ case EP_TYPE_INTR:
+
+ USBx_HC(ch_num)->HCINTMSK = USB_OTG_HCINTMSK_XFRCM |\
+ USB_OTG_HCINTMSK_STALLM |\
+ USB_OTG_HCINTMSK_TXERRM |\
+ USB_OTG_HCINTMSK_DTERRM |\
+ USB_OTG_HCINTMSK_NAKM |\
+ USB_OTG_HCINTMSK_AHBERR |\
+ USB_OTG_HCINTMSK_FRMORM ;
+
+ if (epnum & 0x80)
+ {
+ USBx_HC(ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_BBERRM;
+ }
+
+ break;
+ case EP_TYPE_ISOC:
+
+ USBx_HC(ch_num)->HCINTMSK = USB_OTG_HCINTMSK_XFRCM |\
+ USB_OTG_HCINTMSK_ACKM |\
+ USB_OTG_HCINTMSK_AHBERR |\
+ USB_OTG_HCINTMSK_FRMORM ;
+
+ if (epnum & 0x80)
+ {
+ USBx_HC(ch_num)->HCINTMSK |= (USB_OTG_HCINTMSK_TXERRM | USB_OTG_HCINTMSK_BBERRM);
+ }
+ break;
+ }
+
+ /* Enable the top level host channel interrupt. */
+ USBx_HOST->HAINTMSK |= (1 << ch_num);
+
+ /* Make sure host channel interrupts are enabled. */
+ USBx->GINTMSK |= USB_OTG_GINTMSK_HCIM;
+
+ /* Program the HCCHAR register */
+ USBx_HC(ch_num)->HCCHAR = (((dev_address << 22) & USB_OTG_HCCHAR_DAD) |\
+ (((epnum & 0x7F)<< 11) & USB_OTG_HCCHAR_EPNUM)|\
+ ((((epnum & 0x80) == 0x80)<< 15) & USB_OTG_HCCHAR_EPDIR)|\
+ (((speed == HPRT0_PRTSPD_LOW_SPEED)<< 17) & USB_OTG_HCCHAR_LSDEV)|\
+ ((ep_type << 18) & USB_OTG_HCCHAR_EPTYP)|\
+ (mps & USB_OTG_HCCHAR_MPSIZ));
+
+ if (ep_type == EP_TYPE_INTR)
+ {
+ USBx_HC(ch_num)->HCCHAR |= USB_OTG_HCCHAR_ODDFRM ;
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Start a transfer over a host channel
+ * @param USBx : Selected device
+ * @param hc : pointer to host channel structure
+ * @param dma: USB dma enabled or disabled
+ * This parameter can be one of the these values:
+ * 0 : DMA feature not used
+ * 1 : DMA feature used
+ * @retval HAL state
+ */
+#if defined (__CC_ARM) /*!< ARM Compiler */
+#pragma O0
+#elif defined (__GNUC__) /*!< GNU Compiler */
+#pragma GCC optimize ("O0")
+#elif defined (__TASKING__) /*!< TASKING Compiler */
+#pragma optimize=0
+#endif /* __CC_ARM */
+HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc, uint8_t dma)
+{
+ uint8_t is_oddframe = 0;
+ uint16_t len_words = 0;
+ uint16_t num_packets = 0;
+ uint16_t max_hc_pkt_count = 256;
+
+ if((USBx != USB_OTG_FS) && (hc->speed == USB_OTG_SPEED_HIGH))
+ {
+ if((dma == 0) && (hc->do_ping == 1))
+ {
+ USB_DoPing(USBx, hc->ch_num);
+ return HAL_OK;
+ }
+ }
+
+ /* Compute the expected number of packets associated to the transfer */
+ if (hc->xfer_len > 0)
+ {
+ num_packets = (hc->xfer_len + hc->max_packet - 1) / hc->max_packet;
+
+ if (num_packets > max_hc_pkt_count)
+ {
+ num_packets = max_hc_pkt_count;
+ hc->xfer_len = num_packets * hc->max_packet;
+ }
+ }
+ else
+ {
+ num_packets = 1;
+ }
+ if (hc->ep_is_in)
+ {
+ hc->xfer_len = num_packets * hc->max_packet;
+ }
+
+
+
+ /* Initialize the HCTSIZn register */
+ USBx_HC(hc->ch_num)->HCTSIZ = (((hc->xfer_len) & USB_OTG_HCTSIZ_XFRSIZ)) |\
+ ((num_packets << 19) & USB_OTG_HCTSIZ_PKTCNT) |\
+ (((hc->data_pid) << 29) & USB_OTG_HCTSIZ_DPID);
+
+ if (dma)
+ {
+ /* xfer_buff MUST be 32-bits aligned */
+ USBx_HC(hc->ch_num)->HCDMA = (uint32_t)hc->xfer_buff;
+ }
+
+ is_oddframe = (USBx_HOST->HFNUM & 0x01) ? 0 : 1;
+ USBx_HC(hc->ch_num)->HCCHAR &= ~USB_OTG_HCCHAR_ODDFRM;
+ USBx_HC(hc->ch_num)->HCCHAR |= (is_oddframe << 29);
+
+ /* Set host channel enable */
+ USBx_HC(hc->ch_num)->HCCHAR &= ~USB_OTG_HCCHAR_CHDIS;
+ USBx_HC(hc->ch_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+
+ if (dma == 0) /* Slave mode */
+ {
+ if((hc->ep_is_in == 0) && (hc->xfer_len > 0))
+ {
+ switch(hc->ep_type)
+ {
+ /* Non periodic transfer */
+ case EP_TYPE_CTRL:
+ case EP_TYPE_BULK:
+
+ len_words = (hc->xfer_len + 3) / 4;
+
+ /* check if there is enough space in FIFO space */
+ if(len_words > (USBx->HNPTXSTS & 0xFFFF))
+ {
+ /* need to process data in nptxfempty interrupt */
+ USBx->GINTMSK |= USB_OTG_GINTMSK_NPTXFEM;
+ }
+ break;
+ /* Periodic transfer */
+ case EP_TYPE_INTR:
+ case EP_TYPE_ISOC:
+ len_words = (hc->xfer_len + 3) / 4;
+ /* check if there is enough space in FIFO space */
+ if(len_words > (USBx_HOST->HPTXSTS & 0xFFFF)) /* split the transfer */
+ {
+ /* need to process data in ptxfempty interrupt */
+ USBx->GINTMSK |= USB_OTG_GINTMSK_PTXFEM;
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Write packet into the Tx FIFO. */
+ USB_WritePacket(USBx, hc->xfer_buff, hc->ch_num, hc->xfer_len, 0);
+ }
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Read all host channel interrupts status
+ * @param USBx : Selected device
+ * @retval HAL state
+ */
+uint32_t USB_HC_ReadInterrupt (USB_OTG_GlobalTypeDef *USBx)
+{
+ return ((USBx_HOST->HAINT) & 0xFFFF);
+}
+
+/**
+ * @brief Halt a host channel
+ * @param USBx : Selected device
+ * @param hc_num : Host Channel number
+ * This parameter can be a value from 1 to 15
+ * @retval HAL state
+ */
+HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx , uint8_t hc_num)
+{
+ uint32_t count = 0;
+
+ /* Check for space in the request queue to issue the halt. */
+ if (((USBx_HC(hc_num)->HCCHAR) & (HCCHAR_CTRL << 18)) || ((USBx_HC(hc_num)->HCCHAR) & (HCCHAR_BULK << 18)))
+ {
+ USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHDIS;
+
+ if ((USBx->HNPTXSTS & 0xFFFF) == 0)
+ {
+ USBx_HC(hc_num)->HCCHAR &= ~USB_OTG_HCCHAR_CHENA;
+ USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+ USBx_HC(hc_num)->HCCHAR &= ~USB_OTG_HCCHAR_EPDIR;
+ do
+ {
+ if (++count > 1000)
+ {
+ break;
+ }
+ }
+ while ((USBx_HC(hc_num)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA);
+ }
+ else
+ {
+ USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+ }
+ }
+ else
+ {
+ USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHDIS;
+
+ if ((USBx_HOST->HPTXSTS & 0xFFFF) == 0)
+ {
+ USBx_HC(hc_num)->HCCHAR &= ~USB_OTG_HCCHAR_CHENA;
+ USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+ USBx_HC(hc_num)->HCCHAR &= ~USB_OTG_HCCHAR_EPDIR;
+ do
+ {
+ if (++count > 1000)
+ {
+ break;
+ }
+ }
+ while ((USBx_HC(hc_num)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA);
+ }
+ else
+ {
+ USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+ }
+ }
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Initiate Do Ping protocol
+ * @param USBx : Selected device
+ * @param hc_num : Host Channel number
+ * This parameter can be a value from 1 to 15
+ * @retval HAL state
+ */
+HAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx , uint8_t ch_num)
+{
+ uint8_t num_packets = 1;
+
+ USBx_HC(ch_num)->HCTSIZ = ((num_packets << 19) & USB_OTG_HCTSIZ_PKTCNT) |\
+ USB_OTG_HCTSIZ_DOPING;
+
+ /* Set host channel enable */
+ USBx_HC(ch_num)->HCCHAR &= ~USB_OTG_HCCHAR_CHDIS;
+ USBx_HC(ch_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
+
+ return HAL_OK;
+}
+
+/**
+ * @brief Stop Host Core
+ * @param USBx : Selected device
+ * @retval HAL state
+ */
+HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx)
+{
+ uint8_t i;
+ uint32_t count = 0;
+ uint32_t value;
+
+ USB_DisableGlobalInt(USBx);
+
+ /* Flush FIFO */
+ USB_FlushTxFifo(USBx, 0x10);
+ USB_FlushRxFifo(USBx);
+
+ /* Flush out any leftover queued requests. */
+ for (i = 0; i <= 15; i++)
+ {
+
+ value = USBx_HC(i)->HCCHAR ;
+ value |= USB_OTG_HCCHAR_CHDIS;
+ value &= ~USB_OTG_HCCHAR_CHENA;
+ value &= ~USB_OTG_HCCHAR_EPDIR;
+ USBx_HC(i)->HCCHAR = value;
+ }
+
+ /* Halt all channels to put them into a known state. */
+ for (i = 0; i <= 15; i++)
+ {
+
+ value = USBx_HC(i)->HCCHAR ;
+
+ value |= USB_OTG_HCCHAR_CHDIS;
+ value |= USB_OTG_HCCHAR_CHENA;
+ value &= ~USB_OTG_HCCHAR_EPDIR;
+
+ USBx_HC(i)->HCCHAR = value;
+ do
+ {
+ if (++count > 1000)
+ {
+ break;
+ }
+ }
+ while ((USBx_HC(i)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA);
+ }
+
+ /* Clear any pending Host interrups */
+ USBx_HOST->HAINT = 0xFFFFFFFF;
+ USBx->GINTSTS = 0xFFFFFFFF;
+ USB_EnableGlobalInt(USBx);
+ return HAL_OK;
+}
+/**
+ * @}
+ */
+
+#endif /* defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/